From 8b8ee17246568271baaf891cabf87683ef2f4178 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Thu, 12 Nov 2026 10:07:33 +0100 Subject: [PATCH 001/183] refactor: restore laravel 13 default configs for cache, filesystems and session --- config/cache.php | 130 +++++++++++++++++ config/filesystems.php | 39 ++--- config/session.php | 316 ++++++++++++++++++++++------------------- 3 files changed, 312 insertions(+), 173 deletions(-) create mode 100644 config/cache.php diff --git a/config/cache.php b/config/cache.php new file mode 100644 index 00000000..3e971d5f --- /dev/null +++ b/config/cache.php @@ -0,0 +1,130 @@ + env('CACHE_STORE', 'database'), + + /* + |-------------------------------------------------------------------------- + | Cache Stores + |-------------------------------------------------------------------------- + | + | Here you may define all of the cache "stores" for your application as + | well as their drivers. You may even define multiple stores for the + | same cache driver to group types of items stored in your caches. + | + | Supported drivers: "array", "database", "file", "memcached", + | "redis", "dynamodb", "storage", "octane", + | "session", "failover", "null" + | + */ + + 'stores' => [ + + 'array' => [ + 'driver' => 'array', + 'serialize' => false, + ], + + 'session' => [ + 'driver' => 'session', + 'key' => env('SESSION_CACHE_KEY', '_cache'), + ], + + 'database' => [ + 'driver' => 'database', + 'connection' => env('DB_CACHE_CONNECTION'), + 'table' => env('DB_CACHE_TABLE', 'cache'), + 'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'), + 'lock_table' => env('DB_CACHE_LOCK_TABLE'), + ], + + 'file' => [ + 'driver' => 'file', + 'path' => storage_path('framework/cache/data'), + 'lock_path' => storage_path('framework/cache/data'), + ], + + 'storage' => [ + 'driver' => 'storage', + 'disk' => env('CACHE_STORAGE_DISK'), + 'path' => env('CACHE_STORAGE_PATH', 'framework/cache/data'), + ], + + 'memcached' => [ + 'driver' => 'memcached', + 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'), + 'sasl' => [ + env('MEMCACHED_USERNAME'), + env('MEMCACHED_PASSWORD'), + ], + 'options' => [ + // Memcached::OPT_CONNECT_TIMEOUT => 2000, + ], + 'servers' => [ + [ + 'host' => env('MEMCACHED_HOST', '127.0.0.1'), + 'port' => env('MEMCACHED_PORT', 11211), + 'weight' => 100, + ], + ], + ], + + 'redis' => [ + 'driver' => 'redis', + 'connection' => env('REDIS_CACHE_CONNECTION', 'cache'), + 'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'), + ], + + 'dynamodb' => [ + 'driver' => 'dynamodb', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), + 'endpoint' => env('DYNAMODB_ENDPOINT'), + ], + + 'octane' => [ + 'driver' => 'octane', + ], + + 'failover' => [ + 'driver' => 'failover', + 'stores' => [ + 'database', + 'array', + ], + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Cache Key Prefix + |-------------------------------------------------------------------------- + | + | When utilizing the APC, database, memcached, Redis, and DynamoDB cache + | stores, there might be other applications using the same cache. For + | that reason, you may prefix every cache key to avoid collisions. + | + */ + + 'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')) . '-cache-'), + +]; diff --git a/config/filesystems.php b/config/filesystems.php index a4956fe7..4e5aea19 100644 --- a/config/filesystems.php +++ b/config/filesystems.php @@ -15,7 +15,7 @@ return [ | */ - 'default' => env('FILESYSTEM_DISK') ?: 'local', + 'default' => env('FILESYSTEM_DISK', 'local'), /* |-------------------------------------------------------------------------- @@ -32,22 +32,23 @@ return [ 'disks' => [ + 'local' => [ + 'driver' => 'local', + 'root' => storage_path('app/private'), + 'serve' => true, + 'throw' => false, + 'report' => false, + ], + 'public' => [ 'driver' => 'local', 'root' => storage_path('app/public'), - 'url' => rtrim((string) env('APP_URL', 'http://localhost'), '/') . '/storage', + 'url' => rtrim((string) env('APP_URL'), '/') . '/storage', 'visibility' => 'public', 'throw' => false, 'report' => false, ], - 'private' => [ - 'driver' => 'local', - 'root' => storage_path('app/private'), - 'visibility' => 'private', - 'throw' => false, - ], - 's3' => [ 'driver' => 's3', 'key' => env('AWS_ACCESS_KEY_ID'), @@ -61,26 +62,6 @@ return [ 'report' => false, ], - 'inco' => [ - 'driver' => 'local', - 'root' => storage_path('inco'), - 'visibility' => 'private', - 'throw' => true, - ], - - 'employees' => [ - 'driver' => 'local', - 'root' => storage_path('salaries'), - 'visibility' => 'private', - 'throw' => true, - ], - - 'regate' => [ - 'driver' => 'local', - 'root' => storage_path('orders/in'), - 'visibility' => 'private', - 'throw' => true, - ], ], /* diff --git a/config/session.php b/config/session.php index dcd58731..5db08ecc 100644 --- a/config/session.php +++ b/config/session.php @@ -6,186 +6,214 @@ use Illuminate\Support\Str; return [ - /** - * |-------------------------------------------------------------------------- - * | Default Session Driver - * |-------------------------------------------------------------------------- - * | - * | This option controls the default session "driver" that will be used on - * | requests. By default, we will use the lightweight native driver but - * | you may specify any of the other wonderful drivers provided here. - * | - * | Supported: "file", "cookie", "database", "apc", - * | "memcached", "redis", "dynamodb", "array" - * | + /* + |-------------------------------------------------------------------------- + | Default Session Driver + |-------------------------------------------------------------------------- + | + | This option determines the default session driver that is utilized for + | incoming requests. Laravel supports a variety of storage options to + | persist session data. Database storage is a great default choice. + | + | Supported: "file", "cookie", "database", "memcached", + | "redis", "dynamodb", "array" + | */ - 'driver' => env('SESSION_DRIVER') ?: 'file', - /** - * |-------------------------------------------------------------------------- - * | Session Lifetime - * |-------------------------------------------------------------------------- - * | - * | Here you may specify the number of minutes that you wish the session - * | to be allowed to remain idle before it expires. If you want them - * | to immediately expire on the browser closing, set that option. - * | + 'driver' => env('SESSION_DRIVER', 'database'), + + /* + |-------------------------------------------------------------------------- + | Session Lifetime + |-------------------------------------------------------------------------- + | + | Here you may specify the number of minutes that you wish the session + | to be allowed to remain idle before it expires. If you want them + | to expire immediately when the browser is closed then you may + | indicate that via the expire_on_close configuration option. + | */ - 'lifetime' => env('SESSION_LIFETIME', 120), - 'expire_on_close' => false, + 'lifetime' => (int) env('SESSION_LIFETIME', 120), - /** - * |-------------------------------------------------------------------------- - * | Session Encryption - * |-------------------------------------------------------------------------- - * | - * | This option allows you to easily specify that all of your session data - * | should be encrypted before it is stored. All encryption will be run - * | automatically by Laravel and you can use the Session like normal. - * | + 'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false), + + /* + |-------------------------------------------------------------------------- + | Session Encryption + |-------------------------------------------------------------------------- + | + | This option allows you to easily specify that all of your session data + | should be encrypted before it's stored. All encryption is performed + | automatically by Laravel and you may use the session like normal. + | */ - 'encrypt' => false, - /** - * |-------------------------------------------------------------------------- - * | Session File Location - * |-------------------------------------------------------------------------- - * | - * | When using the native session driver, we need a location where session - * | files may be stored. A default has been set for you but a different - * | location may be specified. This is only needed for file sessions. - * | + 'encrypt' => env('SESSION_ENCRYPT', false), + + /* + |-------------------------------------------------------------------------- + | Session File Location + |-------------------------------------------------------------------------- + | + | When utilizing the "file" session driver, the session files are placed + | on disk. The default storage location is defined here; however, you + | are free to provide another location where they should be stored. + | */ + 'files' => storage_path('framework/sessions'), - /** - * |-------------------------------------------------------------------------- - * | Session Database Connection - * |-------------------------------------------------------------------------- - * | - * | When using the "database" or "redis" session drivers, you may specify a - * | connection that should be used to manage these sessions. This should - * | correspond to a connection in your database configuration options. - * | + /* + |-------------------------------------------------------------------------- + | Session Database Connection + |-------------------------------------------------------------------------- + | + | When using the "database" or "redis" session drivers, you may specify a + | connection that should be used to manage these sessions. This should + | correspond to a connection in your database configuration options. + | */ + 'connection' => env('SESSION_CONNECTION'), - 'prefix' => env('SESSION_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_') . '_session'), - - /** - * |-------------------------------------------------------------------------- - * | Session Database Table - * |-------------------------------------------------------------------------- - * | - * | When using the "database" session driver, you may specify the table we - * | should use to manage the sessions. Of course, a sensible default is - * | provided for you; however, you are free to change this as needed. - * | + /* + |-------------------------------------------------------------------------- + | Session Database Table + |-------------------------------------------------------------------------- + | + | When using the "database" session driver, you may specify the table to + | be used to store sessions. Of course, a sensible default is defined + | for you; however, you're welcome to change this to another table. + | */ - 'table' => 'sessions', - /** - * |-------------------------------------------------------------------------- - * | Session Cache Store - * |-------------------------------------------------------------------------- - * | - * | While using one of the framework's cache driven session backends you may - * | list a cache store that should be used for these sessions. This value - * | must match with one of the application's configured cache "stores". - * | - * | Affects: "apc", "dynamodb", "memcached", "redis" - * | + 'table' => env('SESSION_TABLE', 'sessions'), + + /* + |-------------------------------------------------------------------------- + | Session Cache Store + |-------------------------------------------------------------------------- + | + | When using one of the framework's cache driven session backends, you may + | define the cache store which should be used to store the session data + | between requests. This must match one of your defined cache stores. + | + | Affects: "dynamodb", "memcached", "redis" + | */ + 'store' => env('SESSION_STORE'), - /** - * |-------------------------------------------------------------------------- - * | Session Sweeping Lottery - * |-------------------------------------------------------------------------- - * | - * | Some session drivers must manually sweep their storage location to get - * | rid of old sessions from storage. Here are the chances that it will - * | happen on a given request. By default, the odds are 2 out of 100. - * | + /* + |-------------------------------------------------------------------------- + | Session Sweeping Lottery + |-------------------------------------------------------------------------- + | + | Some session drivers must manually sweep their storage location to get + | rid of old sessions from storage. Here are the chances that it will + | happen on a given request. By default, the odds are 2 out of 100. + | */ + 'lottery' => [2, 100], - /** - * |-------------------------------------------------------------------------- - * | Session Cookie Name - * |-------------------------------------------------------------------------- - * | - * | Here you may change the name of the cookie used to identify a session - * | instance by ID. The name specified here will get used every time a - * | new session cookie is created by the framework for every driver. - * | + /* + |-------------------------------------------------------------------------- + | Session Cookie Name + |-------------------------------------------------------------------------- + | + | Here you may change the name of the session cookie that is created by + | the framework. Typically, you should not need to change this value + | since doing so does not grant a meaningful security improvement. + | */ + 'cookie' => env( 'SESSION_COOKIE', - Str::slug(env('APP_NAME', 'laravel'), '_') . '_session' + Str::snake((string) env('APP_NAME', 'laravel')) . '_session' ), - /** - * |-------------------------------------------------------------------------- - * | Session Cookie Path - * |-------------------------------------------------------------------------- - * | - * | The session cookie path determines the path for which the cookie will - * | be regarded as available. Typically, this will be the root path of - * | your application but you are free to change this when necessary. - * | + /* + |-------------------------------------------------------------------------- + | Session Cookie Path + |-------------------------------------------------------------------------- + | + | The session cookie path determines the path for which the cookie will + | be regarded as available. Typically, this will be the root path of + | your application, but you're free to change this when necessary. + | */ - 'path' => '/', - /** - * |-------------------------------------------------------------------------- - * | Session Cookie Domain - * |-------------------------------------------------------------------------- - * | - * | Here you may change the domain of the cookie used to identify a session - * | in your application. This will determine which domains the cookie is - * | available to in your application. A sensible default has been set. - * | + 'path' => env('SESSION_PATH', '/'), + + /* + |-------------------------------------------------------------------------- + | Session Cookie Domain + |-------------------------------------------------------------------------- + | + | This value determines the domain and subdomains the session cookie is + | available to. By default, the cookie will be available to the root + | domain and all subdomains. Typically, this shouldn't be changed. + | */ + 'domain' => env('SESSION_DOMAIN'), - /** - * |-------------------------------------------------------------------------- - * | HTTPS Only Cookies - * |-------------------------------------------------------------------------- - * | - * | By setting this option to true, session cookies will only be sent back - * | to the server if the browser has a HTTPS connection. This will keep - * | the cookie from being sent to you when it can't be done securely. - * | + /* + |-------------------------------------------------------------------------- + | HTTPS Only Cookies + |-------------------------------------------------------------------------- + | + | By setting this option to true, session cookies will only be sent back + | to the server if the browser has a HTTPS connection. This will keep + | the cookie from being sent to you when it can't be done securely. + | */ + 'secure' => env('SESSION_SECURE_COOKIE'), - /** - * |-------------------------------------------------------------------------- - * | HTTP Access Only - * |-------------------------------------------------------------------------- - * | - * | Setting this value to true will prevent JavaScript from accessing the - * | value of the cookie and the cookie will only be accessible through - * | the HTTP protocol. You are free to modify this option if needed. - * | + /* + |-------------------------------------------------------------------------- + | HTTP Access Only + |-------------------------------------------------------------------------- + | + | Setting this value to true will prevent JavaScript from accessing the + | value of the cookie and the cookie will only be accessible through + | the HTTP protocol. It's unlikely you should disable this option. + | */ - 'http_only' => true, - /** - * |-------------------------------------------------------------------------- - * | Same-Site Cookies - * |-------------------------------------------------------------------------- - * | - * | This option determines how your cookies behave when cross-site requests - * | take place, and can be used to mitigate CSRF attacks. By default, we - * | will set this value to "lax" since this is a secure default value. - * | - * | Supported: "lax", "strict", "none", null - * | + 'http_only' => env('SESSION_HTTP_ONLY', true), + + /* + |-------------------------------------------------------------------------- + | Same-Site Cookies + |-------------------------------------------------------------------------- + | + | This option determines how your cookies behave when cross-site requests + | take place, and can be used to mitigate CSRF attacks. By default, we + | will set this value to "lax" to permit secure cross-site requests. + | + | See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value + | + | Supported: "lax", "strict", "none", null + | */ - 'same_site' => 'lax', + + 'same_site' => env('SESSION_SAME_SITE', 'lax'), + + /* + |-------------------------------------------------------------------------- + | Partitioned Cookies + |-------------------------------------------------------------------------- + | + | Setting this value to true will tie the cookie to the top-level site for + | a cross-site context. Partitioned cookies are accepted by the browser + | when flagged "secure" and the Same-Site attribute is set to "none". + | + */ + + 'partitioned' => env('SESSION_PARTITIONED_COOKIE', false), ]; From 0ee0d7cce7c7aa587ea145ca32045438a2d0198a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Thu, 12 Nov 2026 10:46:37 +0100 Subject: [PATCH 002/183] refactor: update configuration files for improved structure - Added new database and queue configuration files. - Enhanced .env.example with additional environment variables. - Updated manifest.yaml for better deployment settings. --- .env.example | 33 ++++- config/database.php | 220 +++++++++++++++++++++++++++++ config/filesystems.php | 16 +++ config/queue.php | 132 +++++++++++++++++ manifest.yaml | 314 +++++++++++++++++++++++++++++------------ 5 files changed, 616 insertions(+), 99 deletions(-) create mode 100644 config/database.php create mode 100644 config/queue.php diff --git a/.env.example b/.env.example index 567a5608..e8ba3589 100644 --- a/.env.example +++ b/.env.example @@ -1,3 +1,4 @@ +# APP APP_NAME=Laravel APP_ENV=local APP_KEY= @@ -5,9 +6,11 @@ APP_DEBUG=true APP_URL=http://localhost APP_CURRENCY=EUR +# LOG LOG_CHANNEL=stack LOG_LEVEL=debug +# DB DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 @@ -15,14 +18,32 @@ DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD= +# BROADCAST, CACHE, QUEUE BROADCAST_DRIVER=log CACHE_STORE=file QUEUE_CONNECTION=sync -SESSION_DRIVER=file + +# SESSION +SESSION_STORE=file SESSION_LIFETIME=120 +SESSION_ENCRYPT=false +SESSION_SECURE_COOKIE=false +SESSION_PATH=/ +SESSION_DOMAIN= -FILESYSTEM_DISK=local +# S3 +AWS_ACCESS_KEY_ID=minioadmin +AWS_SECRET_ACCESS_KEY=minioadmin +AWS_DEFAULT_REGION=us-east-1 +AWS_BUCKET=ovoteam +AWS_ENDPOINT=http://127.0.0.1:9000 +AWS_URL=http://127.0.0.1:9000/ovoteam +AWS_USE_PATH_STYLE_ENDPOINT=true +# FILESYSTEM +FILESYSTEM_DISK=s3-public + +# MAIL MAIL_MAILER=log MAIL_SCHEME=null MAIL_HOST=127.0.0.1 @@ -40,10 +61,10 @@ CRM_ENDPOINT= CRM_TOKEN= CRM_PASSWORD= -# Sentry +# SENTRY SENTRY_LARAVEL_DSN= -# Matomo +# MATOMO MATOMO_SITE_ID= # UWIL ADMIN SECURE @@ -52,13 +73,13 @@ UWIL_ADMIN_SECURE_CIDR_LIST="" # - LIST SEPARATED WITH ',' (Optional) UWIL_ADMIN_SECURE_CIDR_PROJECT_ALLOWED_LIST="" -# Arcadia API +# ARCADIA API ARCADIA_API_ENDPOINT= ARCADIA_API_APIKEY= ARCADIA_API_SECRET= ARCADIA_API_IGNORE_SELF_SIGNED_CERT=false -# Serial Caster +# SERIAL CASTER SERIAL_CASTER_SEED=12345 # LDC diff --git a/config/database.php b/config/database.php new file mode 100644 index 00000000..9430ac4a --- /dev/null +++ b/config/database.php @@ -0,0 +1,220 @@ + env('DB_CONNECTION', 'sqlite'), + + /* + |-------------------------------------------------------------------------- + | Database Connections + |-------------------------------------------------------------------------- + | + | Below are all of the database connections defined for your application. + | An example configuration is provided for each database system which + | is supported by Laravel. You're free to add / remove connections. + | + */ + + 'connections' => [ + + 'sqlite' => [ + 'driver' => 'sqlite', + 'url' => env('DB_URL'), + 'database' => env('DB_DATABASE', database_path('database.sqlite')), + 'prefix' => '', + 'prefix_indexes' => null, + 'mask_bindings_in_exception_messages' => env('DB_MASK_BINDINGS', false), + 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true), + 'busy_timeout' => null, + 'journal_mode' => null, + 'synchronous' => null, + 'transaction_mode' => 'DEFERRED', + 'pragmas' => [], + ], + + 'mysql' => [ + 'driver' => 'mysql', + 'url' => env('DB_URL'), + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', '3306'), + 'database' => env('DB_DATABASE', 'laravel'), + 'username' => env('DB_USERNAME', 'root'), + 'password' => env('DB_PASSWORD', ''), + 'unix_socket' => env('DB_SOCKET', ''), + 'charset' => env('DB_CHARSET', 'utf8mb4'), + 'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'), + 'prefix' => '', + 'prefix_indexes' => true, + 'mask_bindings_in_exception_messages' => env('DB_MASK_BINDINGS', false), + 'strict' => true, + 'engine' => null, + 'options' => extension_loaded('pdo_mysql') ? array_filter([ + Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), + ]) : [], + ], + + 'mariadb' => [ + 'driver' => 'mariadb', + 'url' => env('DB_URL'), + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', '3306'), + 'database' => env('DB_DATABASE', 'laravel'), + 'username' => env('DB_USERNAME', 'root'), + 'password' => env('DB_PASSWORD', ''), + 'unix_socket' => env('DB_SOCKET', ''), + 'charset' => env('DB_CHARSET', 'utf8mb4'), + 'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'), + 'prefix' => '', + 'prefix_indexes' => true, + 'mask_bindings_in_exception_messages' => env('DB_MASK_BINDINGS', false), + 'strict' => true, + 'engine' => null, + 'options' => extension_loaded('pdo_mysql') ? array_filter([ + Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), + ]) : [], + ], + + 'pgsql' => [ + 'driver' => 'pgsql', + 'url' => env('DB_URL'), + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', '5432'), + 'database' => env('DB_DATABASE', 'laravel'), + 'username' => env('DB_USERNAME', 'root'), + 'password' => env('DB_PASSWORD', ''), + 'charset' => env('DB_CHARSET', 'utf8'), + 'prefix' => '', + 'prefix_indexes' => true, + 'mask_bindings_in_exception_messages' => env('DB_MASK_BINDINGS', false), + 'search_path' => 'public', + 'sslmode' => 'prefer', + 'pooled' => env('DB_POOLED', false), + 'direct' => array_filter([ + 'host' => env('DB_DIRECT_HOST'), + 'port' => env('DB_DIRECT_PORT'), + 'username' => env('DB_DIRECT_USERNAME'), + 'password' => env('DB_DIRECT_PASSWORD'), + 'sslmode' => env('DB_DIRECT_SSLMODE'), + ]), + ], + + 'sqlsrv' => [ + 'driver' => 'sqlsrv', + 'url' => env('DB_URL'), + 'host' => env('DB_HOST', 'localhost'), + 'port' => env('DB_PORT', '1433'), + 'database' => env('DB_DATABASE', 'laravel'), + 'username' => env('DB_USERNAME', 'root'), + 'password' => env('DB_PASSWORD', ''), + 'charset' => env('DB_CHARSET', 'utf8'), + 'prefix' => '', + 'prefix_indexes' => true, + 'mask_bindings_in_exception_messages' => env('DB_MASK_BINDINGS', false), + // 'encrypt' => env('DB_ENCRYPT', 'yes'), + // 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'), + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Migration Repository Table + |-------------------------------------------------------------------------- + | + | This table keeps track of all the migrations that have already run for + | your application. Using this information, we can determine which of + | the migrations on disk haven't actually been run on the database. + | + */ + + 'migrations' => [ + 'table' => 'migrations', + 'update_date_on_publish' => true, + ], + + /* + |-------------------------------------------------------------------------- + | Redis Databases + |-------------------------------------------------------------------------- + | + | Redis is an open source, fast, and advanced key-value store that also + | provides a richer body of commands than a typical key-value system + | such as Memcached. You may define your connection settings here. + | + */ + + 'redis' => [ + + 'client' => env('REDIS_CLIENT', 'phpredis'), + + 'options' => [ + 'cluster' => env('REDIS_CLUSTER', 'redis'), + 'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel'))), + 'persistent' => env('REDIS_PERSISTENT', false), + ], + + 'default' => [ + 'url' => env('REDIS_URL'), + 'host' => env('REDIS_HOST', '127.0.0.1'), + 'username' => env('REDIS_USERNAME'), + 'password' => env('REDIS_PASSWORD'), + 'port' => env('REDIS_PORT', '6379'), + 'database' => env('REDIS_DB', '0'), + 'scheme' => env('REDIS_SCHEME', 'tcp'), + 'prefix' => env('REDIS_DB_PREFIX', env('REDIS_PREFIX', 'ovoteam') . ':database:'), + 'max_retries' => env('REDIS_MAX_RETRIES', 3), + 'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'), + 'backoff_base' => env('REDIS_BACKOFF_BASE', 100), + 'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000), + ], + + 'cache' => [ + 'url' => env('REDIS_URL'), + 'host' => env('REDIS_HOST', '127.0.0.1'), + 'username' => env('REDIS_USERNAME'), + 'password' => env('REDIS_PASSWORD'), + 'port' => env('REDIS_PORT', '6379'), + 'database' => env('REDIS_CACHE_DB', '1'), + 'scheme' => env('REDIS_SCHEME', 'tcp'), + 'prefix' => env('REDIS_CACHE_DB_PREFIX', env('REDIS_PREFIX', 'ovoteam') . ':cache:'), + 'max_retries' => env('REDIS_MAX_RETRIES', 3), + 'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'), + 'backoff_base' => env('REDIS_BACKOFF_BASE', 100), + 'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000), + ], + + 'session' => [ + 'url' => env('REDIS_URL'), + 'host' => env('REDIS_HOST', '127.0.0.1'), + 'username' => env('REDIS_USERNAME'), + 'password' => env('REDIS_PASSWORD'), + 'port' => env('REDIS_PORT', '6379'), + 'database' => env('REDIS_SESSION_DB', '0'), + 'scheme' => env('REDIS_SCHEME', 'tcp'), + 'prefix' => env('REDIS_SESSION_DB_PREFIX', env('REDIS_PREFIX', 'ovoteam') . ':session:'), + 'max_retries' => env('REDIS_MAX_RETRIES', 3), + 'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'), + 'backoff_base' => env('REDIS_BACKOFF_BASE', 100), + 'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000), + ], + + ], + +]; diff --git a/config/filesystems.php b/config/filesystems.php index 4e5aea19..72e4cb81 100644 --- a/config/filesystems.php +++ b/config/filesystems.php @@ -62,6 +62,22 @@ return [ 'report' => false, ], + 's3-public' => [ + 'driver' => 'scoped', + 'disk' => 's3', + 'prefix' => 'public', + 'visibility' => 'public', + 'throw' => false, + ], + + 's3-private' => [ + 'driver' => 'scoped', + 'disk' => 's3', + 'prefix' => 'private', + 'visibility' => 'private', + 'throw' => false, + ], + ], /* diff --git a/config/queue.php b/config/queue.php new file mode 100644 index 00000000..771a3362 --- /dev/null +++ b/config/queue.php @@ -0,0 +1,132 @@ + env('QUEUE_CONNECTION', 'database'), + + /* + |-------------------------------------------------------------------------- + | Queue Connections + |-------------------------------------------------------------------------- + | + | Here you may configure the connection options for every queue backend + | used by your application. An example configuration is provided for + | each backend supported by Laravel. You're also free to add more. + | + | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", + | "deferred", "failover", "null" + | + */ + + 'connections' => [ + + 'sync' => [ + 'driver' => 'sync', + ], + + 'database' => [ + 'driver' => 'database', + 'connection' => env('DB_QUEUE_CONNECTION'), + 'table' => env('DB_QUEUE_TABLE', 'jobs'), + 'queue' => env('DB_QUEUE', 'default'), + 'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90), + 'after_commit' => false, + ], + + 'beanstalkd' => [ + 'driver' => 'beanstalkd', + 'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'), + 'queue' => env('BEANSTALKD_QUEUE', 'default'), + 'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90), + 'block_for' => 0, + 'after_commit' => false, + ], + + 'sqs' => [ + 'driver' => 'sqs', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), + 'queue' => env('SQS_QUEUE', 'default'), + 'suffix' => env('SQS_SUFFIX'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'after_commit' => false, + 'overflow' => [ + 'enabled' => env('SQS_OVERFLOW_ENABLED', false), + 'store' => env('SQS_OVERFLOW_STORE'), + 'always' => false, + 'delete_after_processing' => true, + 'flush_on_clear' => env('SQS_OVERFLOW_FLUSH_ON_CLEAR', false), + ], + ], + + 'redis' => [ + 'driver' => 'redis', + 'connection' => env('REDIS_QUEUE_CONNECTION', 'default'), + 'queue' => env('REDIS_QUEUE', 'default'), + 'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90), + 'block_for' => null, + 'after_commit' => false, + ], + + 'deferred' => [ + 'driver' => 'deferred', + ], + + 'failover' => [ + 'driver' => 'failover', + 'connections' => [ + 'database', + 'deferred', + ], + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Job Batching + |-------------------------------------------------------------------------- + | + | The following options configure the database and table that store job + | batching information. These options can be updated to any database + | connection and table which has been defined by your application. + | + */ + + 'batching' => [ + 'database' => env('DB_CONNECTION', 'sqlite'), + 'table' => 'job_batches', + ], + + /* + |-------------------------------------------------------------------------- + | Failed Queue Jobs + |-------------------------------------------------------------------------- + | + | These options configure the behavior of failed queue job logging so you + | can control how and where failed jobs are stored. Laravel ships with + | support for storing failed jobs in a simple file or in a database. + | + | Supported drivers: "database-uuids", "dynamodb", "file", "null" + | + */ + + 'failed' => [ + 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), + 'database' => env('DB_CONNECTION', 'sqlite'), + 'table' => 'failed_jobs', + ], + +]; diff --git a/manifest.yaml b/manifest.yaml index 65ea3535..08864f07 100644 --- a/manifest.yaml +++ b/manifest.yaml @@ -3,81 +3,151 @@ kind: ConfigMap metadata: name: ${CI_PROJECT_PATH_SLUG}-config-map data: - APP_NAME: "${APP_APP_NAME}" + APP_CURRENCY: "${APP_APP_CURRENCY}" + APP_DEBUG: "${APP_APP_DEBUG}" APP_ENV: "${APP_APP_ENV}" APP_KEY: "${APP_APP_KEY}" - APP_DEBUG: "${APP_APP_DEBUG}" + APP_MAINTENANCE_DRIVER: "cache" + APP_MAINTENANCE_STORE: "redis" + APP_NAME: "${APP_APP_NAME}" APP_URL: "https://${REDIRECT}${APP_DOMAIN}" - APP_CURRENCY: "${APP_APP_CURRENCY}" - LOG_CHANNEL: "k8s" + ARCADIA_API_APIKEY: "${APP_ARCADIA_API_APIKEY}" + ARCADIA_API_ENDPOINT: "${APP_ARCADIA_API_ENDPOINT}" + ARCADIA_API_SECRET: "${APP_ARCADIA_API_SECRET}" + AWS_ACCESS_KEY_ID: ${APP_OVH_S3_ACCESS_KEY_ID} + AWS_BUCKET: ${APP_OVH_S3_BUCKET} + AWS_DEFAULT_REGION: ${APP_GLOBAL_OVH_S3_REGION} + AWS_ENDPOINT: ${APP_GLOBAL_OVH_S3_ENDPOINT} + AWS_SECRET_ACCESS_KEY: ${APP_OVH_S3_SECRET_ACCESS_KEY} + AWS_URL: "${APP_OVH_S3_URL}" + AWS_USE_PATH_STYLE_ENDPOINT: "true" + CACHE_PREFIX: "" CACHE_STORE: "${APP_CACHE_STORE}" - QUEUE_CONNECTION: "${APP_QUEUE_CONNECTION}" - SESSION_DRIVER: "${APP_SESSION_DRIVER}" - FILESYSTEM_DISK: "${APP_FILESYSTEM_DISK}" - DB_HOST: "${APP_GLOBAL_OVH_MYSQL_HOST}" - DB_PORT: "${APP_GLOBAL_OVH_MYSQL_PORT}" - DB_DATABASE: "${APP_DB_DATABASE}" + CRM_ENDPOINT: "${APP_CRM_ENDPOINT}" + CRM_PASSWORD: "${APP_CRM_PASSWORD}" + CRM_TOKEN: "${APP_CRM_TOKEN}" DB_CONNECTION: "mysql" - DB_USERNAME: "${APP_DB_USERNAME}" + DB_DATABASE: "${APP_DB_DATABASE}" + DB_HOST: "${APP_GLOBAL_OVH_MYSQL_HOST}" DB_PASSWORD: "${APP_DB_PASSWORD}" - MAIL_MAILER: "${APP_MAIL_MAILER}" - MAIL_HOST: "${APP_MAIL_HOST}" - MAIL_PORT: "${APP_MAIL_PORT}" - MAIL_USERNAME: "${APP_MAIL_USERNAME}" - MAIL_PASSWORD: "${APP_MAIL_PASSWORD}" + DB_PORT: "${APP_GLOBAL_OVH_MYSQL_PORT}" + DB_USERNAME: "${APP_DB_USERNAME}" + FILESYSTEM_DISK: "${APP_FILESYSTEM_DISK}" + LDC_HEADQUARTERS_PHONE_RECEPTION: "${APP_LDC_HEADQUARTERS_PHONE_RECEPTION}" + LOG_CHANNEL: "k8s" MAIL_ENCRYPTION: "${APP_MAIL_ENCRYPTION}" - MAIL_SCHEME: "${APP_MAIL_SCHEME}" MAIL_FROM_ADDRESS: "${APP_MAIL_FROM_ADDRESS}" MAIL_FROM_NAME: "${APP_APP_NAME}" + MAIL_HOST: "${APP_MAIL_HOST}" + MAIL_MAILER: "${APP_MAIL_MAILER}" + MAIL_PASSWORD: "${APP_MAIL_PASSWORD}" + MAIL_PORT: "${APP_MAIL_PORT}" + MAIL_SCHEME: "${APP_MAIL_SCHEME}" MAIL_TO_CONTACT: "${APP_MAIL_TO_CONTACT}" MAIL_TO_REGATE: "${APP_MAIL_TO_REGATE}" - SENTRY_LARAVEL_DSN: "${APP_SENTRY_LARAVEL_DSN}" - CRM_ENDPOINT: "${APP_CRM_ENDPOINT}" - CRM_TOKEN: "${APP_CRM_TOKEN}" - CRM_PASSWORD: "${APP_CRM_PASSWORD}" + MAIL_USERNAME: "${APP_MAIL_USERNAME}" MATOMO_SITE_ID: "${APP_MATOMO_SITE_ID}" - UWIL_ADMIN_SECURE_CIDR_LIST: "${APP_GLOBAL_UWIL_ADMIN_SECURE_CIDR_LIST}" - ARCADIA_API_ENDPOINT: "${APP_ARCADIA_API_ENDPOINT}" - ARCADIA_API_APIKEY: "${APP_ARCADIA_API_APIKEY}" - ARCADIA_API_SECRET: "${APP_ARCADIA_API_SECRET}" + QUEUE_CONNECTION: "database" + REDIS_CLIENT: "phpredis" + REDIS_HOST: "${APP_GLOBAL_OVH_REDIS_HOST}" + REDIS_PASSWORD: "${APP_REDIS_PASSWORD}" + REDIS_PORT: "${APP_GLOBAL_OVH_REDIS_PORT}" + REDIS_PREFIX: "${APP_REDIS_PREFIX}" + REDIS_SCHEME: "${APP_GLOBAL_OVH_REDIS_SCHEME}" + REDIS_USERNAME: "${APP_REDIS_USERNAME}" + SENTRY_LARAVEL_DSN: "${APP_SENTRY_LARAVEL_DSN}" SERIAL_CASTER_SEED: "${APP_SERIAL_CASTER_SEED}" - LDC_HEADQUARTERS_PHONE_RECEPTION: "${APP_LDC_HEADQUARTERS_PHONE_RECEPTION}" ---- -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: ${CI_PROJECT_PATH_SLUG}-pvc-storage -spec: - storageClassName: "csi-cinder-classic" - accessModes: - - ReadWriteOnce - resources: - requests: - storage: $APP_PVC_SIZE + SESSION_CONNECTION: "${APP_SESSION_CONNECTION}" + SESSION_DRIVER: "${APP_SESSION_DRIVER}" + UWIL_ADMIN_SECURE_CIDR_LIST: "${APP_GLOBAL_UWIL_ADMIN_SECURE_CIDR_LIST}" --- apiVersion: apps/v1 kind: Deployment metadata: name: ${CI_PROJECT_PATH_SLUG}-deployment + labels: + app: ${CI_PROJECT_PATH_SLUG}-app spec: - replicas: 1 selector: matchLabels: app: ${CI_PROJECT_PATH_SLUG}-app + strategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 0 + maxSurge: 1 template: metadata: labels: app: ${CI_PROJECT_PATH_SLUG}-app spec: + securityContext: + runAsUser: 82 + runAsGroup: 82 + fsGroup: 82 + fsGroupChangePolicy: OnRootMismatch + terminationGracePeriodSeconds: 30 + imagePullSecrets: + - name: docker-registry-credentials + affinity: + podAntiAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - labelSelector: + matchExpressions: + - key: app + operator: In + values: + - ${CI_PROJECT_PATH_SLUG}-app + topologyKey: kubernetes.io/hostname + namespaces: + - ${KUBE_NAMESPACE} + volumes: + - name: laravel-cache + emptyDir: {} + - name: laravel-views + emptyDir: {} containers: - name: ${CI_PROJECT_PATH_SLUG}-container image: $IMAGE_TAG + imagePullPolicy: IfNotPresent env: - name: XDG_CONFIG_HOME # For tinker value: /tmp envFrom: - configMapRef: name: ${CI_PROJECT_PATH_SLUG}-config-map + ports: + - name: http + containerPort: 80 + protocol: TCP + volumeMounts: + - name: laravel-cache + mountPath: /app/srcs/bootstrap/cache + - name: laravel-views + mountPath: /app/srcs/storage/framework/views + readinessProbe: + httpGet: + path: /up + port: http + initialDelaySeconds: 10 + periodSeconds: 10 + timeoutSeconds: 3 + failureThreshold: 3 + livenessProbe: + httpGet: + path: /up + port: http + initialDelaySeconds: 30 + periodSeconds: 20 + timeoutSeconds: 3 + failureThreshold: 3 + startupProbe: + httpGet: + path: /up + port: http + periodSeconds: 5 + timeoutSeconds: 3 + failureThreshold: 24 resources: limits: cpu: "${APP_CI_CPU_LIMIT}" @@ -85,9 +155,11 @@ spec: requests: cpu: "${APP_CI_CPU_REQUEST}" memory: "${APP_CI_MEMORY_REQUEST}" - volumeMounts: - - name: storage - mountPath: /app/srcs/storage + securityContext: + # TODO : valider le POC + # readOnlyRootFilesystem: true + # TODO : a priori incompatible avec PVC + # allowPrivilegeEscalation: false - name: ${CI_PROJECT_PATH_SLUG}-queue-worker image: $IMAGE_TAG lifecycle: @@ -108,20 +180,11 @@ spec: envFrom: - configMapRef: name: ${CI_PROJECT_PATH_SLUG}-config-map - volumeMounts: - - name: storage - mountPath: /app/srcs/storage - imagePullSecrets: - - name: docker-registry-credentials - securityContext: - runAsUser: 82 - runAsGroup: 82 - fsGroup: 82 - fsGroupChangePolicy: "OnRootMismatch" - volumes: - - name: storage - persistentVolumeClaim: - claimName: ${CI_PROJECT_PATH_SLUG}-pvc-storage + securityContext: + # TODO : valider le POC + # readOnlyRootFilesystem: true + # TODO : a priori incompatible avec PVC + # allowPrivilegeEscalation: false --- apiVersion: v1 kind: Service @@ -131,8 +194,10 @@ spec: selector: app: ${CI_PROJECT_PATH_SLUG}-app ports: - - port: 80 - targetPort: 80 + - name: http + port: 80 + targetPort: http + protocol: TCP --- apiVersion: traefik.io/v1alpha1 kind: IngressRoute @@ -149,11 +214,57 @@ spec: - name: ${CI_PROJECT_PATH_SLUG}-service port: 80 middlewares: - - name: redirect-no-www-to-www + - name: redirect-no-www-to-www tls: secretName: ${CRT_TLS_NAME} --- +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: ${CI_PROJECT_PATH_SLUG}-hpa +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: ${CI_PROJECT_PATH_SLUG}-deployment + minReplicas: 1 + maxReplicas: 2 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 60 + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 75 + behavior: + scaleUp: + stabilizationWindowSeconds: 0 + selectPolicy: Max + policies: + - type: Percent + value: 100 + periodSeconds: 60 + - type: Pods + value: 2 + periodSeconds: 60 + scaleDown: + stabilizationWindowSeconds: 300 + selectPolicy: Min + policies: + - type: Percent + value: 25 + periodSeconds: 60 + - type: Pods + value: 1 + periodSeconds: 60 +--- apiVersion: batch/v1 kind: CronJob metadata: @@ -167,41 +278,58 @@ spec: spec: template: spec: - affinity: - podAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchExpressions: - - key: app - operator: In - values: - - ${CI_PROJECT_PATH_SLUG}-app - topologyKey: "kubernetes.io/hostname" - namespaces: [ $KUBE_NAMESPACE ] - containers: - - name: ${CI_PROJECT_PATH_SLUG}-scheduled - image: $IMAGE_TAG - imagePullPolicy: IfNotPresent - command: - - "php" - args: - - "artisan" - - "schedule:run" - envFrom: - - configMapRef: - name: ${CI_PROJECT_PATH_SLUG}-config-map - volumeMounts: - - name: storage - mountPath: /app/srcs/storage - imagePullSecrets: - - name: docker-registry-credentials - volumes: - - name: storage - persistentVolumeClaim: - claimName: ${CI_PROJECT_PATH_SLUG}-pvc-storage + restartPolicy: OnFailure securityContext: runAsUser: 82 runAsGroup: 82 fsGroup: 82 - fsGroupChangePolicy: "OnRootMismatch" - restartPolicy: OnFailure + fsGroupChangePolicy: OnRootMismatch + affinity: + podAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - labelSelector: + matchExpressions: + - key: app + operator: In + values: + - ${CI_PROJECT_PATH_SLUG}-app + topologyKey: kubernetes.io/hostname + namespaces: + - ${KUBE_NAMESPACE} + imagePullSecrets: + - name: docker-registry-credentials + volumes: + - name: laravel-cache + emptyDir: {} + - name: laravel-views + emptyDir: {} + containers: + - name: ${CI_PROJECT_PATH_SLUG}-scheduled + image: $IMAGE_TAG + imagePullPolicy: IfNotPresent + workingDir: /app/srcs + command: + - php + args: + - artisan + - schedule:run + envFrom: + - configMapRef: + name: ${CI_PROJECT_PATH_SLUG}-config-map + volumeMounts: + - name: laravel-cache + mountPath: /app/srcs/bootstrap/cache + - name: laravel-views + mountPath: /app/srcs/storage/framework/views + resources: + requests: + cpu: "${APP_CI_CPU_REQUEST}" + memory: "${APP_CI_MEMORY_REQUEST}" + limits: + cpu: "${APP_CI_CPU_LIMIT}" + memory: "${APP_CI_MEMORY_LIMIT}" + securityContext: + # TODO : valider le POC + # readOnlyRootFilesystem: true + # TODO : a priori incompatible avec PVC + # allowPrivilegeEscalation: false From 6bd1273f785dd87cf9b6147e2b06aa26bf606f31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Thu, 12 Nov 2026 11:13:15 +0100 Subject: [PATCH 003/183] refactor(config): update Redis scheme handling Ensure Redis scheme defaults to 'tcp' if not specified. --- config/database.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/config/database.php b/config/database.php index 9430ac4a..08e8f523 100644 --- a/config/database.php +++ b/config/database.php @@ -177,7 +177,7 @@ return [ 'password' => env('REDIS_PASSWORD'), 'port' => env('REDIS_PORT', '6379'), 'database' => env('REDIS_DB', '0'), - 'scheme' => env('REDIS_SCHEME', 'tcp'), + 'scheme' => env('REDIS_SCHEME') ?: 'tcp', 'prefix' => env('REDIS_DB_PREFIX', env('REDIS_PREFIX', 'ovoteam') . ':database:'), 'max_retries' => env('REDIS_MAX_RETRIES', 3), 'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'), @@ -192,7 +192,7 @@ return [ 'password' => env('REDIS_PASSWORD'), 'port' => env('REDIS_PORT', '6379'), 'database' => env('REDIS_CACHE_DB', '1'), - 'scheme' => env('REDIS_SCHEME', 'tcp'), + 'scheme' => env('REDIS_SCHEME') ?: 'tcp', 'prefix' => env('REDIS_CACHE_DB_PREFIX', env('REDIS_PREFIX', 'ovoteam') . ':cache:'), 'max_retries' => env('REDIS_MAX_RETRIES', 3), 'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'), @@ -206,8 +206,8 @@ return [ 'username' => env('REDIS_USERNAME'), 'password' => env('REDIS_PASSWORD'), 'port' => env('REDIS_PORT', '6379'), - 'database' => env('REDIS_SESSION_DB', '0'), - 'scheme' => env('REDIS_SCHEME', 'tcp'), + 'database' => env('REDIS_SESSION_DB', '2'), + 'scheme' => env('REDIS_SCHEME') ?: 'tcp', 'prefix' => env('REDIS_SESSION_DB_PREFIX', env('REDIS_PREFIX', 'ovoteam') . ':session:'), 'max_retries' => env('REDIS_MAX_RETRIES', 3), 'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'), From 1fc311ee7ece96e856bc2fb666948c77fcfc574f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Thu, 12 Nov 2026 11:13:25 +0100 Subject: [PATCH 004/183] refactor(env): update session and Redis configuration Improved clarity and consistency in the environment configuration. --- .env.example | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/.env.example b/.env.example index e8ba3589..bd4b52de 100644 --- a/.env.example +++ b/.env.example @@ -24,12 +24,22 @@ CACHE_STORE=file QUEUE_CONNECTION=sync # SESSION -SESSION_STORE=file +SESSION_DRIVER=file SESSION_LIFETIME=120 SESSION_ENCRYPT=false SESSION_SECURE_COOKIE=false SESSION_PATH=/ SESSION_DOMAIN= +SESSION_CONNECTION= + +# REDIS +REDIS_CLIENT=phpredis +REDIS_SCHEME=tcp +REDIS_HOST=127.0.0.1 +REDIS_USERNAME=null +REDIS_PASSWORD=null +REDIS_PORT=6379 +REDIS_PREFIX=cocotte # S3 AWS_ACCESS_KEY_ID=minioadmin From 30bfabfaf14203535bb653a3b274f3bf2f10f20d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Thu, 12 Nov 2026 11:30:56 +0100 Subject: [PATCH 005/183] chore: remove some dead code --- app/Lib/Helpers/ToolboxHelper.php | 260 ------------------ app/Lib/Helpers/ToolboxHelperCore.php | 43 --- lang/en/crud.php | 2 - lang/fr/crud.php | 2 - .../WithApp/Helpers/ToolboxHelpercoreTest.php | 32 --- 5 files changed, 339 deletions(-) diff --git a/app/Lib/Helpers/ToolboxHelper.php b/app/Lib/Helpers/ToolboxHelper.php index 85a3a1f1..d17ff34c 100644 --- a/app/Lib/Helpers/ToolboxHelper.php +++ b/app/Lib/Helpers/ToolboxHelper.php @@ -4,22 +4,12 @@ declare(strict_types=1); namespace App\Lib\Helpers; -use Illuminate\Contracts\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; -use Illuminate\Http\Request; -use Illuminate\Support\Arr; -use Illuminate\Support\Collection; -use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\File; -use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; use Illuminate\Validation\Rule; -use Illuminate\Validation\ValidationException; -use Propaganistas\LaravelPhone\PhoneNumber; -use Symfony\Component\Finder\SplFileInfo; -use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class ToolboxHelper extends ToolboxHelperCore { @@ -92,87 +82,6 @@ class ToolboxHelper extends ToolboxHelperCore ])->validate(); } - /** - * Assert That no Back Office url is present on txt - * - * @throws \Illuminate\Validation\ValidationException If url is a bo url. - */ - public static function assertNoInternalBoUrls(string $field, string $text): string - { - $routes = Route::getRoutes(); - - return self::replaceUrlsInText($text, function (string $url) use ($routes, $field): void { - $request = Request::create($url); - if (! self::isInternalHost($url)) { - return; - } - - if (trim($routes->match($request)->getPrefix() ?? '', '/') === 'bo') { - throw ValidationException::withMessages([ - $field => trans( - 'crud.libs.toolbox.assertNoInternalBoUrls', - ['attribute' => $field] - ), - ]); - } - }); - } - - /** - * Assert That only external url is present on txt - * - * @throws \Illuminate\Validation\ValidationException If url is a bo url. - */ - public static function assertNoInternalUrls(string $field, string $text): string - { - self::assertNoInternalBoUrls($field, $text); - $routes = Route::getRoutes(); - - return self::replaceUrlsInText($text, function (string $url) use ($routes, $field): void { - $request = Request::create($url); - $routes->match($request); - - if (! self::isInternalHost($url)) { - return; - } - - throw ValidationException::withMessages([ - $field => trans( - 'crud.libs.toolbox.assertNoInternalUrls', - ['attribute' => $field, 'appname' => Config::string('app.name')] - ), - ]); - }); - } - - private static function isInternalHost(string $url): bool - { - return \parse_url((string) Config::string('app.url'), \PHP_URL_HOST) === \parse_url($url, \PHP_URL_HOST); - } - - private static function replaceUrlsInText(string $text, callable $onMatchedUrl): string - { - $result = preg_replace_callback( - // phpcs:ignore Generic.Files.LineLength.TooLong - '/(?P(?:https?:\/\/)?(?:www\.)?[-a-zA-Z0-9@%._+~#=]{2,256}\.[a-z]{2,6}\b[-a-zA-Z0-9@:%_.+~#?&\/=]*)/', - function (array $matches) use ($onMatchedUrl): string { - $match = collect($matches)->first() ?? ''; - $url = (string) $match; - - try { - $onMatchedUrl($url); - } catch (NotFoundHttpException) { - return (string) $match; - } - - return (string) $match; - }, - $text - ); - - return is_string($result) ? $result : $text; - } - /** * Get original polyfill with autotranslate behavior */ @@ -194,78 +103,6 @@ class ToolboxHelper extends ToolboxHelperCore return $model->getOriginal($attribute); } - /** - * Dynamic model query - */ - public static function queryColumnWithLocales( - string $defaultLocale, - Builder $q, - string $column, - string $value - ): Builder { - $columnRegex = '/^[A-Za-z0-9_.]+$/'; - $localeRegex = '/^[A-Za-z0-9_-]+$/'; - - throw_unless(preg_match($columnRegex, $column), \InvalidArgumentException::class, 'Invalid column identifier.'); - - throw_unless(preg_match($localeRegex, $defaultLocale), \InvalidArgumentException::class, 'Invalid locale identifier.'); - - $currentLocale = app()->currentLocale(); - throw_unless(preg_match($localeRegex, $currentLocale), \InvalidArgumentException::class, 'Invalid locale identifier.'); - - /** @var array $locales */ - $locales = Config::array('app.locales', []); - $locales = Collection::make($locales) - ->filter(fn (string $locale) => (bool) preg_match($localeRegex, $locale)) - ->mapWithKeys(fn (string $locale) => [$locale => $locale]); - - if (! $locales->has($defaultLocale)) { - // * Remove default locale. - $locales->pull($defaultLocale); - } - if (! $locales->has($currentLocale)) { - // * Remove current locale. - $locales->pull($currentLocale); - } - - return $q->where(function (Builder $q) use ($defaultLocale, $currentLocale, $locales, $column, $value): void { - // * Query default locale - $q->where("{$column}->{$defaultLocale}", $value); - if ($defaultLocale !== $currentLocale) { - // * Query current locale - $q->orWhere("{$column}->{$currentLocale}", $value); - } - // * Query any other locale - $locales->each(fn (string $locale) => $q->orWhere( - "{$column}->{$locale}", - $value - )); - }); - } - - /** - * Generates an array from a dot separated string - * - * @param string $path The dot separated string to convert to an array. - * @param mixed $value The value to set at the end of the array. - * @param string $separator The separator used in the path (default is '.'). - * @return array The generated array. - */ - public static function dotStringToNestedArray(string $path, mixed $value, string $separator = '.'): array - { - throw_if($separator === '', \InvalidArgumentException::class, 'Separator cannot be an empty string.'); - - $arr = $value; - $keys = explode($separator, $path); - $keys = array_reverse($keys); - - foreach ($keys as $key) { - $arr = [$key => $arr]; - } - - return $arr; - } - /** * Validate picture * @@ -347,101 +184,4 @@ class ToolboxHelper extends ToolboxHelperCore $fail($yMessage); } } - - /** - * Fetch class list from a specific namespace - * - * @return array An array of classe namespaces - */ - public static function getClassesUsingNamespace(string $namespace): array - { - return collect(File::files(\app_path((string) Str::of($namespace)->replaceFirst('\App', '')))) - ->filter(fn (SplFileInfo $splFileInfo) => $splFileInfo->getExtension() === 'php') - ->map(fn (SplFileInfo $splFileInfo) => (string) Str::of($splFileInfo->getBasename()) - ->replace('.' . $splFileInfo->getExtension(), '')->prepend("{$namespace}\\"))->all(); - } - - /** - * Get all classes from a specific namespace that implement a specific interface - * - * @return array An array of classe namespaces - */ - public static function getClassesUsingInterface(string $namespace, string $interface): array - { - return Arr::where( - static::getClassesUsingNamespace($namespace), - fn (string $class_namespace) => \collect(class_implements($class_namespace, true) ?: [])->filter() - ->contains(fn (string $class_interface) => $class_interface === $interface) - ); - } - - /** - * Convert Hex color to RGB - * - * @return int[] - */ - public static function hexToRgb(string $hexcolor): array - { - $hexcolor = (string) str($hexcolor)->replaceStart('#', ''); - $r = (int) hexdec(substr($hexcolor, 0, 2)); - $g = (int) hexdec(substr($hexcolor, 2, 2)); - $b = (int) hexdec(substr($hexcolor, 4, 2)); - - return [$r, $g, $b]; - } - - /** - * Get text color contrast for a hex background color - * - * @return string "black" or "white" - */ - public static function getContrastYiq(string $hexcolor): string - { - [$r, $g, $b] = self::hexToRgb($hexcolor); - $yiq = (($r * 299) + ($g * 587) + ($b * 114)) / 1000; - - return ($yiq >= 128) ? 'black' : 'white'; - } - - /** - * Parse a phone number and return a PhoneNumber instance - * - * @param string $phoneNumber The phone number to parse - * @param string $countryCode The country code (default is 'FR' for France) - * @return \Propaganistas\LaravelPhone\PhoneNumber|null Returns the formatted phone number or null if invalid - */ - public static function parsePhoneNumber(string $phoneNumber, string $countryCode = 'FR'): ?PhoneNumber - { - $phoneNumber = new PhoneNumber($phoneNumber, $countryCode); - if (! $phoneNumber->isValid()) { - return null; - } - - return $phoneNumber; - } - - /** - * Convert an HTML string to plain text with proper word spacing. - * - * Replaces HTML tags with spaces, strips remaining tags, - * normalises whitespace and trims the result. - * - * @param string|null $html The HTML content to convert. - * @param int|null $limit Optional character limit (uses Str::limit). - */ - public static function htmlToText(?string $html, ?int $limit = null): string - { - if ($html === null || $html === '') { - return ''; - } - - $text = strip_tags((string) preg_replace('/<[^>]*>/', ' ', $html)); - $text = trim((string) preg_replace('/\s+/', ' ', $text)); - - if ($limit !== null) { - return Str::limit($text, $limit); - } - - return $text; - } } diff --git a/app/Lib/Helpers/ToolboxHelperCore.php b/app/Lib/Helpers/ToolboxHelperCore.php index 3e3e3d65..61463bde 100644 --- a/app/Lib/Helpers/ToolboxHelperCore.php +++ b/app/Lib/Helpers/ToolboxHelperCore.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace App\Lib\Helpers; -use App\Exceptions\Helpers\UnsupportedStructureConversionException; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Storage; @@ -118,48 +117,6 @@ abstract class ToolboxHelperCore return implode($replace, $parts); } - /** - * Convert deeply an object to array - * - * @return array - * - * @throws \App\Exceptions\Helpers\UnsupportedStructureConversionException If $input var is a scalar value. - */ - public static function objectToArray(mixed $input): array - { - if (! (is_object($input) || is_array($input))) { - throw UnsupportedStructureConversionException::fromType($input); - } - - $ret = (array) $input; - foreach ($ret as &$item) { - $item = (is_object($item) || is_array($item)) ? self::objectToArray($item) : $item; - } - - return $ret; - } - - /** - * Convert deeply an array to object - * - * @throws \App\Exceptions\Helpers\UnsupportedStructureConversionException If $input var is a scalar value. - */ - public static function arrayToObject(mixed $input): object - { - if (! (is_object($input) || is_array($input))) { - throw UnsupportedStructureConversionException::fromType($input); - } - - $ret = (object) $input; - $retArray = (array) $ret; - foreach ($retArray as &$item) { - $item = (is_object($item) || is_array($item)) ? self::arrayToObject($item) : $item; - } - unset($item); - - return (object) $retArray; - } - /** * Get the file full path */ diff --git a/lang/en/crud.php b/lang/en/crud.php index 45c028ba..25ee6472 100644 --- a/lang/en/crud.php +++ b/lang/en/crud.php @@ -55,8 +55,6 @@ return [ 'libs' => [ 'toolbox' => [ 'assertFieldIsUnique' => 'The :valeur of the field :attribut is already used', - 'assertNoInternalBoUrls' => ':attribute: It is forbidden to paste back-office uri in this field', - 'assertNoInternalUrls' => ':attribute: It is forbidden to paste a :appname url in this field.', ], ], diff --git a/lang/fr/crud.php b/lang/fr/crud.php index ef835118..64581205 100644 --- a/lang/fr/crud.php +++ b/lang/fr/crud.php @@ -57,8 +57,6 @@ return [ 'libs' => [ 'toolbox' => [ 'assertFieldIsUnique' => 'La :valeur du champ :attribut est déjà utilisée', - 'assertNoInternalBoUrls' => ':attribute : Il est interdit de coller l\'uri de back-office dans ce champ', - 'assertNoInternalUrls' => ':attribute : Il est interdit de coller une url de :appname dans ce champ.', ], ], diff --git a/tests/Integration/WithApp/Helpers/ToolboxHelpercoreTest.php b/tests/Integration/WithApp/Helpers/ToolboxHelpercoreTest.php index f069ca88..f2213ee1 100644 --- a/tests/Integration/WithApp/Helpers/ToolboxHelpercoreTest.php +++ b/tests/Integration/WithApp/Helpers/ToolboxHelpercoreTest.php @@ -2,7 +2,6 @@ declare(strict_types=1); -use App\Exceptions\Helpers\UnsupportedStructureConversionException; use Illuminate\Support\Facades\Storage; use Tests\Integration\WithApp\Helpers\ToolboxHelperCoreHarness; @@ -52,37 +51,6 @@ it('replaces with paired search and replace arrays', function (): void { expect($result)->toBe('X-Y'); }); -it('converts nested object to array and array to object', function (): void { - // GIVEN - $object = (object) [ - 'name' => 'demo', - 'nested' => (object) [ - 'value' => 10, - ], - ]; - - // WHEN - $asArray = ToolboxHelperCoreHarness::objectToArray($object); - $asObject = ToolboxHelperCoreHarness::arrayToObject($asArray); - - // THEN - expect($asArray)->toBe([ - 'name' => 'demo', - 'nested' => ['value' => 10], - ]) - ->and($asObject)->toBeObject() - ->and($asObject->nested)->toBeObject() - ->and($asObject->nested->value)->toBe(10); -}); - -it('throws for unsupported scalar structure conversion', function (): void { - // WHEN / THEN - expect(fn () => ToolboxHelperCoreHarness::objectToArray('x')) - ->toThrow(UnsupportedStructureConversionException::class) - ->and(fn () => ToolboxHelperCoreHarness::arrayToObject(12)) - ->toThrow(UnsupportedStructureConversionException::class); -}); - it('resolves full path and mime type without storage disk', function (): void { // GIVEN $tmpFile = tempnam(sys_get_temp_dir(), 'tbx-'); From ba077f88b41fdbc1ca90e5526800f3a48e7f16f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Thu, 12 Nov 2026 11:34:04 +0100 Subject: [PATCH 006/183] chore(dependencies): update AWS SDK and Flysystem packages Updated dependencies for AWS SDK and Flysystem to ensure compatibility and access to the latest features. --- composer.json | 2 + composer.lock | 1983 +++++++++++++++++++++++++++++-------------------- 2 files changed, 1190 insertions(+), 795 deletions(-) diff --git a/composer.json b/composer.json index 8496325d..359fed4b 100644 --- a/composer.json +++ b/composer.json @@ -17,6 +17,8 @@ "laravel/ui": "^4.6", "ldc/ldccrmv4client": "^4.0", "league/csv": "*", + "league/flysystem-aws-s3-v3": "^3.35", + "league/flysystem-path-prefixing": "^3.31", "maatwebsite/excel": "4.x-dev", "mews/purifier": "^3.3", "moneyphp/money": "^4.9", diff --git a/composer.lock b/composer.lock index 4a7eac48..faabd587 100644 --- a/composer.lock +++ b/composer.lock @@ -4,8 +4,159 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "3b4525dc0f29aff6e84ff0aebf6f015a", + "content-hash": "f01f8102e7b6581b3ec94ade3b273714", "packages": [ + { + "name": "aws/aws-crt-php", + "version": "v1.2.7", + "source": { + "type": "git", + "url": "https://github.com/awslabs/aws-crt-php.git", + "reference": "d71d9906c7bb63a28295447ba12e74723bd3730e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/awslabs/aws-crt-php/zipball/d71d9906c7bb63a28295447ba12e74723bd3730e", + "reference": "d71d9906c7bb63a28295447ba12e74723bd3730e", + "shasum": "" + }, + "require": { + "php": ">=5.5" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35||^5.6.3||^9.5", + "yoast/phpunit-polyfills": "^1.0" + }, + "suggest": { + "ext-awscrt": "Make sure you install awscrt native extension to use any of the functionality." + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "AWS SDK Common Runtime Team", + "email": "aws-sdk-common-runtime@amazon.com" + } + ], + "description": "AWS Common Runtime for PHP", + "homepage": "https://github.com/awslabs/aws-crt-php", + "keywords": [ + "amazon", + "aws", + "crt", + "sdk" + ], + "support": { + "issues": "https://github.com/awslabs/aws-crt-php/issues", + "source": "https://github.com/awslabs/aws-crt-php/tree/v1.2.7" + }, + "time": "2024-10-18T22:15:13+00:00" + }, + { + "name": "aws/aws-sdk-php", + "version": "3.403.4", + "source": { + "type": "git", + "url": "https://github.com/aws/aws-sdk-php.git", + "reference": "2d01207539928fe943a3f8d8981952b3655e2fc1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/2d01207539928fe943a3f8d8981952b3655e2fc1", + "reference": "2d01207539928fe943a3f8d8981952b3655e2fc1", + "shasum": "" + }, + "require": { + "aws/aws-crt-php": "^1.2.3", + "ext-json": "*", + "ext-pcre": "*", + "ext-simplexml": "*", + "guzzlehttp/guzzle": "^7.8.2 || ^8.0", + "guzzlehttp/promises": "^2.0.3 || ^3.0", + "guzzlehttp/psr7": "^2.6.3 || ^3.0", + "mtdowling/jmespath.php": "^2.9.1", + "php": ">=8.2", + "psr/http-message": "^1.0 || ^2.0", + "symfony/filesystem": "^v5.4.45 || ^v6.4.3 || ^v7.1.0 || ^v8.0.0" + }, + "require-dev": { + "andrewsville/php-token-reflection": "^1.4", + "aws/aws-php-sns-message-validator": "~1.0", + "behat/behat": "~3.0", + "composer/composer": "^2.7.8", + "dms/phpunit-arraysubset-asserts": "^v0.5.0", + "doctrine/cache": "~1.4", + "ext-dom": "*", + "ext-openssl": "*", + "ext-sockets": "*", + "phpunit/phpunit": "^10.0", + "psr/cache": "^2.0 || ^3.0", + "psr/simple-cache": "^2.0 || ^3.0", + "sebastian/comparator": "^1.2.3 || ^4.0 || ^5.0", + "yoast/phpunit-polyfills": "^2.0" + }, + "suggest": { + "aws/aws-php-sns-message-validator": "To validate incoming SNS notifications", + "doctrine/cache": "To use the DoctrineCacheAdapter", + "ext-curl": "To send requests using cURL", + "ext-openssl": "Allows working with CloudFront private distributions and verifying received SNS messages", + "ext-pcntl": "To use client-side monitoring", + "ext-sockets": "To use client-side monitoring" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "Aws\\": "src/" + }, + "exclude-from-classmap": [ + "src/data/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "Amazon Web Services", + "homepage": "https://aws.amazon.com" + } + ], + "description": "AWS SDK for PHP - Use Amazon Web Services in your PHP project", + "homepage": "https://aws.amazon.com/sdk-for-php", + "keywords": [ + "amazon", + "aws", + "cloud", + "dynamodb", + "ec2", + "glacier", + "s3", + "sdk" + ], + "support": { + "forum": "https://github.com/aws/aws-sdk-php/discussions", + "issues": "https://github.com/aws/aws-sdk-php/issues", + "source": "https://github.com/aws/aws-sdk-php/tree/3.403.4" + }, + "time": "2026-11-11T19:03:26+00:00" + }, { "name": "axlon/laravel-postal-code-validation", "version": "v3.10.0", @@ -284,16 +435,16 @@ }, { "name": "composer/semver", - "version": "3.5.1", + "version": "3.6.0", "source": { "type": "git", "url": "https://github.com/composer/semver.git", - "reference": "528948210cc46f967a4b98e83b19e76f2b504993" + "reference": "d92543b7ede9c4ec6b59853cefb061e39866d2cf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/composer/semver/zipball/528948210cc46f967a4b98e83b19e76f2b504993", - "reference": "528948210cc46f967a4b98e83b19e76f2b504993", + "url": "https://api.github.com/repos/composer/semver/zipball/d92543b7ede9c4ec6b59853cefb061e39866d2cf", + "reference": "d92543b7ede9c4ec6b59853cefb061e39866d2cf", "shasum": "" }, "require": { @@ -345,7 +496,7 @@ "support": { "irc": "ircs://irc.libera.chat:6697/composer", "issues": "https://github.com/composer/semver/issues", - "source": "https://github.com/composer/semver/tree/3.5.1" + "source": "https://github.com/composer/semver/tree/3.6.0" }, "funding": [ { @@ -357,7 +508,7 @@ "type": "github" } ], - "time": "2026-10-05T13:12:12+00:00" + "time": "2026-10-29T09:13:34+00:00" }, { "name": "dflydev/dot-access-data", @@ -506,23 +657,23 @@ }, { "name": "doctrine/inflector", - "version": "2.1.0", + "version": "2.1.1", "source": { "type": "git", "url": "https://github.com/doctrine/inflector.git", - "reference": "6d6c96277ea252fc1304627204c3d5e6e15faa3b" + "reference": "46351b6812b7b6d52b82c3efa5dfb786a198ec88" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/inflector/zipball/6d6c96277ea252fc1304627204c3d5e6e15faa3b", - "reference": "6d6c96277ea252fc1304627204c3d5e6e15faa3b", + "url": "https://api.github.com/repos/doctrine/inflector/zipball/46351b6812b7b6d52b82c3efa5dfb786a198ec88", + "reference": "46351b6812b7b6d52b82c3efa5dfb786a198ec88", "shasum": "" }, "require": { "php": "^7.2 || ^8.0" }, "require-dev": { - "doctrine/coding-standard": "^12.0 || ^13.0", + "doctrine/coding-standard": "^12.0 || ^14.0", "phpstan/phpstan": "^1.12 || ^2.0", "phpstan/phpstan-phpunit": "^1.4 || ^2.0", "phpstan/phpstan-strict-rules": "^1.6 || ^2.0", @@ -576,7 +727,7 @@ ], "support": { "issues": "https://github.com/doctrine/inflector/issues", - "source": "https://github.com/doctrine/inflector/tree/2.1.0" + "source": "https://github.com/doctrine/inflector/tree/2.1.1" }, "funding": [ { @@ -592,7 +743,7 @@ "type": "tidelift" } ], - "time": "2025-08-10T19:31:58+00:00" + "time": "2026-10-26T08:14:14+00:00" }, { "name": "doctrine/lexer", @@ -671,16 +822,16 @@ }, { "name": "dragonmantank/cron-expression", - "version": "v3.6.0", + "version": "v3.6.1", "source": { "type": "git", "url": "https://github.com/dragonmantank/cron-expression.git", - "reference": "d61a8a9604ec1f8c3d150d09db6ce98b32675013" + "reference": "4189372ffeff09bf14f731f67a9de90c7b413ebe" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/dragonmantank/cron-expression/zipball/d61a8a9604ec1f8c3d150d09db6ce98b32675013", - "reference": "d61a8a9604ec1f8c3d150d09db6ce98b32675013", + "url": "https://api.github.com/repos/dragonmantank/cron-expression/zipball/4189372ffeff09bf14f731f67a9de90c7b413ebe", + "reference": "4189372ffeff09bf14f731f67a9de90c7b413ebe", "shasum": "" }, "require": { @@ -691,8 +842,8 @@ }, "require-dev": { "phpstan/extension-installer": "^1.4.3", - "phpstan/phpstan": "^1.12.32|^2.1.31", - "phpunit/phpunit": "^8.5.48|^9.0" + "phpstan/phpstan": "^2.1.31", + "phpunit/phpunit": "^11.5.43 || ^12.4" }, "type": "library", "extra": { @@ -723,7 +874,7 @@ ], "support": { "issues": "https://github.com/dragonmantank/cron-expression/issues", - "source": "https://github.com/dragonmantank/cron-expression/tree/v3.6.0" + "source": "https://github.com/dragonmantank/cron-expression/tree/v3.6.1" }, "funding": [ { @@ -731,31 +882,31 @@ "type": "github" } ], - "time": "2025-10-31T18:51:33+00:00" + "time": "2026-10-19T17:53:57+00:00" }, { "name": "dxw/cidr", - "version": "v4.0.0", + "version": "v4.0.1", "source": { "type": "git", "url": "https://github.com/dxw/cidr.git", - "reference": "6c96a03163bdb513e6f3924bb1d48919bf510c6a" + "reference": "58d1e9f8452f21d577283e5ae88589effba01257" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/dxw/cidr/zipball/6c96a03163bdb513e6f3924bb1d48919bf510c6a", - "reference": "6c96a03163bdb513e6f3924bb1d48919bf510c6a", + "url": "https://api.github.com/repos/dxw/cidr/zipball/58d1e9f8452f21d577283e5ae88589effba01257", + "reference": "58d1e9f8452f21d577283e5ae88589effba01257", "shasum": "" }, "require": { "dxw/result": "^1.0", - "php": "^8.1", + "php": "^8.3", "phpseclib/phpseclib": "~3.0" }, "require-dev": { "dxw/php-cs-fixer-config": "^2.0", "kahlan/kahlan": "^5.2", - "vimeo/psalm": "^5.26" + "vimeo/psalm": "^6" }, "type": "library", "autoload": { @@ -778,31 +929,31 @@ "homepage": "https://github.com/dxw/cidr", "support": { "issues": "https://github.com/dxw/cidr/issues", - "source": "https://github.com/dxw/cidr/tree/v4.0.0" + "source": "https://github.com/dxw/cidr/tree/v4.0.1" }, - "time": "2026-09-30T09:40:52+00:00" + "time": "2026-10-26T10:29:12+00:00" }, { "name": "dxw/result", - "version": "v1.0.6", + "version": "v1.0.7", "source": { "type": "git", "url": "https://github.com/dxw/result.git", - "reference": "d554bb10f0cf74056ccd26526688e194652eef79" + "reference": "2e609e156d16627977a535a5b344946b52efb30c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/dxw/result/zipball/d554bb10f0cf74056ccd26526688e194652eef79", - "reference": "d554bb10f0cf74056ccd26526688e194652eef79", + "url": "https://api.github.com/repos/dxw/result/zipball/2e609e156d16627977a535a5b344946b52efb30c", + "reference": "2e609e156d16627977a535a5b344946b52efb30c", "shasum": "" }, "require": { - "php": "^7.4||^8.1" + "php": "^8.3" }, "require-dev": { "dxw/php-cs-fixer-config": "^2.1", "kahlan/kahlan": "^5.2", - "vimeo/psalm": "^4" + "vimeo/psalm": "^6" }, "type": "library", "autoload": { @@ -825,9 +976,9 @@ "homepage": "https://github.com/dxw/result", "support": { "issues": "https://github.com/dxw/result/issues", - "source": "https://github.com/dxw/result/tree/v1.0.6" + "source": "https://github.com/dxw/result/tree/v1.0.7" }, - "time": "2023-07-19T11:14:28+00:00" + "time": "2026-10-26T10:17:13+00:00" }, { "name": "egulias/email-validator", @@ -1083,16 +1234,16 @@ }, { "name": "giggsey/libphonenumber-for-php-lite", - "version": "9.0.41", + "version": "9.0.43", "source": { "type": "git", "url": "https://github.com/giggsey/libphonenumber-for-php-lite.git", - "reference": "6ffb41a259c950d6f4df5596e32917f631052910" + "reference": "e3c20f1eea133cb67b1f31ad86b0f4049c6fa4d8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/giggsey/libphonenumber-for-php-lite/zipball/6ffb41a259c950d6f4df5596e32917f631052910", - "reference": "6ffb41a259c950d6f4df5596e32917f631052910", + "url": "https://api.github.com/repos/giggsey/libphonenumber-for-php-lite/zipball/e3c20f1eea133cb67b1f31ad86b0f4049c6fa4d8", + "reference": "e3c20f1eea133cb67b1f31ad86b0f4049c6fa4d8", "shasum": "" }, "require": { @@ -1157,7 +1308,7 @@ "issues": "https://github.com/giggsey/libphonenumber-for-php-lite/issues", "source": "https://github.com/giggsey/libphonenumber-for-php-lite" }, - "time": "2026-10-08T08:51:54+00:00" + "time": "2026-11-06T09:59:40+00:00" }, { "name": "graham-campbell/result-type", @@ -1223,22 +1374,22 @@ }, { "name": "guzzlehttp/guzzle", - "version": "7.15.5", + "version": "7.16.1", "source": { "type": "git", "url": "https://github.com/guzzle/guzzle.git", - "reference": "ee80339fd9177ba44c49cdb653ff02a4d1106b9a" + "reference": "81755d989b3007ca7f88a069857553cd08e7dc2e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/guzzle/zipball/ee80339fd9177ba44c49cdb653ff02a4d1106b9a", - "reference": "ee80339fd9177ba44c49cdb653ff02a4d1106b9a", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/81755d989b3007ca7f88a069857553cd08e7dc2e", + "reference": "81755d989b3007ca7f88a069857553cd08e7dc2e", "shasum": "" }, "require": { "ext-json": "*", - "guzzlehttp/promises": "^2.5.3", - "guzzlehttp/psr7": "^2.13.1", + "guzzlehttp/promises": "^2.6", + "guzzlehttp/psr7": "^2.13.2", "php": "^7.2.5 || ^8.0", "psr/http-client": "^1.0", "symfony/deprecation-contracts": "^2.5 || ^3.0", @@ -1331,7 +1482,7 @@ ], "support": { "issues": "https://github.com/guzzle/guzzle/issues", - "source": "https://github.com/guzzle/guzzle/tree/7.15.5" + "source": "https://github.com/guzzle/guzzle/tree/7.16.1" }, "funding": [ { @@ -1347,20 +1498,20 @@ "type": "tidelift" } ], - "time": "2026-08-24T09:21:06+00:00" + "time": "2026-10-25T21:35:21+00:00" }, { "name": "guzzlehttp/promises", - "version": "2.5.3", + "version": "2.6.0", "source": { "type": "git", "url": "https://github.com/guzzle/promises.git", - "reference": "cde49999552d185d64715fe9c1f77a2aadd2f9f1" + "reference": "3d88c829bd5f13d13847b39067dbf09a60af2154" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/promises/zipball/cde49999552d185d64715fe9c1f77a2aadd2f9f1", - "reference": "cde49999552d185d64715fe9c1f77a2aadd2f9f1", + "url": "https://api.github.com/repos/guzzle/promises/zipball/3d88c829bd5f13d13847b39067dbf09a60af2154", + "reference": "3d88c829bd5f13d13847b39067dbf09a60af2154", "shasum": "" }, "require": { @@ -1415,7 +1566,7 @@ ], "support": { "issues": "https://github.com/guzzle/promises/issues", - "source": "https://github.com/guzzle/promises/tree/2.5.3" + "source": "https://github.com/guzzle/promises/tree/2.6.0" }, "funding": [ { @@ -1431,20 +1582,20 @@ "type": "tidelift" } ], - "time": "2026-08-24T09:11:28+00:00" + "time": "2026-10-18T12:46:59+00:00" }, { "name": "guzzlehttp/psr7", - "version": "2.13.1", + "version": "2.13.2", "source": { "type": "git", "url": "https://github.com/guzzle/psr7.git", - "reference": "95e7828100de18b4e269fb1703be530082d5166d" + "reference": "adee536f95101929f262b8c59e8a61472f347d58" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/psr7/zipball/95e7828100de18b4e269fb1703be530082d5166d", - "reference": "95e7828100de18b4e269fb1703be530082d5166d", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/adee536f95101929f262b8c59e8a61472f347d58", + "reference": "adee536f95101929f262b8c59e8a61472f347d58", "shasum": "" }, "require": { @@ -1534,7 +1685,7 @@ ], "support": { "issues": "https://github.com/guzzle/psr7/issues", - "source": "https://github.com/guzzle/psr7/tree/2.13.1" + "source": "https://github.com/guzzle/psr7/tree/2.13.2" }, "funding": [ { @@ -1550,7 +1701,7 @@ "type": "tidelift" } ], - "time": "2026-08-24T09:13:11+00:00" + "time": "2026-10-17T23:49:46+00:00" }, { "name": "guzzlehttp/uri-template", @@ -1746,16 +1897,16 @@ }, { "name": "laravel/framework", - "version": "v13.35.0", + "version": "v13.42.0", "source": { "type": "git", "url": "https://github.com/laravel/framework.git", - "reference": "a413a9da94884e5e9d58f4e6612884f712827804" + "reference": "f5c01f6b63803f16f38ebb31622c4fea412bd022" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/framework/zipball/a413a9da94884e5e9d58f4e6612884f712827804", - "reference": "a413a9da94884e5e9d58f4e6612884f712827804", + "url": "https://api.github.com/repos/laravel/framework/zipball/f5c01f6b63803f16f38ebb31622c4fea412bd022", + "reference": "f5c01f6b63803f16f38ebb31622c4fea412bd022", "shasum": "" }, "require": { @@ -1776,12 +1927,12 @@ "guzzlehttp/promises": "^2.0.3 || ^3.0", "guzzlehttp/psr7": "^2.9 || ^3.0", "guzzlehttp/uri-template": "^1.0 || ^2.0", - "laravel/prompts": "^0.3.11", + "laravel/prompts": "^0.3.25", "laravel/serializable-closure": "^2.0.10", "league/commonmark": "^2.8.1", "league/flysystem": "^3.25.1", "league/flysystem-local": "^3.25.1", - "league/uri": "^7.5.1", + "league/uri": "^7.6", "monolog/monolog": "^3.10", "nesbot/carbon": "^3.8.4", "nunomaduro/termwind": "^2.0", @@ -1858,11 +2009,12 @@ "spatie/once": "*" }, "require-dev": { - "ably/ably-php": "^1.0", + "ably/pubsub-server": "^1.0|^2.0", "aws/aws-sdk-php": "^3.322.9", "ext-gmp": "*", "fakerphp/faker": "^1.24", - "intervention/image": "^4.0", + "intervention/image": "^4.2", + "jasonmccreary/double": "^1.1", "laravel/pint": "^1.18", "league/flysystem-aws-s3-v3": "^3.25.1", "league/flysystem-ftp": "^3.25.1", @@ -1871,10 +2023,10 @@ "league/flysystem-sftp-v3": "^3.25.1", "mockery/mockery": "^1.6.10", "opis/json-schema": "^2.4.1", - "orchestra/testbench-core": "^11.5.0", + "orchestra/testbench-core": "^11.6.0", "pda/pheanstalk": "^7.0.0 || ^8.0.0", "php-http/discovery": "^1.15", - "phpstan/phpstan": "2.2.15", + "phpstan/phpstan": "2.3.5", "phpunit/phpunit": "^11.5.50 || ^12.5.8 || ^13.0.3", "predis/predis": "^2.3 || ^3.0", "rector/rector": "2.6.3", @@ -1887,7 +2039,7 @@ "web-token/jwt-library": "^4.1" }, "suggest": { - "ably/ably-php": "Required to use the Ably broadcast driver (^1.0).", + "ably/pubsub-server": "Required to use the Ably broadcast driver (^1.0|^2.0).", "aws/aws-sdk-php": "Required to use the SQS queue driver, DynamoDb failed job storage, and SES mail driver (^3.322.9).", "brianium/paratest": "Required to run tests in parallel (^7.0 || ^8.0).", "ext-apcu": "Required to use the APC cache driver.", @@ -1901,7 +2053,7 @@ "ext-redis": "Required to use the Redis cache and queue drivers (^4.0 || ^5.0 || ^6.0).", "fakerphp/faker": "Required to generate fake data using the fake() helper (^1.23).", "filp/whoops": "Required for friendly error pages in development (^2.14.3).", - "intervention/image": "Required to use the image processing features (^4.0).", + "intervention/image": "Required to use the image processing features (^4.2).", "laravel/tinker": "Required to use the tinker console command (^2.0).", "league/flysystem-aws-s3-v3": "Required to use the Flysystem S3 driver (^3.25.1).", "league/flysystem-ftp": "Required to use the Flysystem FTP driver (^3.25.1).", @@ -1973,20 +2125,20 @@ "issues": "https://github.com/laravel/framework/issues", "source": "https://github.com/laravel/framework" }, - "time": "2026-10-06T13:52:37+00:00" + "time": "2026-11-10T15:54:30+00:00" }, { "name": "laravel/prompts", - "version": "v0.3.25", + "version": "v0.3.27", "source": { "type": "git", "url": "https://github.com/laravel/prompts.git", - "reference": "21b7b49d60fcb700016dd27b582ae739c75de816" + "reference": "abdfc75a1ae6c6f21522daed50da7124cbff09d2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/prompts/zipball/21b7b49d60fcb700016dd27b582ae739c75de816", - "reference": "21b7b49d60fcb700016dd27b582ae739c75de816", + "url": "https://api.github.com/repos/laravel/prompts/zipball/abdfc75a1ae6c6f21522daed50da7124cbff09d2", + "reference": "abdfc75a1ae6c6f21522daed50da7124cbff09d2", "shasum": "" }, "require": { @@ -2029,22 +2181,22 @@ ], "description": "Add beautiful and user-friendly forms to your command-line applications.", "support": { - "source": "https://github.com/laravel/prompts/tree/v0.3.25" + "source": "https://github.com/laravel/prompts/tree/v0.3.27" }, - "time": "2026-10-06T02:25:49+00:00" + "time": "2026-11-09T16:07:10+00:00" }, { "name": "laravel/serializable-closure", - "version": "v2.1.0", + "version": "v2.2.0", "source": { "type": "git", "url": "https://github.com/laravel/serializable-closure.git", - "reference": "2d5869a838bbcf37e0d8b0568fc41914e81374b5" + "reference": "2bfb44e8af009b553ed2c060c94b0bc3c67b4769" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/serializable-closure/zipball/2d5869a838bbcf37e0d8b0568fc41914e81374b5", - "reference": "2d5869a838bbcf37e0d8b0568fc41914e81374b5", + "url": "https://api.github.com/repos/laravel/serializable-closure/zipball/2bfb44e8af009b553ed2c060c94b0bc3c67b4769", + "reference": "2bfb44e8af009b553ed2c060c94b0bc3c67b4769", "shasum": "" }, "require": { @@ -2092,20 +2244,20 @@ "issues": "https://github.com/laravel/serializable-closure/issues", "source": "https://github.com/laravel/serializable-closure" }, - "time": "2026-09-22T14:32:34+00:00" + "time": "2026-10-14T21:20:29+00:00" }, { "name": "laravel/tinker", - "version": "v3.0.2", + "version": "v3.1.0", "source": { "type": "git", "url": "https://github.com/laravel/tinker.git", - "reference": "4faba77764bd33411735936acdf30446d058c78b" + "reference": "5fab2518167975b302e10d1fdf9a8c8113849201" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/tinker/zipball/4faba77764bd33411735936acdf30446d058c78b", - "reference": "4faba77764bd33411735936acdf30446d058c78b", + "url": "https://api.github.com/repos/laravel/tinker/zipball/5fab2518167975b302e10d1fdf9a8c8113849201", + "reference": "5fab2518167975b302e10d1fdf9a8c8113849201", "shasum": "" }, "require": { @@ -2113,13 +2265,12 @@ "illuminate/contracts": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0", "illuminate/support": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0", "php": "^8.1", - "psy/psysh": "^0.12.0", + "psy/psysh": "^0.12.19", "symfony/var-dumper": "^5.4|^6.0|^7.0|^8.0" }, "require-dev": { - "mockery/mockery": "~1.3.3|^1.4.2", "phpstan/phpstan": "^1.10", - "phpunit/phpunit": "^10.5|^11.5" + "phpunit/phpunit": "^10.5|^11.5|^12.5|^13.4" }, "suggest": { "illuminate/database": "The Illuminate Database package (^8.0|^9.0|^10.0|^11.0|^12.0|^13.0)." @@ -2159,9 +2310,9 @@ ], "support": { "issues": "https://github.com/laravel/tinker/issues", - "source": "https://github.com/laravel/tinker/tree/v3.0.2" + "source": "https://github.com/laravel/tinker/tree/v3.1.0" }, - "time": "2026-03-17T14:54:13+00:00" + "time": "2026-10-16T11:13:33+00:00" }, { "name": "laravel/ui", @@ -2280,16 +2431,16 @@ }, { "name": "league/commonmark", - "version": "2.10.3", + "version": "2.10.7", "source": { "type": "git", "url": "https://github.com/thephpleague/commonmark.git", - "reference": "6efbd9c472b91db0a3350fcd601c8332c2382e1f" + "reference": "8eb53e906fd60c67038d22f1f1cab420ed58b8be" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/6efbd9c472b91db0a3350fcd601c8332c2382e1f", - "reference": "6efbd9c472b91db0a3350fcd601c8332c2382e1f", + "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/8eb53e906fd60c67038d22f1f1cab420ed58b8be", + "reference": "8eb53e906fd60c67038d22f1f1cab420ed58b8be", "shasum": "" }, "require": { @@ -2383,7 +2534,7 @@ "type": "tidelift" } ], - "time": "2026-09-21T13:07:34+00:00" + "time": "2026-10-31T13:35:37+00:00" }, { "name": "league/config", @@ -2645,6 +2796,61 @@ }, "time": "2026-09-02T08:00:27+00:00" }, + { + "name": "league/flysystem-aws-s3-v3", + "version": "3.35.3", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/flysystem-aws-s3-v3.git", + "reference": "b03780cb97585ee7e48977f40ed599b33b751634" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/flysystem-aws-s3-v3/zipball/b03780cb97585ee7e48977f40ed599b33b751634", + "reference": "b03780cb97585ee7e48977f40ed599b33b751634", + "shasum": "" + }, + "require": { + "aws/aws-sdk-php": "^3.371.5", + "league/flysystem": "^3.10.0", + "league/mime-type-detection": "^1.0.0", + "php": "^8.0.2" + }, + "conflict": { + "guzzlehttp/guzzle": "<7.0", + "guzzlehttp/ringphp": "<1.1.1" + }, + "type": "library", + "autoload": { + "psr-4": { + "League\\Flysystem\\AwsS3V3\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Frank de Jonge", + "email": "info@frankdejonge.nl" + } + ], + "description": "AWS S3 filesystem adapter for Flysystem.", + "keywords": [ + "Flysystem", + "aws", + "file", + "files", + "filesystem", + "s3", + "storage" + ], + "support": { + "source": "https://github.com/thephpleague/flysystem-aws-s3-v3/tree/3.35.3" + }, + "time": "2026-08-08T16:19:23+00:00" + }, { "name": "league/flysystem-local", "version": "3.35.3", @@ -2694,6 +2900,52 @@ }, "time": "2026-08-12T13:29:21+00:00" }, + { + "name": "league/flysystem-path-prefixing", + "version": "3.31.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/flysystem-path-prefixing.git", + "reference": "d7f667c2d9d6684b74f30c6ad81ae7a0c23232f3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/flysystem-path-prefixing/zipball/d7f667c2d9d6684b74f30c6ad81ae7a0c23232f3", + "reference": "d7f667c2d9d6684b74f30c6ad81ae7a0c23232f3", + "shasum": "" + }, + "require": { + "league/flysystem": "^3.10.0", + "php": "^8.0.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "League\\Flysystem\\PathPrefixing\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Frank de Jonge", + "email": "info@frankdejonge.nl" + } + ], + "description": "Path prefixing filesystem adapter for Flysystem.", + "keywords": [ + "Flysystem", + "filesystem", + "prefix", + "prefixing" + ], + "support": { + "source": "https://github.com/thephpleague/flysystem-path-prefixing/tree/3.31.0" + }, + "time": "2026-01-23T15:30:45+00:00" + }, { "name": "league/mime-type-detection", "version": "1.17.0", @@ -2752,20 +3004,21 @@ }, { "name": "league/uri", - "version": "7.8.1", + "version": "7.10.0", "source": { "type": "git", "url": "https://github.com/thephpleague/uri.git", - "reference": "08cf38e3924d4f56238125547b5720496fac8fd4" + "reference": "be89e2382e37acdef232259071ade5180821397b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/uri/zipball/08cf38e3924d4f56238125547b5720496fac8fd4", - "reference": "08cf38e3924d4f56238125547b5720496fac8fd4", + "url": "https://api.github.com/repos/thephpleague/uri/zipball/be89e2382e37acdef232259071ade5180821397b", + "reference": "be89e2382e37acdef232259071ade5180821397b", "shasum": "" }, "require": { - "league/uri-interfaces": "^7.8.1", + "ext-mbstring": "*", + "league/uri-interfaces": "^7.10.0", "php": "^8.1", "psr/http-factory": "^1" }, @@ -2838,7 +3091,7 @@ "docs": "https://uri.thephpleague.com", "forum": "https://thephpleague.slack.com", "issues": "https://github.com/thephpleague/uri-src/issues", - "source": "https://github.com/thephpleague/uri/tree/7.8.1" + "source": "https://github.com/thephpleague/uri/tree/7.10.0" }, "funding": [ { @@ -2846,20 +3099,20 @@ "type": "github" } ], - "time": "2026-03-15T20:22:25+00:00" + "time": "2026-11-04T12:45:07+00:00" }, { "name": "league/uri-interfaces", - "version": "7.8.1", + "version": "7.10.0", "source": { "type": "git", "url": "https://github.com/thephpleague/uri-interfaces.git", - "reference": "85d5c77c5d6d3af6c54db4a78246364908f3c928" + "reference": "ea66240cff4ae9a56ce85d577a04d038b771e51c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/uri-interfaces/zipball/85d5c77c5d6d3af6c54db4a78246364908f3c928", - "reference": "85d5c77c5d6d3af6c54db4a78246364908f3c928", + "url": "https://api.github.com/repos/thephpleague/uri-interfaces/zipball/ea66240cff4ae9a56ce85d577a04d038b771e51c", + "reference": "ea66240cff4ae9a56ce85d577a04d038b771e51c", "shasum": "" }, "require": { @@ -2922,7 +3175,7 @@ "docs": "https://uri.thephpleague.com", "forum": "https://thephpleague.slack.com", "issues": "https://github.com/thephpleague/uri-src/issues", - "source": "https://github.com/thephpleague/uri-interfaces/tree/7.8.1" + "source": "https://github.com/thephpleague/uri-interfaces/tree/7.10.0" }, "funding": [ { @@ -2930,7 +3183,7 @@ "type": "github" } ], - "time": "2026-03-08T20:05:35+00:00" + "time": "2026-11-04T12:45:07+00:00" }, { "name": "maatwebsite/excel", @@ -2938,12 +3191,12 @@ "source": { "type": "git", "url": "https://github.com/SpartnerNL/Laravel-Excel.git", - "reference": "050985813424582bf084b93eb8c3fee0fb12c6c4" + "reference": "49d752119a1dd2a0266909fca7bd6aa24e024b70" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/SpartnerNL/Laravel-Excel/zipball/050985813424582bf084b93eb8c3fee0fb12c6c4", - "reference": "050985813424582bf084b93eb8c3fee0fb12c6c4", + "url": "https://api.github.com/repos/SpartnerNL/Laravel-Excel/zipball/49d752119a1dd2a0266909fca7bd6aa24e024b70", + "reference": "49d752119a1dd2a0266909fca7bd6aa24e024b70", "shasum": "" }, "require": { @@ -3020,7 +3273,7 @@ "type": "github" } ], - "time": "2026-09-14T12:30:46+00:00" + "time": "2026-11-11T14:35:24+00:00" }, { "name": "maennchen/zipstream-php", @@ -3363,16 +3616,16 @@ }, { "name": "microsoft/kiota-abstractions", - "version": "2.2.0", + "version": "2.2.3", "source": { "type": "git", "url": "https://github.com/microsoft/kiota-abstractions-php.git", - "reference": "03f85e9b6b5b4864bdf188279651190b8062c30a" + "reference": "42f04acb6fb51863fd24d4304803ea5cb7a44f1f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/microsoft/kiota-abstractions-php/zipball/03f85e9b6b5b4864bdf188279651190b8062c30a", - "reference": "03f85e9b6b5b4864bdf188279651190b8062c30a", + "url": "https://api.github.com/repos/microsoft/kiota-abstractions-php/zipball/42f04acb6fb51863fd24d4304803ea5cb7a44f1f", + "reference": "42f04acb6fb51863fd24d4304803ea5cb7a44f1f", "shasum": "" }, "require": { @@ -3406,31 +3659,31 @@ ], "description": "Abstractions for Kiota", "support": { - "source": "https://github.com/microsoft/kiota-abstractions-php/tree/2.2.0" + "source": "https://github.com/microsoft/kiota-abstractions-php/tree/2.2.3" }, - "time": "2026-10-06T14:59:11+00:00" + "time": "2026-11-03T14:06:26+00:00" }, { "name": "microsoft/kiota-bundle", - "version": "2.2.0", + "version": "2.2.3", "source": { "type": "git", "url": "https://github.com/microsoft/kiota-bundle-php.git", - "reference": "3702ed91b750c77e2c168c2343c48fb97e065725" + "reference": "7ae4431a4087a53fea858410de3b02b376579d28" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/microsoft/kiota-bundle-php/zipball/3702ed91b750c77e2c168c2343c48fb97e065725", - "reference": "3702ed91b750c77e2c168c2343c48fb97e065725", + "url": "https://api.github.com/repos/microsoft/kiota-bundle-php/zipball/7ae4431a4087a53fea858410de3b02b376579d28", + "reference": "7ae4431a4087a53fea858410de3b02b376579d28", "shasum": "" }, "require": { - "microsoft/kiota-abstractions": "^2.2.0", - "microsoft/kiota-http-guzzle": "^2.2.0", - "microsoft/kiota-serialization-form": "^2.2.0", - "microsoft/kiota-serialization-json": "^2.2.0", - "microsoft/kiota-serialization-multipart": "^2.2.0", - "microsoft/kiota-serialization-text": "^2.2.0", + "microsoft/kiota-abstractions": "^2.2.3", + "microsoft/kiota-http-guzzle": "^2.2.3", + "microsoft/kiota-serialization-form": "^2.2.3", + "microsoft/kiota-serialization-json": "^2.2.3", + "microsoft/kiota-serialization-multipart": "^2.2.3", + "microsoft/kiota-serialization-text": "^2.2.3", "php": "^8.2" }, "require-dev": { @@ -3455,29 +3708,29 @@ ], "description": "Default implementations for Kiota client setup", "support": { - "source": "https://github.com/microsoft/kiota-bundle-php/tree/2.2.0" + "source": "https://github.com/microsoft/kiota-bundle-php/tree/2.2.3" }, - "time": "2026-10-06T19:09:36+00:00" + "time": "2026-11-03T14:21:48+00:00" }, { "name": "microsoft/kiota-http-guzzle", - "version": "2.2.0", + "version": "2.2.3", "source": { "type": "git", "url": "https://github.com/microsoft/kiota-http-guzzle-php.git", - "reference": "9ef45982a4b16b58f7a8cce650db2ca0ced86b23" + "reference": "71452a61d27cff9e26fc16228f9ce7a58f7bb00a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/microsoft/kiota-http-guzzle-php/zipball/9ef45982a4b16b58f7a8cce650db2ca0ced86b23", - "reference": "9ef45982a4b16b58f7a8cce650db2ca0ced86b23", + "url": "https://api.github.com/repos/microsoft/kiota-http-guzzle-php/zipball/71452a61d27cff9e26fc16228f9ce7a58f7bb00a", + "reference": "71452a61d27cff9e26fc16228f9ce7a58f7bb00a", "shasum": "" }, "require": { "ext-json": "*", "ext-zlib": "*", "guzzlehttp/guzzle": "^7.4.5 || ^8.0", - "microsoft/kiota-abstractions": "^2.2.0", + "microsoft/kiota-abstractions": "^2.2.3", "php": "^8.2" }, "require-dev": { @@ -3502,28 +3755,28 @@ ], "description": "Kiota HTTP Request Adapter implementation", "support": { - "source": "https://github.com/microsoft/kiota-http-guzzle-php/tree/2.2.0" + "source": "https://github.com/microsoft/kiota-http-guzzle-php/tree/2.2.3" }, - "time": "2026-10-06T18:26:46+00:00" + "time": "2026-11-03T14:18:53+00:00" }, { "name": "microsoft/kiota-serialization-form", - "version": "2.2.0", + "version": "2.2.3", "source": { "type": "git", "url": "https://github.com/microsoft/kiota-serialization-form-php.git", - "reference": "52adfd781cc1cd56578d7f0d0ab385c2753a5629" + "reference": "6ff08880571366008469003b983291e89fd8bece" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/microsoft/kiota-serialization-form-php/zipball/52adfd781cc1cd56578d7f0d0ab385c2753a5629", - "reference": "52adfd781cc1cd56578d7f0d0ab385c2753a5629", + "url": "https://api.github.com/repos/microsoft/kiota-serialization-form-php/zipball/6ff08880571366008469003b983291e89fd8bece", + "reference": "6ff08880571366008469003b983291e89fd8bece", "shasum": "" }, "require": { "ext-json": "*", "guzzlehttp/psr7": "^1.6 || ^2 || ^3", - "microsoft/kiota-abstractions": "^2.2.0", + "microsoft/kiota-abstractions": "^2.2.3", "php": "^8.2" }, "require-dev": { @@ -3550,28 +3803,28 @@ ], "description": "Form implementation of Kiota abstractions serialization.", "support": { - "source": "https://github.com/microsoft/kiota-serialization-form-php/tree/2.2.0" + "source": "https://github.com/microsoft/kiota-serialization-form-php/tree/2.2.3" }, - "time": "2026-10-06T18:52:14+00:00" + "time": "2026-11-03T14:17:17+00:00" }, { "name": "microsoft/kiota-serialization-json", - "version": "2.2.0", + "version": "2.2.3", "source": { "type": "git", "url": "https://github.com/microsoft/kiota-serialization-json-php.git", - "reference": "c8c210af48db25e4fbb6c5234182840446a4a3e2" + "reference": "91c837a4fb55a12864f0ef2744d938793720e869" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/microsoft/kiota-serialization-json-php/zipball/c8c210af48db25e4fbb6c5234182840446a4a3e2", - "reference": "c8c210af48db25e4fbb6c5234182840446a4a3e2", + "url": "https://api.github.com/repos/microsoft/kiota-serialization-json-php/zipball/91c837a4fb55a12864f0ef2744d938793720e869", + "reference": "91c837a4fb55a12864f0ef2744d938793720e869", "shasum": "" }, "require": { "ext-json": "*", "guzzlehttp/psr7": "^1.6 || ^2 || ^3", - "microsoft/kiota-abstractions": "^2.2.0", + "microsoft/kiota-abstractions": "^2.2.3", "php": "^8.2" }, "require-dev": { @@ -3598,28 +3851,28 @@ ], "description": "Implementation of Kiota serialization abstractions using Json.", "support": { - "source": "https://github.com/microsoft/kiota-serialization-json-php/tree/2.2.0" + "source": "https://github.com/microsoft/kiota-serialization-json-php/tree/2.2.3" }, - "time": "2026-10-06T17:55:13+00:00" + "time": "2026-11-03T14:16:39+00:00" }, { "name": "microsoft/kiota-serialization-multipart", - "version": "2.2.0", + "version": "2.2.3", "source": { "type": "git", "url": "https://github.com/microsoft/kiota-serialization-multipart-php.git", - "reference": "4ae474342ee0c16bb338af7dd24522bac58a8787" + "reference": "c6a3908e1dc44fe35f82a226e575dd997771a2a7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/microsoft/kiota-serialization-multipart-php/zipball/4ae474342ee0c16bb338af7dd24522bac58a8787", - "reference": "4ae474342ee0c16bb338af7dd24522bac58a8787", + "url": "https://api.github.com/repos/microsoft/kiota-serialization-multipart-php/zipball/c6a3908e1dc44fe35f82a226e575dd997771a2a7", + "reference": "c6a3908e1dc44fe35f82a226e575dd997771a2a7", "shasum": "" }, "require": { "ext-json": "*", "guzzlehttp/psr7": "^1.6 || ^2 || ^3", - "microsoft/kiota-abstractions": "^2.2.0", + "microsoft/kiota-abstractions": "^2.2.3", "php": "^8.2" }, "require-dev": { @@ -3646,27 +3899,27 @@ ], "description": "Multipart implementation of Kiota abstractions serialization.", "support": { - "source": "https://github.com/microsoft/kiota-serialization-multipart-php/tree/2.2.0" + "source": "https://github.com/microsoft/kiota-serialization-multipart-php/tree/2.2.3" }, - "time": "2026-10-06T19:07:42+00:00" + "time": "2026-11-03T14:17:57+00:00" }, { "name": "microsoft/kiota-serialization-text", - "version": "2.2.0", + "version": "2.2.3", "source": { "type": "git", "url": "https://github.com/microsoft/kiota-serialization-text-php.git", - "reference": "0bea98321822aed25251441f2f0f9347e4ca396c" + "reference": "f810c03adb31e42ff5f0b5e6364a24387f7732bf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/microsoft/kiota-serialization-text-php/zipball/0bea98321822aed25251441f2f0f9347e4ca396c", - "reference": "0bea98321822aed25251441f2f0f9347e4ca396c", + "url": "https://api.github.com/repos/microsoft/kiota-serialization-text-php/zipball/f810c03adb31e42ff5f0b5e6364a24387f7732bf", + "reference": "f810c03adb31e42ff5f0b5e6364a24387f7732bf", "shasum": "" }, "require": { "guzzlehttp/psr7": "^1.6 || ^2 || ^3", - "microsoft/kiota-abstractions": "^2.2.0", + "microsoft/kiota-abstractions": "^2.2.3", "php": "^8.2" }, "require-dev": { @@ -3691,9 +3944,9 @@ ], "description": "Implementation of Serialization Abstractions for text/plain content", "support": { - "source": "https://github.com/microsoft/kiota-serialization-text-php/tree/2.2.0" + "source": "https://github.com/microsoft/kiota-serialization-text-php/tree/2.2.3" }, - "time": "2026-10-06T17:53:51+00:00" + "time": "2026-11-03T14:16:52+00:00" }, { "name": "moneyphp/money", @@ -3891,17 +4144,83 @@ "time": "2026-09-29T19:21:12+00:00" }, { - "name": "nesbot/carbon", - "version": "3.14.2", + "name": "mtdowling/jmespath.php", + "version": "2.9.2", "source": { "type": "git", - "url": "https://github.com/CarbonPHP/carbon.git", - "reference": "94cfc34887f07ab5c0efa07914c8f527544e3224" + "url": "https://github.com/jmespath/jmespath.php.git", + "reference": "2157c5e50e813ec6a96c1eed3be7f64a20fb32a8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/CarbonPHP/carbon/zipball/94cfc34887f07ab5c0efa07914c8f527544e3224", - "reference": "94cfc34887f07ab5c0efa07914c8f527544e3224", + "url": "https://api.github.com/repos/jmespath/jmespath.php/zipball/2157c5e50e813ec6a96c1eed3be7f64a20fb32a8", + "reference": "2157c5e50e813ec6a96c1eed3be7f64a20fb32a8", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "symfony/polyfill-mbstring": "^1.17" + }, + "require-dev": { + "composer/xdebug-handler": "^3.0.3", + "phpunit/phpunit": "^8.5.52" + }, + "bin": [ + "bin/jp.php" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.9-dev" + } + }, + "autoload": { + "files": [ + "src/JmesPath.php" + ], + "psr-4": { + "JmesPath\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Declaratively specify how to extract elements from a JSON document", + "keywords": [ + "json", + "jsonpath" + ], + "support": { + "issues": "https://github.com/jmespath/jmespath.php/issues", + "source": "https://github.com/jmespath/jmespath.php/tree/2.9.2" + }, + "time": "2026-07-06T18:56:19+00:00" + }, + { + "name": "nesbot/carbon", + "version": "3.15.1", + "source": { + "type": "git", + "url": "https://github.com/CarbonPHP/carbon.git", + "reference": "ce0e5636fae7d1e99856eb70cae4c719a284aa08" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/CarbonPHP/carbon/zipball/ce0e5636fae7d1e99856eb70cae4c719a284aa08", + "reference": "ce0e5636fae7d1e99856eb70cae4c719a284aa08", "shasum": "" }, "require": { @@ -3911,6 +4230,7 @@ "psr/clock": "^1.0", "symfony/clock": "^6.3.12 || ^7.0 || ^8.0", "symfony/polyfill-mbstring": "^1.0", + "symfony/polyfill-time": "^1.0", "symfony/translation": "^4.4.18 || ^5.2.1 || ^6.0 || ^7.0 || ^8.0" }, "provide": { @@ -3993,37 +4313,37 @@ "type": "tidelift" } ], - "time": "2026-10-02T07:26:52+00:00" + "time": "2026-10-25T14:32:48+00:00" }, { "name": "nette/schema", - "version": "v1.3.6", + "version": "v1.4.0", "source": { "type": "git", "url": "https://github.com/nette/schema.git", - "reference": "c54350438cd6914616f790a49cb424605f421562" + "reference": "af9fa8a86bfca9b02b10346220db26e62ef942ec" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nette/schema/zipball/c54350438cd6914616f790a49cb424605f421562", - "reference": "c54350438cd6914616f790a49cb424605f421562", + "url": "https://api.github.com/repos/nette/schema/zipball/af9fa8a86bfca9b02b10346220db26e62ef942ec", + "reference": "af9fa8a86bfca9b02b10346220db26e62ef942ec", "shasum": "" }, "require": { "nette/utils": "^4.0", - "php": "8.1 - 8.5" + "php": "8.1 - 8.6" }, "require-dev": { - "nette/phpstan-rules": "^1.0", + "nette/phpstan-rules": "^1.0.7", "nette/tester": "^2.6", "phpstan/extension-installer": "^1.4@stable", - "phpstan/phpstan": "^2.1.39@stable", + "phpstan/phpstan": "^2.3@stable", "tracy/tracy": "^2.8" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.3-dev" + "dev-master": "1.4-dev" } }, "autoload": { @@ -4044,40 +4364,40 @@ { "name": "David Grudl", "homepage": "https://davidgrudl.com" - }, - { - "name": "Nette Community", - "homepage": "https://nette.org/contributors" } ], - "description": "📐 Nette Schema: validating data structures against a given Schema.", - "homepage": "https://nette.org", + "description": "📐 Nette Schema: validates and normalizes data such as configuration or API input against a schema described in a few readable lines of PHP, with precise error messages.", + "homepage": "https://doc.nette.org/schema", "keywords": [ - "config", - "nette" + "configuration", + "data validation", + "nette", + "normalization", + "schema", + "validation" ], "support": { "issues": "https://github.com/nette/schema/issues", - "source": "https://github.com/nette/schema/tree/v1.3.6" + "source": "https://github.com/nette/schema/tree/v1.4.0" }, - "time": "2026-08-16T21:58:41+00:00" + "time": "2026-10-22T02:12:50+00:00" }, { "name": "nette/utils", - "version": "v4.1.5", + "version": "v4.1.6", "source": { "type": "git", "url": "https://github.com/nette/utils.git", - "reference": "b043439dbdf954e6c28b5ea7e34b0100f83165e0" + "reference": "6bf24518accf32cf845bca305e0b92078700fd01" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nette/utils/zipball/b043439dbdf954e6c28b5ea7e34b0100f83165e0", - "reference": "b043439dbdf954e6c28b5ea7e34b0100f83165e0", + "url": "https://api.github.com/repos/nette/utils/zipball/6bf24518accf32cf845bca305e0b92078700fd01", + "reference": "6bf24518accf32cf845bca305e0b92078700fd01", "shasum": "" }, "require": { - "php": "8.2 - 8.5" + "php": "8.2 - 8.6" }, "conflict": { "nette/finder": "<3", @@ -4149,9 +4469,9 @@ ], "support": { "issues": "https://github.com/nette/utils/issues", - "source": "https://github.com/nette/utils/tree/v4.1.5" + "source": "https://github.com/nette/utils/tree/v4.1.6" }, - "time": "2026-07-17T23:02:45+00:00" + "time": "2026-10-20T17:07:56+00:00" }, { "name": "nikic/php-parser", @@ -4212,31 +4532,31 @@ }, { "name": "nunomaduro/termwind", - "version": "v2.4.0", + "version": "v2.4.1", "source": { "type": "git", "url": "https://github.com/nunomaduro/termwind.git", - "reference": "712a31b768f5daea284c2169a7d227031001b9a8" + "reference": "9b85ae4d802403bfc004ea633ce542bc262ee5c3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nunomaduro/termwind/zipball/712a31b768f5daea284c2169a7d227031001b9a8", - "reference": "712a31b768f5daea284c2169a7d227031001b9a8", + "url": "https://api.github.com/repos/nunomaduro/termwind/zipball/9b85ae4d802403bfc004ea633ce542bc262ee5c3", + "reference": "9b85ae4d802403bfc004ea633ce542bc262ee5c3", "shasum": "" }, "require": { "ext-mbstring": "*", "php": "^8.2", - "symfony/console": "^7.4.4 || ^8.0.4" + "symfony/console": "^7.4.23 || ^8.1.11" }, "require-dev": { - "illuminate/console": "^11.47.0", - "laravel/pint": "^1.27.1", - "mockery/mockery": "^1.6.12", - "pestphp/pest": "^2.36.0 || ^3.8.4 || ^4.3.2", - "phpstan/phpstan": "^1.12.32", + "illuminate/console": "^11.51 || ^12.70 || ^13.40", + "laravel/pint": "^1.30.4", + "mockery/mockery": "^1.6.15", + "pestphp/pest": "^2.36.1 || ^3.8.7 || ^4.7.8 || ^5.3.5", + "phpstan/phpstan": "^1.12.34", "phpstan/phpstan-strict-rules": "^1.6.2", - "symfony/var-dumper": "^7.3.5 || ^8.0.4", + "symfony/var-dumper": "^7.4.22 || ^8.1.10", "thecodingmachine/phpstan-strict-rules": "^1.0.0" }, "type": "library", @@ -4279,7 +4599,7 @@ ], "support": { "issues": "https://github.com/nunomaduro/termwind/issues", - "source": "https://github.com/nunomaduro/termwind/tree/v2.4.0" + "source": "https://github.com/nunomaduro/termwind/tree/v2.4.1" }, "funding": [ { @@ -4295,7 +4615,7 @@ "type": "github" } ], - "time": "2026-02-16T23:10:27+00:00" + "time": "2026-11-07T03:57:16+00:00" }, { "name": "nyholm/psr7", @@ -4443,36 +4763,43 @@ }, { "name": "open-telemetry/api", - "version": "1.10.0", + "version": "1.11.0", "source": { "type": "git", "url": "https://github.com/opentelemetry-php/api.git", - "reference": "7c029c4a6fd457094a20569bf98f93d95e9a7559" + "reference": "bc169d9ecd11858e941657770dc708c6a15fc5f4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/opentelemetry-php/api/zipball/7c029c4a6fd457094a20569bf98f93d95e9a7559", - "reference": "7c029c4a6fd457094a20569bf98f93d95e9a7559", + "url": "https://api.github.com/repos/opentelemetry-php/api/zipball/bc169d9ecd11858e941657770dc708c6a15fc5f4", + "reference": "bc169d9ecd11858e941657770dc708c6a15fc5f4", "shasum": "" }, "require": { "open-telemetry/context": "^1.4", - "php": "^8.1", - "psr/log": "^1.1|^2.0|^3.0", - "symfony/polyfill-php82": "^1.26" + "php": "^8.2", + "psr/log": "^1.1|^2.0|^3.0" }, "conflict": { - "open-telemetry/sdk": "<=1.11" + "open-telemetry/sdk": "<=1.11", + "open-telemetry/sdk-configuration": "<0.10" + }, + "suggest": { + "symfony/config": "To implement a ComponentProvider for declarative configuration" }, "type": "library", "extra": { "spi": { + "OpenTelemetry\\API\\Configuration\\Config\\ComponentProvider": [ + "OpenTelemetry\\API\\Baggage\\Propagation\\Config\\TextMapPropagatorBaggage", + "OpenTelemetry\\API\\Trace\\Propagation\\Config\\TextMapPropagatorTraceContext" + ], "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\HookManagerInterface": [ "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\ExtensionHookManager" ] }, "branch-alias": { - "dev-main": "1.8.x-dev" + "dev-main": "1.11.x-dev" } }, "autoload": { @@ -4509,25 +4836,24 @@ "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", "source": "https://github.com/open-telemetry/opentelemetry-php" }, - "time": "2026-07-06T12:28:04+00:00" + "time": "2026-11-05T11:54:49+00:00" }, { "name": "open-telemetry/context", - "version": "1.5.0", + "version": "1.6.0", "source": { "type": "git", "url": "https://github.com/opentelemetry-php/context.git", - "reference": "3c414b246e0dabb7d6145404e6a5e4536ca18d07" + "reference": "711e7291d9cf8a984c059c5afd926e45ab444b7f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/opentelemetry-php/context/zipball/3c414b246e0dabb7d6145404e6a5e4536ca18d07", - "reference": "3c414b246e0dabb7d6145404e6a5e4536ca18d07", + "url": "https://api.github.com/repos/opentelemetry-php/context/zipball/711e7291d9cf8a984c059c5afd926e45ab444b7f", + "reference": "711e7291d9cf8a984c059c5afd926e45ab444b7f", "shasum": "" }, "require": { - "php": "^8.1", - "symfony/polyfill-php82": "^1.26" + "php": "^8.2" }, "suggest": { "ext-ffi": "To allow context switching in Fibers" @@ -4535,7 +4861,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "1.0.x-dev" + "dev-main": "1.6.x-dev" } }, "autoload": { @@ -4568,29 +4894,29 @@ "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", "source": "https://github.com/open-telemetry/opentelemetry-php" }, - "time": "2025-10-19T06:44:33+00:00" + "time": "2026-11-05T11:54:49+00:00" }, { "name": "open-telemetry/sdk", - "version": "1.15.0", + "version": "1.16.1", "source": { "type": "git", "url": "https://github.com/opentelemetry-php/sdk.git", - "reference": "77e1aa73850154abb86937d52a70883edc3b4547" + "reference": "51ebca2563dd580d682d4f32b1611c1779424dac" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/opentelemetry-php/sdk/zipball/77e1aa73850154abb86937d52a70883edc3b4547", - "reference": "77e1aa73850154abb86937d52a70883edc3b4547", + "url": "https://api.github.com/repos/opentelemetry-php/sdk/zipball/51ebca2563dd580d682d4f32b1611c1779424dac", + "reference": "51ebca2563dd580d682d4f32b1611c1779424dac", "shasum": "" }, "require": { "ext-json": "*", "nyholm/psr7-server": "^1.1", - "open-telemetry/api": "^1.8", + "open-telemetry/api": "^1.11", "open-telemetry/context": "^1.4", - "open-telemetry/sem-conv": "^1.38.0", - "php": "^8.1", + "open-telemetry/sem-conv": "^1.45.0", + "php": "^8.2", "php-http/discovery": "^1.14", "psr/http-client": "^1.0", "psr/http-client-implementation": "^1.0", @@ -4599,7 +4925,6 @@ "psr/log": "^1.1|^2.0|^3.0", "ramsey/uuid": "^3.0 || ^4.0", "symfony/polyfill-mbstring": "^1.23", - "symfony/polyfill-php82": "^1.26", "tbachert/spi": "^1.0.5" }, "suggest": { @@ -4625,7 +4950,7 @@ ] }, "branch-alias": { - "dev-main": "1.14.x-dev" + "dev-main": "1.16.x-dev" } }, "autoload": { @@ -4668,20 +4993,20 @@ "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", "source": "https://github.com/open-telemetry/opentelemetry-php" }, - "time": "2026-07-14T13:09:54+00:00" + "time": "2026-11-06T02:25:35+00:00" }, { "name": "open-telemetry/sem-conv", - "version": "1.44.0", + "version": "1.45.0", "source": { "type": "git", "url": "https://github.com/opentelemetry-php/sem-conv.git", - "reference": "c94bc7ebacef039cda4f4c9270807dcc58b4e3af" + "reference": "7a42562cf5891f56f6f8ea2ecc945f31108c8806" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/opentelemetry-php/sem-conv/zipball/c94bc7ebacef039cda4f4c9270807dcc58b4e3af", - "reference": "c94bc7ebacef039cda4f4c9270807dcc58b4e3af", + "url": "https://api.github.com/repos/opentelemetry-php/sem-conv/zipball/7a42562cf5891f56f6f8ea2ecc945f31108c8806", + "reference": "7a42562cf5891f56f6f8ea2ecc945f31108c8806", "shasum": "" }, "require": { @@ -4725,20 +5050,20 @@ "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", "source": "https://github.com/open-telemetry/opentelemetry-php" }, - "time": "2026-09-09T22:06:17+00:00" + "time": "2026-11-03T22:37:22+00:00" }, { "name": "paragonie/constant_time_encoding", - "version": "v3.1.3", + "version": "v3.1.4", "source": { "type": "git", "url": "https://github.com/paragonie/constant_time_encoding.git", - "reference": "d5b01a39b3415c2cd581d3bd3a3575c1ebbd8e77" + "reference": "5efef6e6cb43e088ccab7d0c1e2f2ab25b9e8b54" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/paragonie/constant_time_encoding/zipball/d5b01a39b3415c2cd581d3bd3a3575c1ebbd8e77", - "reference": "d5b01a39b3415c2cd581d3bd3a3575c1ebbd8e77", + "url": "https://api.github.com/repos/paragonie/constant_time_encoding/zipball/5efef6e6cb43e088ccab7d0c1e2f2ab25b9e8b54", + "reference": "5efef6e6cb43e088ccab7d0c1e2f2ab25b9e8b54", "shasum": "" }, "require": { @@ -4794,7 +5119,7 @@ "issues": "https://github.com/paragonie/constant_time_encoding/issues", "source": "https://github.com/paragonie/constant_time_encoding" }, - "time": "2025-09-24T15:06:41+00:00" + "time": "2026-11-06T20:31:19+00:00" }, { "name": "paragonie/random_compat", @@ -4979,16 +5304,16 @@ }, { "name": "phpoffice/phpspreadsheet", - "version": "5.10.0", + "version": "5.11.0", "source": { "type": "git", "url": "https://github.com/PHPOffice/PhpSpreadsheet.git", - "reference": "eb18727acf6b1f4cc67145a52ab04f9fd4c28d53" + "reference": "3aa1f0d0f3c658b803c18050ac49244d07d96907" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/eb18727acf6b1f4cc67145a52ab04f9fd4c28d53", - "reference": "eb18727acf6b1f4cc67145a52ab04f9fd4c28d53", + "url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/3aa1f0d0f3c658b803c18050ac49244d07d96907", + "reference": "3aa1f0d0f3c658b803c18050ac49244d07d96907", "shasum": "" }, "require": { @@ -5011,9 +5336,11 @@ "markbaker/complex": "^3.0", "markbaker/matrix": "^3.0", "php": "^8.2", + "phpoffice/wmf": "^0.2.1", "psr/simple-cache": "^1.0 || ^2.0 || ^3.0" }, "require-dev": { + "cyclonedx/cyclonedx-php-composer": "^6.2", "dealerdirect/phpcodesniffer-composer-installer": "dev-main", "dompdf/dompdf": "^2.0 || ^3.0", "ext-intl": "*", @@ -5084,9 +5411,61 @@ ], "support": { "issues": "https://github.com/PHPOffice/PhpSpreadsheet/issues", - "source": "https://github.com/PHPOffice/PhpSpreadsheet/tree/5.10.0" + "source": "https://github.com/PHPOffice/PhpSpreadsheet/tree/5.11.0" }, - "time": "2026-09-17T03:54:50+00:00" + "time": "2026-11-08T06:29:49+00:00" + }, + { + "name": "phpoffice/wmf", + "version": "0.2.1", + "source": { + "type": "git", + "url": "https://github.com/PHPOffice/WMF.git", + "reference": "d1eafbab74509ee2adfcdda3888737cd8d349820" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPOffice/WMF/zipball/d1eafbab74509ee2adfcdda3888737cd8d349820", + "reference": "d1eafbab74509ee2adfcdda3888737cd8d349820", + "shasum": "" + }, + "require": { + "ext-gd": "*", + "php": "^7.1|^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.88 || ^1.0.0", + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "PhpOffice\\WMF\\": "src/WMF/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Progi1984", + "homepage": "https://lefevre.dev" + } + ], + "description": "WMF - Manipulate WMF Images", + "homepage": "https://phpoffice.github.io/WMF/", + "keywords": [ + "emf", + "image", + "php", + "wmf" + ], + "support": { + "issues": "https://github.com/PHPOffice/WMF/issues", + "source": "https://github.com/PHPOffice/WMF/tree/0.2.1" + }, + "time": "2026-10-08T19:34:28+00:00" }, { "name": "phpoption/phpoption", @@ -5165,16 +5544,16 @@ }, { "name": "phpseclib/phpseclib", - "version": "3.0.57", + "version": "3.0.58", "source": { "type": "git", "url": "https://github.com/phpseclib/phpseclib.git", - "reference": "d17e0ddaeaf6f22f7e007cbb437d78792fe2a0e4" + "reference": "91f3a6436bb84040ac0cf49e761977f17d16a39b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/d17e0ddaeaf6f22f7e007cbb437d78792fe2a0e4", - "reference": "d17e0ddaeaf6f22f7e007cbb437d78792fe2a0e4", + "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/91f3a6436bb84040ac0cf49e761977f17d16a39b", + "reference": "91f3a6436bb84040ac0cf49e761977f17d16a39b", "shasum": "" }, "require": { @@ -5255,7 +5634,7 @@ ], "support": { "issues": "https://github.com/phpseclib/phpseclib/issues", - "source": "https://github.com/phpseclib/phpseclib/tree/3.0.57" + "source": "https://github.com/phpseclib/phpseclib/tree/3.0.58" }, "funding": [ { @@ -5271,7 +5650,7 @@ "type": "tidelift" } ], - "time": "2026-08-26T12:13:21+00:00" + "time": "2026-11-02T10:45:48+00:00" }, { "name": "propaganistas/laravel-phone", @@ -6207,16 +6586,16 @@ }, { "name": "sentry/sentry", - "version": "4.33.2", + "version": "4.37.0", "source": { "type": "git", "url": "https://github.com/getsentry/sentry-php.git", - "reference": "8a0556ccb6cdcdce81f9af4ca8714c22cff2e003" + "reference": "635a94908528ca5c4f0804640a0ec578e51639b3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/getsentry/sentry-php/zipball/8a0556ccb6cdcdce81f9af4ca8714c22cff2e003", - "reference": "8a0556ccb6cdcdce81f9af4ca8714c22cff2e003", + "url": "https://api.github.com/repos/getsentry/sentry-php/zipball/635a94908528ca5c4f0804640a0ec578e51639b3", + "reference": "635a94908528ca5c4f0804640a0ec578e51639b3", "shasum": "" }, "require": { @@ -6245,7 +6624,7 @@ "open-telemetry/gen-otlp-protobuf": "^1.2.1", "open-telemetry/sdk": "^1.1", "open-telemetry/sem-conv": "^1.27", - "phpstan/phpstan": "^1.3", + "phpstan/phpstan": "^2.2", "phpunit/phpunit": "^8.5.52|^9.6.34", "spiral/roadrunner-http": "^3.6", "spiral/roadrunner-worker": "^3.6" @@ -6288,7 +6667,7 @@ ], "support": { "issues": "https://github.com/getsentry/sentry-php/issues", - "source": "https://github.com/getsentry/sentry-php/tree/4.33.2" + "source": "https://github.com/getsentry/sentry-php/tree/4.37.0" }, "funding": [ { @@ -6300,33 +6679,33 @@ "type": "custom" } ], - "time": "2026-10-07T12:48:05+00:00" + "time": "2026-11-11T15:29:22+00:00" }, { "name": "sentry/sentry-laravel", - "version": "4.28.0", + "version": "4.30.0", "source": { "type": "git", "url": "https://github.com/getsentry/sentry-laravel.git", - "reference": "34bf18fbf99b884a9bfbb46957d0178d2d0b988e" + "reference": "001f8c7eeeb0d512491c4a22c5a4880c833bd036" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/getsentry/sentry-laravel/zipball/34bf18fbf99b884a9bfbb46957d0178d2d0b988e", - "reference": "34bf18fbf99b884a9bfbb46957d0178d2d0b988e", + "url": "https://api.github.com/repos/getsentry/sentry-laravel/zipball/001f8c7eeeb0d512491c4a22c5a4880c833bd036", + "reference": "001f8c7eeeb0d512491c4a22c5a4880c833bd036", "shasum": "" }, "require": { "illuminate/support": "^6.0 | ^7.0 | ^8.0 | ^9.0 | ^10.0 | ^11.0 | ^12.0 | ^13.0", "nyholm/psr7": "^1.0", "php": "^7.2 | ^8.0", - "sentry/sentry": "^4.31.0", + "sentry/sentry": "^4.34.0", "symfony/psr-http-message-bridge": "^1.0 | ^2.0 | ^6.0 | ^7.0 | ^8.0" }, "require-dev": { "friendsofphp/php-cs-fixer": "^3.11", "guzzlehttp/guzzle": "^7.2", - "laravel/ai": "^0.1.5", + "laravel/ai": "^0.1.5 | ^1.0", "laravel/folio": "^1.1", "laravel/framework": "^6.0 | ^7.0 | ^8.0 | ^9.0 | ^10.0 | ^11.0 | ^12.0 | ^13.0", "laravel/octane": "^2.15", @@ -6334,7 +6713,7 @@ "livewire/livewire": "^2.0 | ^3.0 | ^4.0", "mockery/mockery": "^1.3", "orchestra/testbench": "^4.7 | ^5.1 | ^6.0 | ^7.0 | ^8.0 | ^9.0 | ^10.0 | ^11.0", - "phpstan/phpstan": "^1.10", + "phpstan/phpstan": "^1.10 | ^2.2", "phpunit/phpunit": "^8.5 | ^9.6 | ^10.4 | ^11.5" }, "type": "library", @@ -6380,7 +6759,7 @@ ], "support": { "issues": "https://github.com/getsentry/sentry-laravel/issues", - "source": "https://github.com/getsentry/sentry-laravel/tree/4.28.0" + "source": "https://github.com/getsentry/sentry-laravel/tree/4.30.0" }, "funding": [ { @@ -6392,7 +6771,7 @@ "type": "custom" } ], - "time": "2026-09-23T14:29:19+00:00" + "time": "2026-11-11T19:17:46+00:00" }, { "name": "spatie/crawler", @@ -6611,23 +6990,23 @@ }, { "name": "spatie/robots-txt", - "version": "2.5.4", + "version": "2.6.0", "source": { "type": "git", "url": "https://github.com/spatie/robots-txt.git", - "reference": "a8dd35d0a94e863f52509a366a634978e9c1db03" + "reference": "a416c58e9572c8680d3c3720184b8ffb8320720d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/spatie/robots-txt/zipball/a8dd35d0a94e863f52509a366a634978e9c1db03", - "reference": "a8dd35d0a94e863f52509a366a634978e9c1db03", + "url": "https://api.github.com/repos/spatie/robots-txt/zipball/a416c58e9572c8680d3c3720184b8ffb8320720d", + "reference": "a416c58e9572c8680d3c3720184b8ffb8320720d", "shasum": "" }, "require": { - "php": "^8.1" + "php": "^8.4.1" }, "require-dev": { - "phpunit/phpunit": "^11.5.2" + "phpunit/phpunit": "^13.4.5" }, "type": "library", "autoload": { @@ -6655,7 +7034,7 @@ ], "support": { "issues": "https://github.com/spatie/robots-txt/issues", - "source": "https://github.com/spatie/robots-txt/tree/2.5.4" + "source": "https://github.com/spatie/robots-txt/tree/2.6.0" }, "funding": [ { @@ -6667,20 +7046,20 @@ "type": "github" } ], - "time": "2026-02-25T07:59:20+00:00" + "time": "2026-11-06T12:00:00+00:00" }, { "name": "stduritemplate/stduritemplate", - "version": "2.0.12", + "version": "2.0.13", "source": { "type": "git", "url": "https://github.com/std-uritemplate/std-uritemplate-php.git", - "reference": "fd18ebed22ded14a5833ab69d91443b19bd28647" + "reference": "b201e20f552411f3da40eef7b651f847ad1e3ff9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/std-uritemplate/std-uritemplate-php/zipball/fd18ebed22ded14a5833ab69d91443b19bd28647", - "reference": "fd18ebed22ded14a5833ab69d91443b19bd28647", + "url": "https://api.github.com/repos/std-uritemplate/std-uritemplate-php/zipball/b201e20f552411f3da40eef7b651f847ad1e3ff9", + "reference": "b201e20f552411f3da40eef7b651f847ad1e3ff9", "shasum": "" }, "require": { @@ -6704,22 +7083,22 @@ ], "description": "Std UriTemplate, RFC 6570 implementation", "support": { - "source": "https://github.com/std-uritemplate/std-uritemplate-php/tree/2.0.12" + "source": "https://github.com/std-uritemplate/std-uritemplate-php/tree/2.0.13" }, - "time": "2026-07-16T11:03:57+00:00" + "time": "2026-10-30T12:51:09+00:00" }, { "name": "symfony/clock", - "version": "v8.1.0", + "version": "v8.1.9", "source": { "type": "git", "url": "https://github.com/symfony/clock.git", - "reference": "701ef4de9705d6c32292ebee5e8044094a09fbf6" + "reference": "945ea3b64d6da9c1c2c354fe5c07b27455df6442" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/clock/zipball/701ef4de9705d6c32292ebee5e8044094a09fbf6", - "reference": "701ef4de9705d6c32292ebee5e8044094a09fbf6", + "url": "https://api.github.com/repos/symfony/clock/zipball/945ea3b64d6da9c1c2c354fe5c07b27455df6442", + "reference": "945ea3b64d6da9c1c2c354fe5c07b27455df6442", "shasum": "" }, "require": { @@ -6763,7 +7142,7 @@ "time" ], "support": { - "source": "https://github.com/symfony/clock/tree/v8.1.0" + "source": "https://github.com/symfony/clock/tree/v8.1.9" }, "funding": [ { @@ -6783,20 +7162,20 @@ "type": "tidelift" } ], - "time": "2026-05-29T05:06:50+00:00" + "time": "2026-10-12T14:32:04+00:00" }, { "name": "symfony/console", - "version": "v8.1.8", + "version": "v8.1.11", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "4b81146e3ee248ea969186f85499b54fbc78db08" + "reference": "5a315b092b81f3e920e9daea1a2ae4c66ed298b9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/4b81146e3ee248ea969186f85499b54fbc78db08", - "reference": "4b81146e3ee248ea969186f85499b54fbc78db08", + "url": "https://api.github.com/repos/symfony/console/zipball/5a315b092b81f3e920e9daea1a2ae4c66ed298b9", + "reference": "5a315b092b81f3e920e9daea1a2ae4c66ed298b9", "shasum": "" }, "require": { @@ -6863,7 +7242,7 @@ "terminal" ], "support": { - "source": "https://github.com/symfony/console/tree/v8.1.8" + "source": "https://github.com/symfony/console/tree/v8.1.11" }, "funding": [ { @@ -6883,20 +7262,20 @@ "type": "tidelift" } ], - "time": "2026-09-18T16:00:27+00:00" + "time": "2026-11-04T07:07:11+00:00" }, { "name": "symfony/css-selector", - "version": "v8.1.6", + "version": "v8.1.10", "source": { "type": "git", "url": "https://github.com/symfony/css-selector.git", - "reference": "08e2905152a39cf3fd1745d83f8c483e258887d9" + "reference": "9cfd588b8b07cf83e3426b030dbafd2291c132d9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/css-selector/zipball/08e2905152a39cf3fd1745d83f8c483e258887d9", - "reference": "08e2905152a39cf3fd1745d83f8c483e258887d9", + "url": "https://api.github.com/repos/symfony/css-selector/zipball/9cfd588b8b07cf83e3426b030dbafd2291c132d9", + "reference": "9cfd588b8b07cf83e3426b030dbafd2291c132d9", "shasum": "" }, "require": { @@ -6932,7 +7311,7 @@ "description": "Converts CSS selectors to XPath expressions", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/css-selector/tree/v8.1.6" + "source": "https://github.com/symfony/css-selector/tree/v8.1.10" }, "funding": [ { @@ -6952,20 +7331,20 @@ "type": "tidelift" } ], - "time": "2026-08-23T10:06:25+00:00" + "time": "2026-10-18T14:56:39+00:00" }, { "name": "symfony/deprecation-contracts", - "version": "v3.7.1", + "version": "v3.8.1", "source": { "type": "git", "url": "https://github.com/symfony/deprecation-contracts.git", - "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d" + "reference": "feb1edf4e546af3b85c5caebe8359a20db230ca3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/f3202fa1b5097b0af062dc978b32ecf63404e31d", - "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/feb1edf4e546af3b85c5caebe8359a20db230ca3", + "reference": "feb1edf4e546af3b85c5caebe8359a20db230ca3", "shasum": "" }, "require": { @@ -6978,7 +7357,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -7003,7 +7382,7 @@ "description": "A generic function and convention to trigger deprecation notices", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/deprecation-contracts/tree/v3.7.1" + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.8.1" }, "funding": [ { @@ -7023,20 +7402,20 @@ "type": "tidelift" } ], - "time": "2026-06-05T06:23:12+00:00" + "time": "2026-09-16T14:15:10+00:00" }, { "name": "symfony/dom-crawler", - "version": "v8.1.5", + "version": "v8.1.10", "source": { "type": "git", "url": "https://github.com/symfony/dom-crawler.git", - "reference": "94f70e1b2e5b7b8f8618871fd9eaad3e39e9f03d" + "reference": "aa0674b52e1bd00502756fbaba8c982b446472e6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/94f70e1b2e5b7b8f8618871fd9eaad3e39e9f03d", - "reference": "94f70e1b2e5b7b8f8618871fd9eaad3e39e9f03d", + "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/aa0674b52e1bd00502756fbaba8c982b446472e6", + "reference": "aa0674b52e1bd00502756fbaba8c982b446472e6", "shasum": "" }, "require": { @@ -7073,7 +7452,7 @@ "description": "Eases DOM navigation for HTML and XML documents", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/dom-crawler/tree/v8.1.5" + "source": "https://github.com/symfony/dom-crawler/tree/v8.1.10" }, "funding": [ { @@ -7093,20 +7472,20 @@ "type": "tidelift" } ], - "time": "2026-08-21T17:47:34+00:00" + "time": "2026-10-25T14:40:25+00:00" }, { "name": "symfony/error-handler", - "version": "v8.1.8", + "version": "v8.1.10", "source": { "type": "git", "url": "https://github.com/symfony/error-handler.git", - "reference": "c146daceccd5d4f864c051b233c276641cec527b" + "reference": "84c6d73f990ae22dbd45625c056d7ff99ca6810d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/error-handler/zipball/c146daceccd5d4f864c051b233c276641cec527b", - "reference": "c146daceccd5d4f864c051b233c276641cec527b", + "url": "https://api.github.com/repos/symfony/error-handler/zipball/84c6d73f990ae22dbd45625c056d7ff99ca6810d", + "reference": "84c6d73f990ae22dbd45625c056d7ff99ca6810d", "shasum": "" }, "require": { @@ -7154,7 +7533,7 @@ "description": "Provides tools to manage errors and ease debugging PHP code", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/error-handler/tree/v8.1.8" + "source": "https://github.com/symfony/error-handler/tree/v8.1.10" }, "funding": [ { @@ -7174,7 +7553,7 @@ "type": "tidelift" } ], - "time": "2026-09-22T18:58:53+00:00" + "time": "2026-10-25T14:40:25+00:00" }, { "name": "symfony/event-dispatcher", @@ -7264,16 +7643,16 @@ }, { "name": "symfony/event-dispatcher-contracts", - "version": "v3.7.1", + "version": "v3.8.1", "source": { "type": "git", "url": "https://github.com/symfony/event-dispatcher-contracts.git", - "reference": "c7de7a00ffb67842132da02ea92988a39ccd9f4e" + "reference": "658e29751424da3ef4758c60f769e59d1b2981eb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/c7de7a00ffb67842132da02ea92988a39ccd9f4e", - "reference": "c7de7a00ffb67842132da02ea92988a39ccd9f4e", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/658e29751424da3ef4758c60f769e59d1b2981eb", + "reference": "658e29751424da3ef4758c60f769e59d1b2981eb", "shasum": "" }, "require": { @@ -7287,7 +7666,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -7320,7 +7699,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.7.1" + "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.8.1" }, "funding": [ { @@ -7340,20 +7719,91 @@ "type": "tidelift" } ], - "time": "2026-06-05T06:23:12+00:00" + "time": "2026-09-16T14:15:10+00:00" }, { - "name": "symfony/finder", - "version": "v8.1.8", + "name": "symfony/filesystem", + "version": "v8.1.11", "source": { "type": "git", - "url": "https://github.com/symfony/finder.git", - "reference": "bd4fed193a3132c91c5c93595cbfc78988915822" + "url": "https://github.com/symfony/filesystem.git", + "reference": "58f57b6a33e3495f7f41e01258f1ae5ef76cccd2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/bd4fed193a3132c91c5c93595cbfc78988915822", - "reference": "bd4fed193a3132c91c5c93595cbfc78988915822", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/58f57b6a33e3495f7f41e01258f1ae5ef76cccd2", + "reference": "58f57b6a33e3495f7f41e01258f1ae5ef76cccd2", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-mbstring": "~1.8" + }, + "require-dev": { + "symfony/process": "^7.4|^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Filesystem\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides basic utilities for the filesystem", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/filesystem/tree/v8.1.11" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-11-04T08:39:20+00:00" + }, + { + "name": "symfony/finder", + "version": "v8.1.11", + "source": { + "type": "git", + "url": "https://github.com/symfony/finder.git", + "reference": "a2902e479ba5691d20d51d100a715ea19ad2c837" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/finder/zipball/a2902e479ba5691d20d51d100a715ea19ad2c837", + "reference": "a2902e479ba5691d20d51d100a715ea19ad2c837", "shasum": "" }, "require": { @@ -7388,7 +7838,7 @@ "description": "Finds files and directories via an intuitive fluent interface", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/finder/tree/v8.1.8" + "source": "https://github.com/symfony/finder/tree/v8.1.11" }, "funding": [ { @@ -7408,20 +7858,20 @@ "type": "tidelift" } ], - "time": "2026-09-26T06:33:49+00:00" + "time": "2026-11-02T10:58:30+00:00" }, { "name": "symfony/http-foundation", - "version": "v8.1.8", + "version": "v8.1.11", "source": { "type": "git", "url": "https://github.com/symfony/http-foundation.git", - "reference": "662f5257658d4f60deff1bc790e9f2c68cb391bf" + "reference": "30fa3efe6e736b0d06f5331cc6abe813582c0a26" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-foundation/zipball/662f5257658d4f60deff1bc790e9f2c68cb391bf", - "reference": "662f5257658d4f60deff1bc790e9f2c68cb391bf", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/30fa3efe6e736b0d06f5331cc6abe813582c0a26", + "reference": "30fa3efe6e736b0d06f5331cc6abe813582c0a26", "shasum": "" }, "require": { @@ -7469,7 +7919,7 @@ "description": "Defines an object-oriented layer for the HTTP specification", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/http-foundation/tree/v8.1.8" + "source": "https://github.com/symfony/http-foundation/tree/v8.1.11" }, "funding": [ { @@ -7489,20 +7939,20 @@ "type": "tidelift" } ], - "time": "2026-09-24T07:13:53+00:00" + "time": "2026-11-04T08:39:20+00:00" }, { "name": "symfony/http-kernel", - "version": "v8.1.8", + "version": "v8.1.11", "source": { "type": "git", "url": "https://github.com/symfony/http-kernel.git", - "reference": "51c014e881d8b4ce61e56c0d4105f65b50df786a" + "reference": "460658504e26a2794aa614b4fbe6cf9bac2076fe" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-kernel/zipball/51c014e881d8b4ce61e56c0d4105f65b50df786a", - "reference": "51c014e881d8b4ce61e56c0d4105f65b50df786a", + "url": "https://api.github.com/repos/symfony/http-kernel/zipball/460658504e26a2794aa614b4fbe6cf9bac2076fe", + "reference": "460658504e26a2794aa614b4fbe6cf9bac2076fe", "shasum": "" }, "require": { @@ -7579,7 +8029,7 @@ "description": "Provides a structured process for converting a Request into a Response", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/http-kernel/tree/v8.1.8" + "source": "https://github.com/symfony/http-kernel/tree/v8.1.11" }, "funding": [ { @@ -7599,20 +8049,20 @@ "type": "tidelift" } ], - "time": "2026-09-29T14:08:01+00:00" + "time": "2026-11-04T11:29:46+00:00" }, { "name": "symfony/mailer", - "version": "v8.1.7", + "version": "v8.1.10", "source": { "type": "git", "url": "https://github.com/symfony/mailer.git", - "reference": "8783380ecdafa23d36fc90c5873fd44b635c6e10" + "reference": "4ba81a8f04fbf0bb1691f7bff760b301f1956fd7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/mailer/zipball/8783380ecdafa23d36fc90c5873fd44b635c6e10", - "reference": "8783380ecdafa23d36fc90c5873fd44b635c6e10", + "url": "https://api.github.com/repos/symfony/mailer/zipball/4ba81a8f04fbf0bb1691f7bff760b301f1956fd7", + "reference": "4ba81a8f04fbf0bb1691f7bff760b301f1956fd7", "shasum": "" }, "require": { @@ -7659,7 +8109,7 @@ "description": "Helps sending emails", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/mailer/tree/v8.1.7" + "source": "https://github.com/symfony/mailer/tree/v8.1.10" }, "funding": [ { @@ -7679,20 +8129,20 @@ "type": "tidelift" } ], - "time": "2026-09-15T06:01:24+00:00" + "time": "2026-10-23T17:06:53+00:00" }, { "name": "symfony/mime", - "version": "v8.1.7", + "version": "v8.1.10", "source": { "type": "git", "url": "https://github.com/symfony/mime.git", - "reference": "773ac57f20e2795bdadb65b5b1b5f4850d498283" + "reference": "8d1232052c9cdef170ed9608b3147bca4f61ff69" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/mime/zipball/773ac57f20e2795bdadb65b5b1b5f4850d498283", - "reference": "773ac57f20e2795bdadb65b5b1b5f4850d498283", + "url": "https://api.github.com/repos/symfony/mime/zipball/8d1232052c9cdef170ed9608b3147bca4f61ff69", + "reference": "8d1232052c9cdef170ed9608b3147bca4f61ff69", "shasum": "" }, "require": { @@ -7745,7 +8195,7 @@ "mime-type" ], "support": { - "source": "https://github.com/symfony/mime/tree/v8.1.7" + "source": "https://github.com/symfony/mime/tree/v8.1.10" }, "funding": [ { @@ -7765,20 +8215,20 @@ "type": "tidelift" } ], - "time": "2026-09-04T11:02:17+00:00" + "time": "2026-10-28T17:58:38+00:00" }, { "name": "symfony/options-resolver", - "version": "v8.1.0", + "version": "v8.1.10", "source": { "type": "git", "url": "https://github.com/symfony/options-resolver.git", - "reference": "88f9c561f678a02d54b897014049fa839e33ff82" + "reference": "68cc43038d234c69d510c62f37bd0058b40d548a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/options-resolver/zipball/88f9c561f678a02d54b897014049fa839e33ff82", - "reference": "88f9c561f678a02d54b897014049fa839e33ff82", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/68cc43038d234c69d510c62f37bd0058b40d548a", + "reference": "68cc43038d234c69d510c62f37bd0058b40d548a", "shasum": "" }, "require": { @@ -7816,7 +8266,7 @@ "options" ], "support": { - "source": "https://github.com/symfony/options-resolver/tree/v8.1.0" + "source": "https://github.com/symfony/options-resolver/tree/v8.1.10" }, "funding": [ { @@ -7836,7 +8286,7 @@ "type": "tidelift" } ], - "time": "2026-05-29T05:06:50+00:00" + "time": "2026-10-18T14:56:39+00:00" }, { "name": "symfony/polyfill-ctype", @@ -7923,16 +8373,16 @@ }, { "name": "symfony/polyfill-intl-grapheme", - "version": "v1.43.0", + "version": "v1.43.3", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-intl-grapheme.git", - "reference": "5cac8f4db97208823aa353f59a01faad2da52c75" + "reference": "5a8f33c87aeecffce24e721b5064fab05f4becf8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/5cac8f4db97208823aa353f59a01faad2da52c75", - "reference": "5cac8f4db97208823aa353f59a01faad2da52c75", + "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/5a8f33c87aeecffce24e721b5064fab05f4becf8", + "reference": "5a8f33c87aeecffce24e721b5064fab05f4becf8", "shasum": "" }, "require": { @@ -7981,7 +8431,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.43.0" + "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.43.3" }, "funding": [ { @@ -8001,7 +8451,7 @@ "type": "tidelift" } ], - "time": "2026-09-25T15:46:47+00:00" + "time": "2026-10-15T09:18:53+00:00" }, { "name": "symfony/polyfill-intl-idn", @@ -8177,16 +8627,16 @@ }, { "name": "symfony/polyfill-mbstring", - "version": "v1.43.0", + "version": "v1.43.3", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-mbstring.git", - "reference": "4d5d331bf731e0aedbc6b2f5e61135b7b7996a72" + "reference": "122889ed24dc000165bcbfd77ec412f15cbdfc6a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/4d5d331bf731e0aedbc6b2f5e61135b7b7996a72", - "reference": "4d5d331bf731e0aedbc6b2f5e61135b7b7996a72", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/122889ed24dc000165bcbfd77ec412f15cbdfc6a", + "reference": "122889ed24dc000165bcbfd77ec412f15cbdfc6a", "shasum": "" }, "require": { @@ -8238,7 +8688,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.43.0" + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.43.3" }, "funding": [ { @@ -8258,7 +8708,7 @@ "type": "tidelift" } ], - "time": "2026-09-24T15:19:04+00:00" + "time": "2026-10-28T09:35:49+00:00" }, { "name": "symfony/polyfill-php80", @@ -8344,86 +8794,6 @@ ], "time": "2026-09-25T15:50:05+00:00" }, - { - "name": "symfony/polyfill-php82", - "version": "v1.43.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-php82.git", - "reference": "843bbe8b2a7934307b749751eede0f111f5d1cfc" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php82/zipball/843bbe8b2a7934307b749751eede0f111f5d1cfc", - "reference": "843bbe8b2a7934307b749751eede0f111f5d1cfc", - "shasum": "" - }, - "require": { - "php": ">=7.2" - }, - "type": "library", - "extra": { - "thanks": { - "url": "https://github.com/symfony/polyfill", - "name": "symfony/polyfill" - } - }, - "autoload": { - "files": [ - "bootstrap.php" - ], - "psr-4": { - "Symfony\\Polyfill\\Php82\\": "" - }, - "classmap": [ - "Resources/stubs" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill backporting some PHP 8.2+ features to lower PHP versions", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "polyfill", - "portable", - "shim" - ], - "support": { - "source": "https://github.com/symfony/polyfill-php82/tree/v1.43.0" - }, - "funding": [ - { - "url": "https://symfony.com/sponsor", - "type": "custom" - }, - { - "url": "https://github.com/fabpot", - "type": "github" - }, - { - "url": "https://github.com/nicolas-grekas", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", - "type": "tidelift" - } - ], - "time": "2026-09-25T15:50:05+00:00" - }, { "name": "symfony/polyfill-php84", "version": "v1.43.0", @@ -8664,6 +9034,89 @@ ], "time": "2026-09-25T15:46:47+00:00" }, + { + "name": "symfony/polyfill-time", + "version": "v1.42.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-time.git", + "reference": "ac9f1ed802dd58f37e720388130c088434aa09fc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-time/zipball/ac9f1ed802dd58f37e720388130c088434aa09fc", + "reference": "ac9f1ed802dd58f37e720388130c088434aa09fc", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Time\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ignace Philippe Nyamagana Butera", + "email": "nyamsprod@gmail.com" + }, + { + "name": "Tim Düsterhus", + "email": "tim@tideways-gmbh.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Time API added to PHP 8.6", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "duration", + "polyfill", + "portable", + "shim", + "time" + ], + "support": { + "source": "https://github.com/symfony/polyfill-time/tree/v1.42.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-08-07T13:08:13+00:00" + }, { "name": "symfony/polyfill-uuid", "version": "v1.43.0", @@ -8749,16 +9202,16 @@ }, { "name": "symfony/process", - "version": "v8.1.7", + "version": "v8.1.10", "source": { "type": "git", "url": "https://github.com/symfony/process.git", - "reference": "10823b09358e690df4ff943e24e8492bb1019fc3" + "reference": "08aa69fa0998bb65a089f9e148a2c0f8b391398e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/process/zipball/10823b09358e690df4ff943e24e8492bb1019fc3", - "reference": "10823b09358e690df4ff943e24e8492bb1019fc3", + "url": "https://api.github.com/repos/symfony/process/zipball/08aa69fa0998bb65a089f9e148a2c0f8b391398e", + "reference": "08aa69fa0998bb65a089f9e148a2c0f8b391398e", "shasum": "" }, "require": { @@ -8790,7 +9243,7 @@ "description": "Executes commands in sub-processes", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/process/tree/v8.1.7" + "source": "https://github.com/symfony/process/tree/v8.1.10" }, "funding": [ { @@ -8810,20 +9263,20 @@ "type": "tidelift" } ], - "time": "2026-09-02T12:40:29+00:00" + "time": "2026-10-25T14:40:25+00:00" }, { "name": "symfony/psr-http-message-bridge", - "version": "v8.1.0", + "version": "v8.1.9", "source": { "type": "git", "url": "https://github.com/symfony/psr-http-message-bridge.git", - "reference": "67fd34de15ded1763aa1e330fe345f080a94022c" + "reference": "cfa8f3ac693fec234a91d8745b45ed9a81a0b799" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/psr-http-message-bridge/zipball/67fd34de15ded1763aa1e330fe345f080a94022c", - "reference": "67fd34de15ded1763aa1e330fe345f080a94022c", + "url": "https://api.github.com/repos/symfony/psr-http-message-bridge/zipball/cfa8f3ac693fec234a91d8745b45ed9a81a0b799", + "reference": "cfa8f3ac693fec234a91d8745b45ed9a81a0b799", "shasum": "" }, "require": { @@ -8877,7 +9330,7 @@ "psr-7" ], "support": { - "source": "https://github.com/symfony/psr-http-message-bridge/tree/v8.1.0" + "source": "https://github.com/symfony/psr-http-message-bridge/tree/v8.1.9" }, "funding": [ { @@ -8897,20 +9350,20 @@ "type": "tidelift" } ], - "time": "2026-05-29T05:06:50+00:00" + "time": "2026-10-07T08:21:34+00:00" }, { "name": "symfony/routing", - "version": "v8.1.8", + "version": "v8.1.11", "source": { "type": "git", "url": "https://github.com/symfony/routing.git", - "reference": "e46d741c56485441f37104a3e7eace4e17ed91f9" + "reference": "f3fefc6cad3748d538be970ca81b71f06d7aa8b3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/routing/zipball/e46d741c56485441f37104a3e7eace4e17ed91f9", - "reference": "e46d741c56485441f37104a3e7eace4e17ed91f9", + "url": "https://api.github.com/repos/symfony/routing/zipball/f3fefc6cad3748d538be970ca81b71f06d7aa8b3", + "reference": "f3fefc6cad3748d538be970ca81b71f06d7aa8b3", "shasum": "" }, "require": { @@ -8957,7 +9410,7 @@ "url" ], "support": { - "source": "https://github.com/symfony/routing/tree/v8.1.8" + "source": "https://github.com/symfony/routing/tree/v8.1.11" }, "funding": [ { @@ -8977,20 +9430,20 @@ "type": "tidelift" } ], - "time": "2026-09-28T19:13:15+00:00" + "time": "2026-11-04T08:39:20+00:00" }, { "name": "symfony/service-contracts", - "version": "v3.7.3", + "version": "v3.8.1", "source": { "type": "git", "url": "https://github.com/symfony/service-contracts.git", - "reference": "15e6a07ec2a2c75ceb1b21dd98105ee8456d2257" + "reference": "052852a96fd5e5ebdb617dba22031e41a3300fb5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/service-contracts/zipball/15e6a07ec2a2c75ceb1b21dd98105ee8456d2257", - "reference": "15e6a07ec2a2c75ceb1b21dd98105ee8456d2257", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/052852a96fd5e5ebdb617dba22031e41a3300fb5", + "reference": "052852a96fd5e5ebdb617dba22031e41a3300fb5", "shasum": "" }, "require": { @@ -9008,7 +9461,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -9044,7 +9497,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/service-contracts/tree/v3.7.3" + "source": "https://github.com/symfony/service-contracts/tree/v3.8.1" }, "funding": [ { @@ -9064,20 +9517,20 @@ "type": "tidelift" } ], - "time": "2026-07-27T15:39:01+00:00" + "time": "2026-10-20T17:38:25+00:00" }, { "name": "symfony/string", - "version": "v8.1.7", + "version": "v8.1.10", "source": { "type": "git", "url": "https://github.com/symfony/string.git", - "reference": "d950140b5f56f31901e5b7a0c04ffc3a3deb943c" + "reference": "6c6110979c0150393bbb336170e286d51ab4d76c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/string/zipball/d950140b5f56f31901e5b7a0c04ffc3a3deb943c", - "reference": "d950140b5f56f31901e5b7a0c04ffc3a3deb943c", + "url": "https://api.github.com/repos/symfony/string/zipball/6c6110979c0150393bbb336170e286d51ab4d76c", + "reference": "6c6110979c0150393bbb336170e286d51ab4d76c", "shasum": "" }, "require": { @@ -9134,7 +9587,7 @@ "utf8" ], "support": { - "source": "https://github.com/symfony/string/tree/v8.1.7" + "source": "https://github.com/symfony/string/tree/v8.1.10" }, "funding": [ { @@ -9154,20 +9607,20 @@ "type": "tidelift" } ], - "time": "2026-09-11T14:51:16+00:00" + "time": "2026-10-23T17:06:53+00:00" }, { "name": "symfony/translation", - "version": "v8.1.5", + "version": "v8.1.11", "source": { "type": "git", "url": "https://github.com/symfony/translation.git", - "reference": "d9e1caba0d6b6f9a26710af8a2f88d37f001215a" + "reference": "d065adf56e5508293e80d7c140b0a9e043b63e9c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation/zipball/d9e1caba0d6b6f9a26710af8a2f88d37f001215a", - "reference": "d9e1caba0d6b6f9a26710af8a2f88d37f001215a", + "url": "https://api.github.com/repos/symfony/translation/zipball/d065adf56e5508293e80d7c140b0a9e043b63e9c", + "reference": "d065adf56e5508293e80d7c140b0a9e043b63e9c", "shasum": "" }, "require": { @@ -9227,7 +9680,7 @@ "description": "Provides tools to internationalize your application", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/translation/tree/v8.1.5" + "source": "https://github.com/symfony/translation/tree/v8.1.11" }, "funding": [ { @@ -9247,20 +9700,20 @@ "type": "tidelift" } ], - "time": "2026-08-21T17:47:34+00:00" + "time": "2026-11-01T22:27:46+00:00" }, { "name": "symfony/translation-contracts", - "version": "v3.7.1", + "version": "v3.8.1", "source": { "type": "git", "url": "https://github.com/symfony/translation-contracts.git", - "reference": "ccb206b98faccc511ebae8e5fad50f2dc0b30621" + "reference": "0a3ae917402632fcba2aeddae9c98332f3d7dd05" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/ccb206b98faccc511ebae8e5fad50f2dc0b30621", - "reference": "ccb206b98faccc511ebae8e5fad50f2dc0b30621", + "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/0a3ae917402632fcba2aeddae9c98332f3d7dd05", + "reference": "0a3ae917402632fcba2aeddae9c98332f3d7dd05", "shasum": "" }, "require": { @@ -9273,7 +9726,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -9309,7 +9762,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/translation-contracts/tree/v3.7.1" + "source": "https://github.com/symfony/translation-contracts/tree/v3.8.1" }, "funding": [ { @@ -9329,20 +9782,20 @@ "type": "tidelift" } ], - "time": "2026-06-05T06:23:12+00:00" + "time": "2026-10-03T08:17:19+00:00" }, { "name": "symfony/uid", - "version": "v8.1.8", + "version": "v8.1.9", "source": { "type": "git", "url": "https://github.com/symfony/uid.git", - "reference": "f412a0b5edd75eb3104a93bd0d11fd2ea3da34e4" + "reference": "cb487cf30380f0b0b090973bb9c0588193c06685" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/uid/zipball/f412a0b5edd75eb3104a93bd0d11fd2ea3da34e4", - "reference": "f412a0b5edd75eb3104a93bd0d11fd2ea3da34e4", + "url": "https://api.github.com/repos/symfony/uid/zipball/cb487cf30380f0b0b090973bb9c0588193c06685", + "reference": "cb487cf30380f0b0b090973bb9c0588193c06685", "shasum": "" }, "require": { @@ -9387,7 +9840,7 @@ "uuid" ], "support": { - "source": "https://github.com/symfony/uid/tree/v8.1.8" + "source": "https://github.com/symfony/uid/tree/v8.1.9" }, "funding": [ { @@ -9407,20 +9860,20 @@ "type": "tidelift" } ], - "time": "2026-09-23T17:45:45+00:00" + "time": "2026-10-12T14:32:04+00:00" }, { "name": "symfony/var-dumper", - "version": "v8.1.7", + "version": "v8.1.10", "source": { "type": "git", "url": "https://github.com/symfony/var-dumper.git", - "reference": "741a8c4c948b0bb9bd3653daacd3644c73c40ea5" + "reference": "3412a5af7d34a19515a77890fc804fe8e50d1a4f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/var-dumper/zipball/741a8c4c948b0bb9bd3653daacd3644c73c40ea5", - "reference": "741a8c4c948b0bb9bd3653daacd3644c73c40ea5", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/3412a5af7d34a19515a77890fc804fe8e50d1a4f", + "reference": "3412a5af7d34a19515a77890fc804fe8e50d1a4f", "shasum": "" }, "require": { @@ -9474,7 +9927,7 @@ "dump" ], "support": { - "source": "https://github.com/symfony/var-dumper/tree/v8.1.7" + "source": "https://github.com/symfony/var-dumper/tree/v8.1.10" }, "funding": [ { @@ -9494,7 +9947,7 @@ "type": "tidelift" } ], - "time": "2026-09-03T16:02:27+00:00" + "time": "2026-10-26T21:55:04+00:00" }, { "name": "tbachert/spi", @@ -9949,16 +10402,16 @@ }, { "name": "vlucas/phpdotenv", - "version": "v5.7.0", + "version": "v5.8.0", "source": { "type": "git", - "url": "https://github.com/vlucas/phpdotenv.git", - "reference": "301c07936b16d88628b126b01d082ba153cf4c40" + "url": "https://github.com/phpdotenv/phpdotenv.git", + "reference": "96149103e62ac67e915f6d2ef59b72dee2e011e0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/301c07936b16d88628b126b01d082ba153cf4c40", - "reference": "301c07936b16d88628b126b01d082ba153cf4c40", + "url": "https://api.github.com/repos/phpdotenv/phpdotenv/zipball/96149103e62ac67e915f6d2ef59b72dee2e011e0", + "reference": "96149103e62ac67e915f6d2ef59b72dee2e011e0", "shasum": "" }, "require": { @@ -9985,7 +10438,7 @@ "forward-command": false }, "branch-alias": { - "dev-master": "5.6-dev" + "dev-master": "5.8-dev" } }, "autoload": { @@ -10016,8 +10469,8 @@ "environment" ], "support": { - "issues": "https://github.com/vlucas/phpdotenv/issues", - "source": "https://github.com/vlucas/phpdotenv/tree/v5.7.0" + "issues": "https://github.com/phpdotenv/phpdotenv/issues", + "source": "https://github.com/phpdotenv/phpdotenv/tree/v5.8.0" }, "funding": [ { @@ -10029,7 +10482,7 @@ "type": "tidelift" } ], - "time": "2026-08-24T18:07:49+00:00" + "time": "2026-10-25T16:26:19+00:00" }, { "name": "voku/portable-ascii", @@ -10279,16 +10732,16 @@ }, { "name": "barryvdh/laravel-ide-helper", - "version": "v3.7.0", + "version": "v3.8.0", "source": { "type": "git", "url": "https://github.com/barryvdh/laravel-ide-helper.git", - "reference": "ad7e37676f1ff985d55ef1b6b96a0c0a40f2609a" + "reference": "f9521af2a0ed5ff1d70386cac3fae547a96be947" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/barryvdh/laravel-ide-helper/zipball/ad7e37676f1ff985d55ef1b6b96a0c0a40f2609a", - "reference": "ad7e37676f1ff985d55ef1b6b96a0c0a40f2609a", + "url": "https://api.github.com/repos/barryvdh/laravel-ide-helper/zipball/f9521af2a0ed5ff1d70386cac3fae547a96be947", + "reference": "f9521af2a0ed5ff1d70386cac3fae547a96be947", "shasum": "" }, "require": { @@ -10325,7 +10778,7 @@ ] }, "branch-alias": { - "dev-master": "3.6-dev" + "dev-master": "3.7-dev" } }, "autoload": { @@ -10358,7 +10811,7 @@ ], "support": { "issues": "https://github.com/barryvdh/laravel-ide-helper/issues", - "source": "https://github.com/barryvdh/laravel-ide-helper/tree/v3.7.0" + "source": "https://github.com/barryvdh/laravel-ide-helper/tree/v3.8.0" }, "funding": [ { @@ -10370,7 +10823,7 @@ "type": "github" } ], - "time": "2026-03-17T14:12:51+00:00" + "time": "2026-09-15T12:58:37+00:00" }, { "name": "barryvdh/reflection-docblock", @@ -10589,16 +11042,16 @@ }, { "name": "composer/class-map-generator", - "version": "1.8.0", + "version": "1.9.0", "source": { "type": "git", "url": "https://github.com/composer/class-map-generator.git", - "reference": "c0efbeb2f3fd7e23c7f180a59765c0b48a31fbc4" + "reference": "5fa48e0e1992ea8a786df3ceca80625c9a643b75" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/composer/class-map-generator/zipball/c0efbeb2f3fd7e23c7f180a59765c0b48a31fbc4", - "reference": "c0efbeb2f3fd7e23c7f180a59765c0b48a31fbc4", + "url": "https://api.github.com/repos/composer/class-map-generator/zipball/5fa48e0e1992ea8a786df3ceca80625c9a643b75", + "reference": "5fa48e0e1992ea8a786df3ceca80625c9a643b75", "shasum": "" }, "require": { @@ -10642,7 +11095,7 @@ ], "support": { "issues": "https://github.com/composer/class-map-generator/issues", - "source": "https://github.com/composer/class-map-generator/tree/1.8.0" + "source": "https://github.com/composer/class-map-generator/tree/1.9.0" }, "funding": [ { @@ -10654,7 +11107,7 @@ "type": "github" } ], - "time": "2026-09-25T15:24:19+00:00" + "time": "2026-11-03T10:10:19+00:00" }, { "name": "composer/xdebug-handler", @@ -10820,16 +11273,16 @@ }, { "name": "dg/bypass-finals", - "version": "v1.11.0", + "version": "v1.11.1", "source": { "type": "git", "url": "https://github.com/dg/bypass-finals.git", - "reference": "b21595bdd1937e9ac912d68380dc85a65d77285f" + "reference": "295d8549a99848afc7fe39099d9bfac6fceb0e75" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/dg/bypass-finals/zipball/b21595bdd1937e9ac912d68380dc85a65d77285f", - "reference": "b21595bdd1937e9ac912d68380dc85a65d77285f", + "url": "https://api.github.com/repos/dg/bypass-finals/zipball/295d8549a99848afc7fe39099d9bfac6fceb0e75", + "reference": "295d8549a99848afc7fe39099d9bfac6fceb0e75", "shasum": "" }, "require": { @@ -10859,36 +11312,38 @@ "homepage": "https://davidgrudl.com" } ], - "description": "Removes final keyword from source code on-the-fly and allows mocking of final methods and classes", + "description": "🔓 BypassFinals: removes final and readonly from your code on the fly, so you can mock final classes and methods in PHPUnit, Mockery or Nette Tester.", "keywords": [ - "finals", + "final", + "mock final class", + "mockery", "mocking", "phpunit", - "testing", - "unit" + "readonly", + "testing" ], "support": { "issues": "https://github.com/dg/bypass-finals/issues", - "source": "https://github.com/dg/bypass-finals/tree/v1.11.0" + "source": "https://github.com/dg/bypass-finals/tree/v1.11.1" }, - "time": "2026-07-24T12:24:07+00:00" + "time": "2026-10-23T13:27:43+00:00" }, { "name": "doctrine/deprecations", - "version": "1.1.6", + "version": "1.2.0", "source": { "type": "git", "url": "https://github.com/doctrine/deprecations.git", - "reference": "d4fe3e6fd9bb9e72557a19674f44d8ac7db4c6ca" + "reference": "d2e16653a734c8784c1851ad68b02f997b53ca82" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/deprecations/zipball/d4fe3e6fd9bb9e72557a19674f44d8ac7db4c6ca", - "reference": "d4fe3e6fd9bb9e72557a19674f44d8ac7db4c6ca", + "url": "https://api.github.com/repos/doctrine/deprecations/zipball/d2e16653a734c8784c1851ad68b02f997b53ca82", + "reference": "d2e16653a734c8784c1851ad68b02f997b53ca82", "shasum": "" }, "require": { - "php": "^7.1 || ^8.0" + "php": "^7.4 || ^8.0" }, "conflict": { "phpunit/phpunit": "<=7.5 || >=14" @@ -10917,9 +11372,9 @@ "homepage": "https://www.doctrine-project.org/", "support": { "issues": "https://github.com/doctrine/deprecations/issues", - "source": "https://github.com/doctrine/deprecations/tree/1.1.6" + "source": "https://github.com/doctrine/deprecations/tree/1.2.0" }, - "time": "2026-02-07T07:09:04+00:00" + "time": "2026-11-11T10:04:49+00:00" }, { "name": "dragon-code/contracts", @@ -10983,77 +11438,9 @@ "type": "yoomoney" } ], + "abandoned": true, "time": "2026-03-17T21:50:20+00:00" }, - { - "name": "dragon-code/pretty-array", - "version": "4.2.0", - "source": { - "type": "git", - "url": "https://github.com/TheDragonCode/pretty-array.git", - "reference": "b94034d92172a5d14a578822d68b2a8f8b5388e0" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/TheDragonCode/pretty-array/zipball/b94034d92172a5d14a578822d68b2a8f8b5388e0", - "reference": "b94034d92172a5d14a578822d68b2a8f8b5388e0", - "shasum": "" - }, - "require": { - "dragon-code/contracts": "^2.20", - "dragon-code/support": "^6.11.2", - "ext-dom": "*", - "ext-mbstring": "*", - "php": "^8.0" - }, - "require-dev": { - "phpunit/phpunit": "^9.6 || ^10.0 || ^11.0 || ^12.0" - }, - "suggest": { - "symfony/thanks": "Give thanks (in the form of a GitHub) to your fellow PHP package maintainers" - }, - "type": "library", - "autoload": { - "psr-4": { - "DragonCode\\PrettyArray\\": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Andrey Helldar", - "email": "helldar@dragon-code.pro", - "homepage": "https://dragon-code.pro" - } - ], - "description": "Simple conversion of an array to a pretty view", - "keywords": [ - "andrey helldar", - "array", - "dragon", - "dragon code", - "pretty", - "pretty array" - ], - "support": { - "issues": "https://github.com/TheDragonCode/pretty-array/issues", - "source": "https://github.com/TheDragonCode/pretty-array" - }, - "funding": [ - { - "url": "https://boosty.to/dragon-code", - "type": "boosty" - }, - { - "url": "https://yoomoney.ru/to/410012608840929", - "type": "yoomoney" - } - ], - "time": "2025-02-24T15:35:24+00:00" - }, { "name": "dragon-code/support", "version": "6.17.1", @@ -11146,30 +11533,32 @@ "type": "yoomoney" } ], + "abandoned": "illuminate/support", "time": "2026-04-03T15:06:29+00:00" }, { "name": "driftingly/rector-laravel", - "version": "2.6.2", + "version": "2.7.3", "source": { "type": "git", "url": "https://github.com/driftingly/rector-laravel.git", - "reference": "c0f9a2ff7365cec45d4dc64223608e7cec74604a" + "reference": "699f25bda7efcbe98cf8ff9c9e687da76ce0d8c5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/driftingly/rector-laravel/zipball/c0f9a2ff7365cec45d4dc64223608e7cec74604a", - "reference": "c0f9a2ff7365cec45d4dc64223608e7cec74604a", + "url": "https://api.github.com/repos/driftingly/rector-laravel/zipball/699f25bda7efcbe98cf8ff9c9e687da76ce0d8c5", + "reference": "699f25bda7efcbe98cf8ff9c9e687da76ce0d8c5", "shasum": "" }, "require": { "php": ">=8.3", - "rector/rector": "^2.6.4", + "rector/rector": "^2.8", "symplify/rule-doc-generator-contracts": "^11.2", "webmozart/assert": "^1.11 || ^2.0" }, "require-dev": { - "boundwize/structarmed": "^0.16", + "boundwize/structarmed": "^0.19", + "illuminate/support": "^13.0", "nette/utils": "^4.0", "nikic/php-parser": "^5.6", "phpstan/extension-installer": "^1.3", @@ -11182,6 +11571,9 @@ "tightenco/duster": "^3.1", "tracy/tracy": "^2.10" }, + "suggest": { + "illuminate/support": "Required by RelationTableStringToPivotClassRector, which uses Illuminate\\Support\\Str at runtime to resolve pivot models from table names (^8.0 || ^9.0 || ^10.0 || ^11.0 || ^12.0 || ^13.0)." + }, "type": "rector-extension", "extra": { "rector": { @@ -11200,24 +11592,31 @@ "MIT" ], "description": "Rector upgrades rules for Laravel Framework", + "keywords": [ + "dev", + "laravel", + "rector", + "refactoring", + "upgrade" + ], "support": { "issues": "https://github.com/driftingly/rector-laravel/issues", - "source": "https://github.com/driftingly/rector-laravel/tree/2.6.2" + "source": "https://github.com/driftingly/rector-laravel/tree/2.7.3" }, - "time": "2026-08-29T21:42:57+00:00" + "time": "2026-10-27T12:37:16+00:00" }, { "name": "entropy/entropy", - "version": "0.4.29", + "version": "0.4.36", "source": { "type": "git", "url": "https://github.com/TomasVotruba/entropy.git", - "reference": "e2dfbd791ab7acea5aed40deefa00b12ad902ca2" + "reference": "9f08272a96275d22a9d9808a32581392920626db" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/TomasVotruba/entropy/zipball/e2dfbd791ab7acea5aed40deefa00b12ad902ca2", - "reference": "e2dfbd791ab7acea5aed40deefa00b12ad902ca2", + "url": "https://api.github.com/repos/TomasVotruba/entropy/zipball/9f08272a96275d22a9d9808a32581392920626db", + "reference": "9f08272a96275d22a9d9808a32581392920626db", "shasum": "" }, "require": { @@ -11253,9 +11652,9 @@ "description": "Entropy framework", "support": { "issues": "https://github.com/TomasVotruba/entropy/issues", - "source": "https://github.com/TomasVotruba/entropy/tree/0.4.29" + "source": "https://github.com/TomasVotruba/entropy/tree/0.4.36" }, - "time": "2026-10-08T07:55:55+00:00" + "time": "2026-10-26T16:46:17+00:00" }, { "name": "fakerphp/faker", @@ -11384,16 +11783,16 @@ }, { "name": "filp/whoops", - "version": "2.18.6", + "version": "2.19.3", "source": { "type": "git", "url": "https://github.com/filp/whoops.git", - "reference": "7d0a2cde892089bb09372f4366e9b960eb3001a9" + "reference": "d5480d53f10069dc4620a39f87e38e8945d47322" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/filp/whoops/zipball/7d0a2cde892089bb09372f4366e9b960eb3001a9", - "reference": "7d0a2cde892089bb09372f4366e9b960eb3001a9", + "url": "https://api.github.com/repos/filp/whoops/zipball/d5480d53f10069dc4620a39f87e38e8945d47322", + "reference": "d5480d53f10069dc4620a39f87e38e8945d47322", "shasum": "" }, "require": { @@ -11443,7 +11842,7 @@ ], "support": { "issues": "https://github.com/filp/whoops/issues", - "source": "https://github.com/filp/whoops/tree/2.18.6" + "source": "https://github.com/filp/whoops/tree/2.19.3" }, "funding": [ { @@ -11451,7 +11850,7 @@ "type": "github" } ], - "time": "2026-10-03T17:03:57+00:00" + "time": "2026-11-09T23:30:17+00:00" }, { "name": "hamcrest/hamcrest-php", @@ -11551,16 +11950,16 @@ }, { "name": "larastan/larastan", - "version": "v3.13.0", + "version": "v3.15.0", "source": { "type": "git", "url": "https://github.com/larastan/larastan.git", - "reference": "24ee69a7705ffc7c2cd8a3c96a5f498a4c2de5e3" + "reference": "ffb29680700b7e56000183ddacd68fab991f690b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/larastan/larastan/zipball/24ee69a7705ffc7c2cd8a3c96a5f498a4c2de5e3", - "reference": "24ee69a7705ffc7c2cd8a3c96a5f498a4c2de5e3", + "url": "https://api.github.com/repos/larastan/larastan/zipball/ffb29680700b7e56000183ddacd68fab991f690b", + "reference": "ffb29680700b7e56000183ddacd68fab991f690b", "shasum": "" }, "require": { @@ -11573,13 +11972,13 @@ "illuminate/pipeline": "^11.44.2 || ^12.4.1 || ^13", "illuminate/support": "^11.44.2 || ^12.4.1 || ^13", "php": "^8.2", - "phpstan/phpstan": "^2.3.0" + "phpstan/phpstan": "^2.3.5" }, "require-dev": { "doctrine/coding-standard": "^14", "laravel/framework": "^11.44.2 || ^12.7.2 || ^13", "mockery/mockery": "^1.6.12", - "nikic/php-parser": "^5.4", + "nikic/php-parser": "^5.6", "orchestra/canvas": "^v9.2.2 || ^10.0.1 || ^11", "orchestra/testbench-core": "^9.12.0 || ^10.1 || ^11", "phpstan/phpstan-deprecation-rules": "^2.0.1", @@ -11628,7 +12027,7 @@ ], "support": { "issues": "https://github.com/larastan/larastan/issues", - "source": "https://github.com/larastan/larastan/tree/v3.13.0" + "source": "https://github.com/larastan/larastan/tree/v3.15.0" }, "funding": [ { @@ -11636,7 +12035,7 @@ "type": "github" } ], - "time": "2026-10-07T14:14:28+00:00" + "time": "2026-11-11T15:06:29+00:00" }, { "name": "laravel-lang/actions", @@ -11717,16 +12116,16 @@ }, { "name": "laravel-lang/attributes", - "version": "2.16.4", + "version": "2.16.5", "source": { "type": "git", "url": "https://github.com/Laravel-Lang/attributes.git", - "reference": "4a0de72632bb1862532977fd76ed6be9c1cc65af" + "reference": "313d064f7fb1262a98349157d9754dafc5fdead6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Laravel-Lang/attributes/zipball/4a0de72632bb1862532977fd76ed6be9c1cc65af", - "reference": "4a0de72632bb1862532977fd76ed6be9c1cc65af", + "url": "https://api.github.com/repos/Laravel-Lang/attributes/zipball/313d064f7fb1262a98349157d9754dafc5fdead6", + "reference": "313d064f7fb1262a98349157d9754dafc5fdead6", "shasum": "" }, "require": { @@ -11780,7 +12179,7 @@ ], "support": { "issues": "https://github.com/Laravel-Lang/attributes/issues", - "source": "https://github.com/Laravel-Lang/attributes/tree/2.16.4" + "source": "https://github.com/Laravel-Lang/attributes/tree/2.16.5" }, "funding": [ { @@ -11792,20 +12191,20 @@ "type": "yoomoney" } ], - "time": "2026-05-30T12:11:05+00:00" + "time": "2026-11-04T11:47:31+00:00" }, { "name": "laravel-lang/common", - "version": "6.8.0", + "version": "6.9.0", "source": { "type": "git", "url": "https://github.com/Laravel-Lang/common.git", - "reference": "f1e3383f94c4f157f0f41324792382bf2dd84d52" + "reference": "7c7c00a493ec6718d09559470b51110b42193cfa" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Laravel-Lang/common/zipball/f1e3383f94c4f157f0f41324792382bf2dd84d52", - "reference": "f1e3383f94c4f157f0f41324792382bf2dd84d52", + "url": "https://api.github.com/repos/Laravel-Lang/common/zipball/7c7c00a493ec6718d09559470b51110b42193cfa", + "reference": "7c7c00a493ec6718d09559470b51110b42193cfa", "shasum": "" }, "require": { @@ -11823,7 +12222,6 @@ "php": "^8.1" }, "require-dev": { - "dragon-code/support": "^6.13", "orchestra/testbench": "^8.17 || ^9.1.2 || ^10.0 || ^11.0", "phpunit/phpunit": "^10.5.20 || ^11.0 || ^12.0", "symfony/var-dumper": "^6.4 || ^7.1.1 || ^8.0" @@ -11890,7 +12288,7 @@ "type": "yoomoney" } ], - "time": "2026-03-17T23:15:14+00:00" + "time": "2026-11-07T20:54:11+00:00" }, { "name": "laravel-lang/config", @@ -12106,16 +12504,16 @@ }, { "name": "laravel-lang/lang", - "version": "15.37.3", + "version": "15.37.7", "source": { "type": "git", "url": "https://github.com/Laravel-Lang/lang.git", - "reference": "a3504212776c77984273beb9b7ef9ecbacc2e4e4" + "reference": "07c03c1085fd666e6a9c08328ccd414eff4b00a8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Laravel-Lang/lang/zipball/a3504212776c77984273beb9b7ef9ecbacc2e4e4", - "reference": "a3504212776c77984273beb9b7ef9ecbacc2e4e4", + "url": "https://api.github.com/repos/Laravel-Lang/lang/zipball/07c03c1085fd666e6a9c08328ccd414eff4b00a8", + "reference": "07c03c1085fd666e6a9c08328ccd414eff4b00a8", "shasum": "" }, "require": { @@ -12176,7 +12574,7 @@ "type": "yoomoney" } ], - "time": "2026-10-01T08:03:34+00:00" + "time": "2026-11-07T19:09:28+00:00" }, { "name": "laravel-lang/locale-list", @@ -12320,21 +12718,20 @@ }, { "name": "laravel-lang/models", - "version": "1.7.0", + "version": "1.8.0", "source": { "type": "git", "url": "https://github.com/Laravel-Lang/models.git", - "reference": "a9aa0205ca019f4459ace26b0432b3b6d1886f66" + "reference": "8a1e52c3f92fc65feb7e2b4c82637f7094ad93e1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Laravel-Lang/models/zipball/a9aa0205ca019f4459ace26b0432b3b6d1886f66", - "reference": "a9aa0205ca019f4459ace26b0432b3b6d1886f66", + "url": "https://api.github.com/repos/Laravel-Lang/models/zipball/8a1e52c3f92fc65feb7e2b4c82637f7094ad93e1", + "reference": "8a1e52c3f92fc65feb7e2b4c82637f7094ad93e1", "shasum": "" }, "require": { "composer/class-map-generator": "^1.3", - "dragon-code/support": "^6.13", "illuminate/database": "^10.0 || ^11.0 || ^12.0 || ^13.0", "illuminate/support": "^10.0 || ^11.0 || ^12.0 || ^13.0", "laravel-lang/config": "^1.12", @@ -12410,7 +12807,7 @@ "type": "yoomoney" } ], - "time": "2026-03-17T23:00:20+00:00" + "time": "2026-11-10T17:54:56+00:00" }, { "name": "laravel-lang/moonshine", @@ -12574,20 +12971,19 @@ }, { "name": "laravel-lang/native-currency-names", - "version": "1.10.0", + "version": "1.11.0", "source": { "type": "git", "url": "https://github.com/Laravel-Lang/native-currency-names.git", - "reference": "7ebe95a9942bebf6afd61986fa18c82dade3d583" + "reference": "bc8548ecd9fc2956ad0fd1b4275ed1fe23085bfe" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Laravel-Lang/native-currency-names/zipball/7ebe95a9942bebf6afd61986fa18c82dade3d583", - "reference": "7ebe95a9942bebf6afd61986fa18c82dade3d583", + "url": "https://api.github.com/repos/Laravel-Lang/native-currency-names/zipball/bc8548ecd9fc2956ad0fd1b4275ed1fe23085bfe", + "reference": "bc8548ecd9fc2956ad0fd1b4275ed1fe23085bfe", "shasum": "" }, "require": { - "dragon-code/support": "^6.11", "ext-json": "*", "illuminate/collections": "^10.0 || ^11.0 || ^12.0 || ^13.0", "php": "^8.1" @@ -12649,24 +13045,23 @@ "type": "yoomoney" } ], - "time": "2026-06-20T16:50:37+00:00" + "time": "2026-11-11T18:05:32+00:00" }, { "name": "laravel-lang/native-locale-names", - "version": "2.9.0", + "version": "2.10.0", "source": { "type": "git", "url": "https://github.com/Laravel-Lang/native-locale-names.git", - "reference": "e5925182bad34654203a5d93544357ca00a6d9c0" + "reference": "29d247897855a7bff9910090c94a262e7933d86d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Laravel-Lang/native-locale-names/zipball/e5925182bad34654203a5d93544357ca00a6d9c0", - "reference": "e5925182bad34654203a5d93544357ca00a6d9c0", + "url": "https://api.github.com/repos/Laravel-Lang/native-locale-names/zipball/29d247897855a7bff9910090c94a262e7933d86d", + "reference": "29d247897855a7bff9910090c94a262e7933d86d", "shasum": "" }, "require": { - "dragon-code/support": "^6.11", "ext-json": "*", "php": "^8.1" }, @@ -12725,26 +13120,24 @@ "type": "yoomoney" } ], - "time": "2026-06-20T16:52:11+00:00" + "time": "2026-11-10T18:05:52+00:00" }, { "name": "laravel-lang/publisher", - "version": "16.8.0", + "version": "16.9.0", "source": { "type": "git", "url": "https://github.com/Laravel-Lang/publisher.git", - "reference": "e5d3383f5385c2102f8a0d3dbe488ed86cd0250f" + "reference": "b0d1e7a60d6504ac2f2204315defd243cabe8385" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Laravel-Lang/publisher/zipball/e5d3383f5385c2102f8a0d3dbe488ed86cd0250f", - "reference": "e5d3383f5385c2102f8a0d3dbe488ed86cd0250f", + "url": "https://api.github.com/repos/Laravel-Lang/publisher/zipball/b0d1e7a60d6504ac2f2204315defd243cabe8385", + "reference": "b0d1e7a60d6504ac2f2204315defd243cabe8385", "shasum": "" }, "require": { "composer/semver": "^3.4", - "dragon-code/pretty-array": "^4.1", - "dragon-code/support": "^6.11.3", "ext-json": "*", "illuminate/collections": "^10.0 || ^11.0 || ^12.0 || ^13.0", "illuminate/console": "^10.0 || ^11.0 || ^12.0 || ^13.0", @@ -12833,7 +13226,7 @@ "type": "yoomoney" } ], - "time": "2026-03-17T22:56:20+00:00" + "time": "2026-11-07T09:39:33+00:00" }, { "name": "laravel-lang/routes", @@ -12925,16 +13318,16 @@ }, { "name": "laravel-lang/starter-kits", - "version": "1.16.1", + "version": "1.17.1", "source": { "type": "git", "url": "https://github.com/Laravel-Lang/starter-kits.git", - "reference": "87c00c77bbb73385d0526b35dbe07ea2bbfc32db" + "reference": "1de9547644309a18da42647546beaa1c163a8f35" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Laravel-Lang/starter-kits/zipball/87c00c77bbb73385d0526b35dbe07ea2bbfc32db", - "reference": "87c00c77bbb73385d0526b35dbe07ea2bbfc32db", + "url": "https://api.github.com/repos/Laravel-Lang/starter-kits/zipball/1de9547644309a18da42647546beaa1c163a8f35", + "reference": "1de9547644309a18da42647546beaa1c163a8f35", "shasum": "" }, "require": { @@ -12986,7 +13379,7 @@ ], "support": { "issues": "https://github.com/Laravel-Lang/starter-kits/issues", - "source": "https://github.com/Laravel-Lang/starter-kits/tree/1.16.1" + "source": "https://github.com/Laravel-Lang/starter-kits/tree/1.17.1" }, "funding": [ { @@ -12998,20 +13391,20 @@ "type": "yoomoney" } ], - "time": "2026-07-16T18:13:26+00:00" + "time": "2026-11-04T11:46:44+00:00" }, { "name": "laravel/pint", - "version": "v1.32.1", + "version": "v1.32.3", "source": { "type": "git", "url": "https://github.com/laravel/pint.git", - "reference": "006bd7825eb01daf92959d060b89cd9514fe4253" + "reference": "1cf8e0320bed4b3c6e51df92039a5636c3887728" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/pint/zipball/006bd7825eb01daf92959d060b89cd9514fe4253", - "reference": "006bd7825eb01daf92959d060b89cd9514fe4253", + "url": "https://api.github.com/repos/laravel/pint/zipball/1cf8e0320bed4b3c6e51df92039a5636c3887728", + "reference": "1cf8e0320bed4b3c6e51df92039a5636c3887728", "shasum": "" }, "require": { @@ -13022,15 +13415,15 @@ "php": "^8.3.0" }, "require-dev": { - "composer/semver": "^3.4.4", - "friendsofphp/php-cs-fixer": "^3.95.25", - "illuminate/view": "^13.31.0", - "larastan/larastan": "^3.11.0", + "composer/semver": "^3.6.0", + "friendsofphp/php-cs-fixer": "^3.95.30", + "illuminate/view": "^13.42.0", + "larastan/larastan": "^3.15.0", "laravel-zero/framework": "^13.0.0", - "laravel/agent-detector": "^2.0.2", - "laravel/prompts": "^0.3.24", + "laravel/agent-detector": "^2.0.5", + "laravel/prompts": "^0.3.27", "mockery/mockery": "^1.6.15", - "nunomaduro/termwind": "^2.4.0", + "nunomaduro/termwind": "^2.4.1", "pestphp/pest": "^4.7.8" }, "bin": [ @@ -13068,7 +13461,7 @@ "issues": "https://github.com/laravel/pint/issues", "source": "https://github.com/laravel/pint" }, - "time": "2026-09-10T10:47:55+00:00" + "time": "2026-11-11T16:45:13+00:00" }, { "name": "mockery/mockery", @@ -13214,36 +13607,36 @@ }, { "name": "nunomaduro/collision", - "version": "v8.9.5", + "version": "v8.9.6", "source": { "type": "git", "url": "https://github.com/nunomaduro/collision.git", - "reference": "fb53eacd509a1d303858e2d20cfebf2d630254ec" + "reference": "68806f9257968f23775bee62970cb90925b79d51" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nunomaduro/collision/zipball/fb53eacd509a1d303858e2d20cfebf2d630254ec", - "reference": "fb53eacd509a1d303858e2d20cfebf2d630254ec", + "url": "https://api.github.com/repos/nunomaduro/collision/zipball/68806f9257968f23775bee62970cb90925b79d51", + "reference": "68806f9257968f23775bee62970cb90925b79d51", "shasum": "" }, "require": { - "filp/whoops": "^2.18.4", - "nunomaduro/termwind": "^2.4.0", + "filp/whoops": "^2.19.3", + "nunomaduro/termwind": "^2.4.1", "php": "^8.2.0", - "symfony/console": "^7.4.14 || ^8.1.1" + "symfony/console": "^7.4.23 || ^8.1.11" }, "conflict": { "laravel/framework": "<11.48.0 || >=14.0.0", "phpunit/phpunit": "<11.5.50 || >=14.0.0" }, "require-dev": { - "brianium/paratest": "^7.8.5", - "larastan/larastan": "^3.10.0", - "laravel/framework": "^11.48.0 || ^12.56.0 || ^13.20.0", - "laravel/pint": "^1.29.3", - "orchestra/testbench-core": "^9.12.0 || ^10.12.1 || ^11.3.5", - "pestphp/pest": "^3.8.5 || ^4.7.5 || ^5.0.0", - "sebastian/environment": "^7.2.1 || ^8.1.2 || ^9.3.2" + "brianium/paratest": "^7.8.6", + "larastan/larastan": "^3.14.0", + "laravel/framework": "^11.57.1 || ^12.72.0 || ^13.40.0", + "laravel/pint": "^1.30.4", + "orchestra/testbench-core": "^9.24.0 || ^10.16.0 || ^11.6.0", + "pestphp/pest": "^3.8.7 || ^4.7.8 || ^5.3.5", + "sebastian/environment": "^7.2.1 || ^8.1.2 || ^9.3.3" }, "type": "library", "extra": { @@ -13306,7 +13699,7 @@ "type": "patreon" } ], - "time": "2026-07-15T19:09:14+00:00" + "time": "2026-11-10T17:06:52+00:00" }, { "name": "nunomaduro/mock-final-classes", @@ -14420,16 +14813,16 @@ }, { "name": "phpstan/phpdoc-parser", - "version": "2.3.6", + "version": "2.4.1", "source": { "type": "git", "url": "https://github.com/phpstan/phpdoc-parser.git", - "reference": "1427af4647235b4a73b13940b1f1258d3584f36e" + "reference": "af8e840551031d254cfdb3a18a62c3470a309c10" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/1427af4647235b4a73b13940b1f1258d3584f36e", - "reference": "1427af4647235b4a73b13940b1f1258d3584f36e", + "url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/af8e840551031d254cfdb3a18a62c3470a309c10", + "reference": "af8e840551031d254cfdb3a18a62c3470a309c10", "shasum": "" }, "require": { @@ -14461,17 +14854,17 @@ "description": "PHPDoc parser with support for nullable, intersection and generic types", "support": { "issues": "https://github.com/phpstan/phpdoc-parser/issues", - "source": "https://github.com/phpstan/phpdoc-parser/tree/2.3.6" + "source": "https://github.com/phpstan/phpdoc-parser/tree/2.4.1" }, - "time": "2026-09-27T20:07:45+00:00" + "time": "2026-10-30T19:36:28+00:00" }, { "name": "phpstan/phpstan", - "version": "2.3.0", + "version": "2.3.5", "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/b1f9890d9af53a25c58129e78f0aadd31f90d7f4", - "reference": "b1f9890d9af53a25c58129e78f0aadd31f90d7f4", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/645a1bd6bead15fc1b8474137467961d0fa30a79", + "reference": "645a1bd6bead15fc1b8474137467961d0fa30a79", "shasum": "" }, "require": { @@ -14527,7 +14920,7 @@ "type": "github" } ], - "time": "2026-10-06T06:15:36+00:00" + "time": "2026-11-03T12:14:22+00:00" }, { "name": "phpunit/php-code-coverage", @@ -15050,21 +15443,21 @@ }, { "name": "rector/rector", - "version": "2.7.0", + "version": "2.8.4", "source": { "type": "git", "url": "https://github.com/rectorphp/rector.git", - "reference": "4d6a39b7fff302cac0ce90cd959a53c2f6a32776" + "reference": "55acbd956d7e3907f7d21aab54edd68a310609e6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/rectorphp/rector/zipball/4d6a39b7fff302cac0ce90cd959a53c2f6a32776", - "reference": "4d6a39b7fff302cac0ce90cd959a53c2f6a32776", + "url": "https://api.github.com/repos/rectorphp/rector/zipball/55acbd956d7e3907f7d21aab54edd68a310609e6", + "reference": "55acbd956d7e3907f7d21aab54edd68a310609e6", "shasum": "" }, "require": { "php": "^7.4|^8.0", - "phpstan/phpstan": "^2.3.0" + "phpstan/phpstan": "^2.3.5" }, "conflict": { "rector/rector-doctrine": "*", @@ -15095,7 +15488,7 @@ ], "support": { "issues": "https://github.com/rectorphp/rector/issues", - "source": "https://github.com/rectorphp/rector/tree/2.7.0" + "source": "https://github.com/rectorphp/rector/tree/2.8.4" }, "funding": [ { @@ -15103,7 +15496,7 @@ "type": "github" } ], - "time": "2026-10-06T08:46:45+00:00" + "time": "2026-11-03T18:48:08+00:00" }, { "name": "sebastian/cli-parser", @@ -15974,16 +16367,16 @@ }, { "name": "sebastian/version", - "version": "6.0.1", + "version": "6.0.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/version.git", - "reference": "9e935a16187e14f39b0e79910dabd614972cdb26" + "reference": "a8b6643a19ba6c8125a473623e45fb8cbb0e4159" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/9e935a16187e14f39b0e79910dabd614972cdb26", - "reference": "9e935a16187e14f39b0e79910dabd614972cdb26", + "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/a8b6643a19ba6c8125a473623e45fb8cbb0e4159", + "reference": "a8b6643a19ba6c8125a473623e45fb8cbb0e4159", "shasum": "" }, "require": { @@ -16016,7 +16409,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/version/issues", "security": "https://github.com/sebastianbergmann/version/security/policy", - "source": "https://github.com/sebastianbergmann/version/tree/6.0.1" + "source": "https://github.com/sebastianbergmann/version/tree/6.0.2" }, "funding": [ { @@ -16036,36 +16429,36 @@ "type": "tidelift" } ], - "time": "2026-10-04T05:50:08+00:00" + "time": "2026-11-09T06:30:55+00:00" }, { "name": "slevomat/coding-standard", - "version": "8.31.1", + "version": "8.31.3", "source": { "type": "git", "url": "https://github.com/slevomat/coding-standard.git", - "reference": "0a40807a48873948bfa7ffce2a4e69ba40cf5e76" + "reference": "b5c34b28811ee2ed323c52c7dabe2f2802dd2f8a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/slevomat/coding-standard/zipball/0a40807a48873948bfa7ffce2a4e69ba40cf5e76", - "reference": "0a40807a48873948bfa7ffce2a4e69ba40cf5e76", + "url": "https://api.github.com/repos/slevomat/coding-standard/zipball/b5c34b28811ee2ed323c52c7dabe2f2802dd2f8a", + "reference": "b5c34b28811ee2ed323c52c7dabe2f2802dd2f8a", "shasum": "" }, "require": { "dealerdirect/phpcodesniffer-composer-installer": "^0.7 || ^1.2.1", "php": "^7.4 || ^8.0", - "phpstan/phpdoc-parser": "^2.3.3", - "squizlabs/php_codesniffer": "^4.0.1" + "phpstan/phpdoc-parser": "^2.3.6", + "squizlabs/php_codesniffer": "^4.0.4" }, "require-dev": { "phing/phing": "3.0.1|3.1.2", "php-parallel-lint/php-parallel-lint": "1.4.0", - "phpstan/phpstan": "2.2.7", + "phpstan/phpstan": "2.3.2", "phpstan/phpstan-deprecation-rules": "2.0.5", - "phpstan/phpstan-phpunit": "2.0.18", - "phpstan/phpstan-strict-rules": "2.0.12", - "phpunit/phpunit": "9.6.34|10.5.63|11.4.4|11.5.56|12.5.33" + "phpstan/phpstan-phpunit": "2.1.1", + "phpstan/phpstan-strict-rules": "2.1.0", + "phpunit/phpunit": "9.6.38|10.5.66|11.4.4|11.5.57|12.5.40" }, "type": "phpcodesniffer-standard", "extra": { @@ -16089,7 +16482,7 @@ ], "support": { "issues": "https://github.com/slevomat/coding-standard/issues", - "source": "https://github.com/slevomat/coding-standard/tree/8.31.1" + "source": "https://github.com/slevomat/coding-standard/tree/8.31.3" }, "funding": [ { @@ -16101,7 +16494,7 @@ "type": "tidelift" } ], - "time": "2026-07-31T10:42:43+00:00" + "time": "2026-10-28T16:34:46+00:00" }, { "name": "spatie/backtrace", @@ -16243,16 +16636,16 @@ }, { "name": "spatie/flare-client-php", - "version": "1.11.1", + "version": "1.11.2", "source": { "type": "git", "url": "https://github.com/spatie/flare-client-php.git", - "reference": "53f41b08a27cc039e1a8ed2be9a202e924f31bad" + "reference": "181cab18224b7ed3ec66bccdf645c0e04a1aa3b1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/spatie/flare-client-php/zipball/53f41b08a27cc039e1a8ed2be9a202e924f31bad", - "reference": "53f41b08a27cc039e1a8ed2be9a202e924f31bad", + "url": "https://api.github.com/repos/spatie/flare-client-php/zipball/181cab18224b7ed3ec66bccdf645c0e04a1aa3b1", + "reference": "181cab18224b7ed3ec66bccdf645c0e04a1aa3b1", "shasum": "" }, "require": { @@ -16300,7 +16693,7 @@ ], "support": { "issues": "https://github.com/spatie/flare-client-php/issues", - "source": "https://github.com/spatie/flare-client-php/tree/1.11.1" + "source": "https://github.com/spatie/flare-client-php/tree/1.11.2" }, "funding": [ { @@ -16308,7 +16701,7 @@ "type": "github" } ], - "time": "2026-05-15T09:31:32+00:00" + "time": "2026-11-04T15:14:45+00:00" }, { "name": "spatie/ignition", @@ -16398,25 +16791,25 @@ }, { "name": "spatie/laravel-ignition", - "version": "2.12.0", + "version": "2.13.0", "source": { "type": "git", "url": "https://github.com/spatie/laravel-ignition.git", - "reference": "45b3b6e1e73fc161cba2149972698644b99594ee" + "reference": "0cf60c3e1a63e7fc5ea04d6fb0a162057724f041" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/spatie/laravel-ignition/zipball/45b3b6e1e73fc161cba2149972698644b99594ee", - "reference": "45b3b6e1e73fc161cba2149972698644b99594ee", + "url": "https://api.github.com/repos/spatie/laravel-ignition/zipball/0cf60c3e1a63e7fc5ea04d6fb0a162057724f041", + "reference": "0cf60c3e1a63e7fc5ea04d6fb0a162057724f041", "shasum": "" }, "require": { "ext-curl": "*", "ext-json": "*", "ext-mbstring": "*", - "illuminate/support": "^11.0|^12.0|^13.0", - "nesbot/carbon": "^2.72|^3.0", - "php": "^8.2", + "illuminate/support": "^13.0", + "nesbot/carbon": "^3.13.3", + "php": "^8.4", "spatie/ignition": "^1.16", "symfony/console": "^7.4|^8.0", "symfony/var-dumper": "^7.4|^8.0" @@ -16425,8 +16818,8 @@ "livewire/livewire": "^3.7.0|^4.0|dev-josh/v3-laravel-13-support", "mockery/mockery": "^1.6.12", "openai-php/client": "^0.10.3|^0.19", - "orchestra/testbench": "^v9.16.0|^10.6|^11.0", - "pestphp/pest": "^3.7|^4.0", + "orchestra/testbench": "^11.0", + "pestphp/pest": "^5.3.5", "phpstan/extension-installer": "^1.4.3", "phpstan/phpstan-deprecation-rules": "^2.0.3", "phpstan/phpstan-phpunit": "^2.0.8", @@ -16486,7 +16879,7 @@ "type": "github" } ], - "time": "2026-03-17T12:20:04+00:00" + "time": "2026-11-06T15:11:05+00:00" }, { "name": "squizlabs/php_codesniffer", @@ -16795,16 +17188,16 @@ }, { "name": "tomasvotruba/type-coverage", - "version": "2.5.0", + "version": "2.5.1", "source": { "type": "git", "url": "https://github.com/TomasVotruba/type-coverage.git", - "reference": "afcfc6f890cb680d10974cbdff210892210c822a" + "reference": "2d8e722c1776a17f506f6a66cd325e50fbaa12ee" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/TomasVotruba/type-coverage/zipball/afcfc6f890cb680d10974cbdff210892210c822a", - "reference": "afcfc6f890cb680d10974cbdff210892210c822a", + "url": "https://api.github.com/repos/TomasVotruba/type-coverage/zipball/2d8e722c1776a17f506f6a66cd325e50fbaa12ee", + "reference": "2d8e722c1776a17f506f6a66cd325e50fbaa12ee", "shasum": "" }, "require": { @@ -16819,10 +17212,10 @@ "rector/jack": "^1.1", "rector/rector": "^2.5", "shipmonk/composer-dependency-analyser": "^1.8", + "shipmonk/dead-code-detector": "^1.4", "symfony/dom-crawler": "^8.1", "symfony/form": "^8.1", "symplify/easy-coding-standard": "^13.2", - "tomasvotruba/unused-public": "^2.2", "tracy/tracy": "^2.12" }, "type": "phpstan-extension", @@ -16850,7 +17243,7 @@ ], "support": { "issues": "https://github.com/TomasVotruba/type-coverage/issues", - "source": "https://github.com/TomasVotruba/type-coverage/tree/2.5.0" + "source": "https://github.com/TomasVotruba/type-coverage/tree/2.5.1" }, "funding": [ { @@ -16862,7 +17255,7 @@ "type": "github" } ], - "time": "2026-10-05T20:07:08+00:00" + "time": "2026-10-09T19:09:05+00:00" } ], "aliases": [], From f7a20c9d5d3c10c672f59c4f73f693218ac2d922 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Thu, 12 Nov 2026 15:09:26 +0100 Subject: [PATCH 007/183] style(queue): apply consistent formatting and add strict types Improves code readability and enforces strict typing in queue configuration. --- config/queue.php | 72 +++++++++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 35 deletions(-) diff --git a/config/queue.php b/config/queue.php index 771a3362..840b2874 100644 --- a/config/queue.php +++ b/config/queue.php @@ -1,5 +1,7 @@ env('QUEUE_CONNECTION', 'database'), @@ -27,7 +29,7 @@ return [ | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", | "deferred", "failover", "null" | - */ + */ 'connections' => [ @@ -36,47 +38,47 @@ return [ ], 'database' => [ - 'driver' => 'database', - 'connection' => env('DB_QUEUE_CONNECTION'), - 'table' => env('DB_QUEUE_TABLE', 'jobs'), - 'queue' => env('DB_QUEUE', 'default'), - 'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90), + 'driver' => 'database', + 'connection' => env('DB_QUEUE_CONNECTION'), + 'table' => env('DB_QUEUE_TABLE', 'jobs'), + 'queue' => env('DB_QUEUE', 'default'), + 'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90), 'after_commit' => false, ], 'beanstalkd' => [ - 'driver' => 'beanstalkd', - 'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'), - 'queue' => env('BEANSTALKD_QUEUE', 'default'), - 'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90), - 'block_for' => 0, + 'driver' => 'beanstalkd', + 'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'), + 'queue' => env('BEANSTALKD_QUEUE', 'default'), + 'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90), + 'block_for' => 0, 'after_commit' => false, ], 'sqs' => [ - 'driver' => 'sqs', - 'key' => env('AWS_ACCESS_KEY_ID'), - 'secret' => env('AWS_SECRET_ACCESS_KEY'), - 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), - 'queue' => env('SQS_QUEUE', 'default'), - 'suffix' => env('SQS_SUFFIX'), - 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'driver' => 'sqs', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), + 'queue' => env('SQS_QUEUE', 'default'), + 'suffix' => env('SQS_SUFFIX'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), 'after_commit' => false, - 'overflow' => [ - 'enabled' => env('SQS_OVERFLOW_ENABLED', false), - 'store' => env('SQS_OVERFLOW_STORE'), - 'always' => false, + 'overflow' => [ + 'enabled' => env('SQS_OVERFLOW_ENABLED', false), + 'store' => env('SQS_OVERFLOW_STORE'), + 'always' => false, 'delete_after_processing' => true, - 'flush_on_clear' => env('SQS_OVERFLOW_FLUSH_ON_CLEAR', false), + 'flush_on_clear' => env('SQS_OVERFLOW_FLUSH_ON_CLEAR', false), ], ], 'redis' => [ - 'driver' => 'redis', - 'connection' => env('REDIS_QUEUE_CONNECTION', 'default'), - 'queue' => env('REDIS_QUEUE', 'default'), - 'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90), - 'block_for' => null, + 'driver' => 'redis', + 'connection' => env('REDIS_QUEUE_CONNECTION', 'default'), + 'queue' => env('REDIS_QUEUE', 'default'), + 'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90), + 'block_for' => null, 'after_commit' => false, ], @@ -85,7 +87,7 @@ return [ ], 'failover' => [ - 'driver' => 'failover', + 'driver' => 'failover', 'connections' => [ 'database', 'deferred', @@ -103,11 +105,11 @@ return [ | batching information. These options can be updated to any database | connection and table which has been defined by your application. | - */ + */ 'batching' => [ 'database' => env('DB_CONNECTION', 'sqlite'), - 'table' => 'job_batches', + 'table' => 'job_batches', ], /* @@ -121,12 +123,12 @@ return [ | | Supported drivers: "database-uuids", "dynamodb", "file", "null" | - */ + */ 'failed' => [ - 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), + 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), 'database' => env('DB_CONNECTION', 'sqlite'), - 'table' => 'failed_jobs', + 'table' => 'failed_jobs', ], ]; From 4a9af4a90acc50de5a06ad4c76a2bf7e0b3957cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Sat, 14 Nov 2026 16:05:43 +0100 Subject: [PATCH 008/183] refactor(database): squash migrations into mysql-schema.sql and harden Setting singleton --- app/Models/Setting.php | 18 +- .../2014_10_12_000000_create_users_table.php | 41 - ...12_100000_create_password_resets_table.php | 35 - ...12_23_120000_create_shoppingcart_table.php | 37 - ..._08_19_000000_create_failed_jobs_table.php | 38 - .../2020_11_04_132346_create_contents.php | 35 - .../2020_11_04_132538_create_settings.php | 35 - .../2020_11_04_133603_create_faqs.php | 35 - .../2020_11_05_084122_create_ranges.php | 38 - .../2020_11_05_084142_create_products.php | 45 -- .../2020_11_05_105239_create_old_slugs.php | 36 - .../2020_11_09_113830_create_stats.php | 37 - ...2020_11_09_125215_create_orders_status.php | 33 - .../2020_11_09_125304_create_orders.php | 38 - ...20_11_09_161858_create_orders_products.php | 34 - ...21_02_04_175136_create_customers_table.php | 42 -- ...4_180000_constrain_orders_to_customers.php | 35 - ...21_03_16_111337_add_fields_to_products.php | 49 -- ...2021_03_16_135155_create_food_products.php | 111 --- ..._03_16_140753_create_products_products.php | 37 - ...21_03_17_093244_add_fields_to_contents.php | 38 - ..._03_27_163403_create_order_lines_table.php | 49 -- ...21_03_29_114933_create_timeslots_table.php | 36 - ..._06_153634_create_discount_types_table.php | 33 - ...1_04_06_154003_create_promotions_table.php | 37 - ..._100613_create_product_promotion_table.php | 36 - ...21_04_07_153852_create_tax_rates_table.php | 34 - ...07_154718_add_fields_to_products_table.php | 35 - .../2021_04_09_081311_create_tags_table.php | 35 - ..._04_09_081345_create_product_tag_table.php | 35 - ..._04_13_142701_remove_deprecated_tables.php | 30 - ...2021_04_14_115938_create_sliders_table.php | 37 - .../2021_04_14_115954_create_slides_table.php | 46 -- ...tend_champ_description_in_ranges_table.php | 33 - ...ange_optional_fields_in_products_table.php | 34 - ..._154225_create_timeslot_settings_table.php | 43 -- .../2021_04_21_092030_create_jobs_table.php | 38 - ...21_04_21_101455_create_xml_incos_table.php | 53 -- ...54354_create_collecte_exceptions_table.php | 35 - ...021_04_21_165607_create_magasins_table.php | 43 -- ..._child_of_magasins_time_settings_table.php | 56 -- ..._112008_add_magasin_to_timeslots_table.php | 39 - ..._unique_no_art_inf_food_products_table.php | 33 - ...2021_05_03_173156_alter_products_table.php | 36 - ...5_06_121330_create_tool_products_table.php | 39 - ...6_121546_create_anifood_products_table.php | 39 - ...6_121656_create_garment_products_table.php | 39 - ...803_add_management_flags_to_tags_table.php | 44 -- ...9_add_fields_to_anifood_products_table.php | 36 - ...1_add_fields_to_garment_products_table.php | 38 - ..._add_orderable_dates_to_products_table.php | 36 - ...021_07_20_141844_create_salaries_table.php | 41 - ..._order_export_fields_to_products_table.php | 40 - ...612_add_code_societe_to_salaries_table.php | 36 - ...8_144311_alter_price_to_products_table.php | 36 - ...3_12_115802_add_nom_to_xml_incos_table.php | 34 - ...14_143040_remove_crm_id_from_customers.php | 35 - ...022_09_12_160131_add_brand_to_products.php | 34 - ...22_09_14_090354_add_fields_to_salaries.php | 45 -- ..._09_20_171712_link_magasin_to_salaries.php | 36 - ..._add_variable_weight_to_products_table.php | 34 - ..._111255_alter_ranges_description_table.php | 34 - ..._30_110313_alter_product_serving_table.php | 34 - ...07_04_151150_alter_code_salaries_table.php | 36 - ...4_151446_format_day_in_timeslots_table.php | 58 -- ..._07_26_091913_add_order_products_table.php | 41 - ...3_07_27_145254_alter_birth_users_table.php | 34 - ...23_07_27_150324_alter_role_users_table.php | 35 - ...7_27_153349_alter_clean_salaries_table.php | 49 -- ...10_112337_add_type_to_exceptions_table.php | 46 -- ...19_add_connected_field_in_slides_table.php | 31 - ...2026_02_25_102520_reorder_all_products.php | 31 - ...display_old_value_for_promotions_table.php | 34 - ...2026_04_09_111244_delete_promotion_tag.php | 38 - ...7_152343_add_unique_to_password_resets.php | 30 - ...ord_resets_to_customer_password_resets.php | 30 - ...emove_id_from_customer_password_resets.php | 30 - .../2026_05_06_164734_fix_slides_table.php | 34 - ...2026_05_07_090552_delete_sliders_table.php | 30 - ...6_05_07_104436_migrate_slides_pictures.php | 59 -- ...115830_add_image_attributes_on_sliders.php | 32 - ...2026_05_07_123948_add_status_to_slides.php | 30 - ...2026_05_12_162815_update_order_on_tags.php | 30 - ..._12_172419_drop_anifoods_product_table.php | 25 - ...2026_05_12_172830_rename_food_products.php | 25 - ...026_05_12_174606_drop_garment_products.php | 25 - .../2026_05_12_174709_drop_tool_products.php | 25 - ...2_175637_drop_product_type_on_products.php | 28 - ...165615_resole_salarie_shop_dynamically.php | 131 ---- .../2026_05_15_085114_rename_tables.php | 71 -- ..._05_15_094440_drop_discount_type_table.php | 30 - ...6_05_15_095409_drop_ordre_status_table.php | 30 - .../2026_05_15_095736_drop_order_products.php | 30 - .../2026_05_15_100312_drop_tax_rates.php | 30 - .../2026_05_15_102945_drop_settings.php | 25 - ...dd_unique_to_matricule_employees_table.php | 47 -- .../2026_05_15_130940_add_unique_to_pages.php | 31 - ...131427_remove_heading_from_pages_table.php | 29 - .../2026_05_15_133554_rename_promotions.php | 34 - ...6_05_15_165156_add_order_to_faqs_table.php | 43 -- ...5_172544_add_seo_fields_on_pages_table.php | 68 -- ..._migrate_old_slugs_to_redirect_package.php | 67 -- ...6_05_18_125014_migrate_ranges_pictures.php | 59 -- .../2026_05_18_142859_add_order_to_ranges.php | 43 -- ...2042_add_picture_title_to_ranges_table.php | 45 -- ...43_add_picture_title_to_products_table.php | 53 -- ..._change_some_columns_on_products_table.php | 32 - .../2026_05_19_101521_change_order_status.php | 26 - ...05_19_101521_migrate_products_pictures.php | 84 --- ...hange_some_columns_2_on_products_table.php | 34 - ...dd_sort_order_to_product_product_table.php | 30 - ...3658_remove_margin_from_products_table.php | 30 - ...nge_product_inco_relation_with_product.php | 42 -- ..._21_103837_change_product_order_column.php | 35 - ...6_05_21_120644_remove_home_statis_page.php | 25 - ...5_21_122658_rename_offers_to_discounts.php | 38 - ...6_05_21_131414_rename_offers_discounts.php | 25 - ...roduct_discount_relation_to_belongs_to.php | 40 - .../2026_05_21_163851_simplify_shops_map.php | 30 - ...05_22_101939_remove_time_slot_settings.php | 25 - ...2026_05_22_102624_remove_timeslot_time.php | 28 - ..._rename_shop_column_on_timeslots_table.php | 30 - ...4824_rename_time_slot_exceptions_table.php | 25 - ...05_22_124529_refactor_pickup_exception.php | 137 ---- ...uto_updated_on_pickup_exceptions_table.php | 36 - ...nts_day_to_shop_pickup_exception_table.php | 32 - ..._05_26_154849_convert_all_dates_to_utc.php | 119 --- ...2026_05_28_095941_remove_order_comment.php | 30 - .../2026_05_28_101213_consolidate_order.php | 58 -- ...8_101213_convert_discount_value_as_int.php | 35 - ...5_28_101213_convert_order_total_as_int.php | 36 - ...8_101213_convert_product_prices_as_int.php | 29 - ...01213_rename_columns_on_discount_table.php | 29 - ...6_05_28_102411_consolidate_order_lines.php | 163 ---- ...2026_06_01_130113_update_sliders_links.php | 36 - .../2026_06_01_150709_update_page_title.php | 27 - ...dd_short_description_to_products_table.php | 58 -- ...hange_columns_to_int_on_products_table.php | 32 - ...082126_strip_product_short_description.php | 30 - ..._112425_add_delivery_address_to_orders.php | 73 -- ...6_06_181952_migrate_products_to_uuidv7.php | 190 ----- ..._06_06_181953_migrate_orders_to_uuidv7.php | 119 --- ..._07_072414_migrate_customers_to_uuidv7.php | 130 ---- ...027_drop_date_column_from_orders_table.php | 30 - ...7_175730_add_reference_to_orders_table.php | 46 -- ...7_180625_simplify_timeslot_into_orders.php | 39 - ...5_update_shop_employee_exception_table.php | 46 -- ...atricule_virtual_index_to_orders_table.php | 30 - ...ll_unit_not_nullable_on_products_table.php | 32 - ..._orders_and_make_employee_non_nullable.php | 56 -- ...9_add_last_login_at_to_customers_table.php | 30 - ..._06_11_160000_migrate_weights_to_grams.php | 80 -- ...able_to_boolean_in_order_lines_product.php | 41 - ...iscounted_price_in_order_lines_product.php | 48 -- ..._shops_and_pickup_exceptions_to_uuidv7.php | 183 ----- ...0_01_123336_add_last_sync_to_employees.php | 30 - ...10_01_150950_fix_employee_service_code.php | 38 - ...026_10_01_163000_create_settings_table.php | 38 - ...02_130500_fix_ambiguous_employee_codes.php | 41 - ...0_02_143800_fix_orders_employee_column.php | 68 -- ...2026_10_02_222500_drop_xml_incos_table.php | 25 - ...0_07_100650_recalculate_products_order.php | 41 - ...000_fix_inco_id_in_order_lines_product.php | 57 -- database/schema/mysql-schema.sql | 703 ++++++++++++++++++ 164 files changed, 715 insertions(+), 7140 deletions(-) delete mode 100644 database/migrations/2014_10_12_000000_create_users_table.php delete mode 100644 database/migrations/2014_10_12_100000_create_password_resets_table.php delete mode 100644 database/migrations/2018_12_23_120000_create_shoppingcart_table.php delete mode 100644 database/migrations/2019_08_19_000000_create_failed_jobs_table.php delete mode 100644 database/migrations/2020_11_04_132346_create_contents.php delete mode 100644 database/migrations/2020_11_04_132538_create_settings.php delete mode 100644 database/migrations/2020_11_04_133603_create_faqs.php delete mode 100644 database/migrations/2020_11_05_084122_create_ranges.php delete mode 100644 database/migrations/2020_11_05_084142_create_products.php delete mode 100644 database/migrations/2020_11_05_105239_create_old_slugs.php delete mode 100644 database/migrations/2020_11_09_113830_create_stats.php delete mode 100644 database/migrations/2020_11_09_125215_create_orders_status.php delete mode 100644 database/migrations/2020_11_09_125304_create_orders.php delete mode 100644 database/migrations/2020_11_09_161858_create_orders_products.php delete mode 100644 database/migrations/2021_02_04_175136_create_customers_table.php delete mode 100644 database/migrations/2021_02_04_180000_constrain_orders_to_customers.php delete mode 100644 database/migrations/2021_03_16_111337_add_fields_to_products.php delete mode 100644 database/migrations/2021_03_16_135155_create_food_products.php delete mode 100644 database/migrations/2021_03_16_140753_create_products_products.php delete mode 100644 database/migrations/2021_03_17_093244_add_fields_to_contents.php delete mode 100644 database/migrations/2021_03_27_163403_create_order_lines_table.php delete mode 100644 database/migrations/2021_03_29_114933_create_timeslots_table.php delete mode 100644 database/migrations/2021_04_06_153634_create_discount_types_table.php delete mode 100644 database/migrations/2021_04_06_154003_create_promotions_table.php delete mode 100644 database/migrations/2021_04_07_100613_create_product_promotion_table.php delete mode 100644 database/migrations/2021_04_07_153852_create_tax_rates_table.php delete mode 100644 database/migrations/2021_04_07_154718_add_fields_to_products_table.php delete mode 100644 database/migrations/2021_04_09_081311_create_tags_table.php delete mode 100644 database/migrations/2021_04_09_081345_create_product_tag_table.php delete mode 100644 database/migrations/2021_04_13_142701_remove_deprecated_tables.php delete mode 100644 database/migrations/2021_04_14_115938_create_sliders_table.php delete mode 100644 database/migrations/2021_04_14_115954_create_slides_table.php delete mode 100644 database/migrations/2021_04_19_145945_extend_champ_description_in_ranges_table.php delete mode 100644 database/migrations/2021_04_19_155920_change_optional_fields_in_products_table.php delete mode 100644 database/migrations/2021_04_20_154225_create_timeslot_settings_table.php delete mode 100644 database/migrations/2021_04_21_092030_create_jobs_table.php delete mode 100644 database/migrations/2021_04_21_101455_create_xml_incos_table.php delete mode 100644 database/migrations/2021_04_21_154354_create_collecte_exceptions_table.php delete mode 100644 database/migrations/2021_04_21_165607_create_magasins_table.php delete mode 100644 database/migrations/2021_04_22_153147_make_child_of_magasins_time_settings_table.php delete mode 100644 database/migrations/2021_04_23_112008_add_magasin_to_timeslots_table.php delete mode 100644 database/migrations/2021_04_26_161004_make_unique_no_art_inf_food_products_table.php delete mode 100644 database/migrations/2021_05_03_173156_alter_products_table.php delete mode 100644 database/migrations/2021_05_06_121330_create_tool_products_table.php delete mode 100644 database/migrations/2021_05_06_121546_create_anifood_products_table.php delete mode 100644 database/migrations/2021_05_06_121656_create_garment_products_table.php delete mode 100644 database/migrations/2021_05_07_091803_add_management_flags_to_tags_table.php delete mode 100644 database/migrations/2021_05_25_100049_add_fields_to_anifood_products_table.php delete mode 100644 database/migrations/2021_05_25_101151_add_fields_to_garment_products_table.php delete mode 100644 database/migrations/2021_06_07_124924_add_orderable_dates_to_products_table.php delete mode 100644 database/migrations/2021_07_20_141844_create_salaries_table.php delete mode 100644 database/migrations/2021_07_27_103748_add_required_for_order_export_fields_to_products_table.php delete mode 100644 database/migrations/2021_09_24_091612_add_code_societe_to_salaries_table.php delete mode 100644 database/migrations/2021_11_18_144311_alter_price_to_products_table.php delete mode 100644 database/migrations/2022_03_12_115802_add_nom_to_xml_incos_table.php delete mode 100644 database/migrations/2022_04_14_143040_remove_crm_id_from_customers.php delete mode 100644 database/migrations/2022_09_12_160131_add_brand_to_products.php delete mode 100644 database/migrations/2022_09_14_090354_add_fields_to_salaries.php delete mode 100644 database/migrations/2022_09_20_171712_link_magasin_to_salaries.php delete mode 100644 database/migrations/2022_10_11_163252_add_variable_weight_to_products_table.php delete mode 100644 database/migrations/2022_10_20_111255_alter_ranges_description_table.php delete mode 100644 database/migrations/2023_03_30_110313_alter_product_serving_table.php delete mode 100644 database/migrations/2023_07_04_151150_alter_code_salaries_table.php delete mode 100644 database/migrations/2023_07_04_151446_format_day_in_timeslots_table.php delete mode 100644 database/migrations/2023_07_26_091913_add_order_products_table.php delete mode 100644 database/migrations/2023_07_27_145254_alter_birth_users_table.php delete mode 100644 database/migrations/2023_07_27_150324_alter_role_users_table.php delete mode 100644 database/migrations/2023_07_27_153349_alter_clean_salaries_table.php delete mode 100644 database/migrations/2025_02_10_112337_add_type_to_exceptions_table.php delete mode 100644 database/migrations/2026_02_04_102119_add_connected_field_in_slides_table.php delete mode 100644 database/migrations/2026_02_25_102520_reorder_all_products.php delete mode 100644 database/migrations/2026_02_25_111055_add_boolean_display_old_value_for_promotions_table.php delete mode 100644 database/migrations/2026_04_09_111244_delete_promotion_tag.php delete mode 100644 database/migrations/2026_04_27_152343_add_unique_to_password_resets.php delete mode 100644 database/migrations/2026_04_29_110121_rename_table_password_resets_to_customer_password_resets.php delete mode 100644 database/migrations/2026_04_29_120913_remove_id_from_customer_password_resets.php delete mode 100644 database/migrations/2026_05_06_164734_fix_slides_table.php delete mode 100644 database/migrations/2026_05_07_090552_delete_sliders_table.php delete mode 100644 database/migrations/2026_05_07_104436_migrate_slides_pictures.php delete mode 100644 database/migrations/2026_05_07_115830_add_image_attributes_on_sliders.php delete mode 100644 database/migrations/2026_05_07_123948_add_status_to_slides.php delete mode 100644 database/migrations/2026_05_12_162815_update_order_on_tags.php delete mode 100644 database/migrations/2026_05_12_172419_drop_anifoods_product_table.php delete mode 100644 database/migrations/2026_05_12_172830_rename_food_products.php delete mode 100644 database/migrations/2026_05_12_174606_drop_garment_products.php delete mode 100644 database/migrations/2026_05_12_174709_drop_tool_products.php delete mode 100644 database/migrations/2026_05_12_175637_drop_product_type_on_products.php delete mode 100644 database/migrations/2026_05_13_165615_resole_salarie_shop_dynamically.php delete mode 100644 database/migrations/2026_05_15_085114_rename_tables.php delete mode 100644 database/migrations/2026_05_15_094440_drop_discount_type_table.php delete mode 100644 database/migrations/2026_05_15_095409_drop_ordre_status_table.php delete mode 100644 database/migrations/2026_05_15_095736_drop_order_products.php delete mode 100644 database/migrations/2026_05_15_100312_drop_tax_rates.php delete mode 100644 database/migrations/2026_05_15_102945_drop_settings.php delete mode 100644 database/migrations/2026_05_15_110705_add_unique_to_matricule_employees_table.php delete mode 100644 database/migrations/2026_05_15_130940_add_unique_to_pages.php delete mode 100644 database/migrations/2026_05_15_131427_remove_heading_from_pages_table.php delete mode 100644 database/migrations/2026_05_15_133554_rename_promotions.php delete mode 100644 database/migrations/2026_05_15_165156_add_order_to_faqs_table.php delete mode 100644 database/migrations/2026_05_15_172544_add_seo_fields_on_pages_table.php delete mode 100644 database/migrations/2026_05_18_113005_migrate_old_slugs_to_redirect_package.php delete mode 100644 database/migrations/2026_05_18_125014_migrate_ranges_pictures.php delete mode 100644 database/migrations/2026_05_18_142859_add_order_to_ranges.php delete mode 100644 database/migrations/2026_05_18_152042_add_picture_title_to_ranges_table.php delete mode 100644 database/migrations/2026_05_18_152043_add_picture_title_to_products_table.php delete mode 100644 database/migrations/2026_05_19_094421_change_some_columns_on_products_table.php delete mode 100644 database/migrations/2026_05_19_101521_change_order_status.php delete mode 100644 database/migrations/2026_05_19_101521_migrate_products_pictures.php delete mode 100644 database/migrations/2026_05_19_101522_change_some_columns_2_on_products_table.php delete mode 100644 database/migrations/2026_05_20_113304_add_sort_order_to_product_product_table.php delete mode 100644 database/migrations/2026_05_20_123658_remove_margin_from_products_table.php delete mode 100644 database/migrations/2026_05_20_160028_change_product_inco_relation_with_product.php delete mode 100644 database/migrations/2026_05_21_103837_change_product_order_column.php delete mode 100644 database/migrations/2026_05_21_120644_remove_home_statis_page.php delete mode 100644 database/migrations/2026_05_21_122658_rename_offers_to_discounts.php delete mode 100644 database/migrations/2026_05_21_131414_rename_offers_discounts.php delete mode 100644 database/migrations/2026_05_21_142044_change_product_discount_relation_to_belongs_to.php delete mode 100644 database/migrations/2026_05_21_163851_simplify_shops_map.php delete mode 100644 database/migrations/2026_05_22_101939_remove_time_slot_settings.php delete mode 100644 database/migrations/2026_05_22_102624_remove_timeslot_time.php delete mode 100644 database/migrations/2026_05_22_102934_rename_shop_column_on_timeslots_table.php delete mode 100644 database/migrations/2026_05_22_104824_rename_time_slot_exceptions_table.php delete mode 100644 database/migrations/2026_05_22_124529_refactor_pickup_exception.php delete mode 100644 database/migrations/2026_05_26_095455_add_auto_updated_on_pickup_exceptions_table.php delete mode 100644 database/migrations/2026_05_26_143214_add_replacements_day_to_shop_pickup_exception_table.php delete mode 100644 database/migrations/2026_05_26_154849_convert_all_dates_to_utc.php delete mode 100644 database/migrations/2026_05_28_095941_remove_order_comment.php delete mode 100644 database/migrations/2026_05_28_101213_consolidate_order.php delete mode 100644 database/migrations/2026_05_28_101213_convert_discount_value_as_int.php delete mode 100644 database/migrations/2026_05_28_101213_convert_order_total_as_int.php delete mode 100644 database/migrations/2026_05_28_101213_convert_product_prices_as_int.php delete mode 100644 database/migrations/2026_05_28_101213_rename_columns_on_discount_table.php delete mode 100644 database/migrations/2026_05_28_102411_consolidate_order_lines.php delete mode 100644 database/migrations/2026_06_01_130113_update_sliders_links.php delete mode 100644 database/migrations/2026_06_01_150709_update_page_title.php delete mode 100644 database/migrations/2026_06_03_143713_add_short_description_to_products_table.php delete mode 100644 database/migrations/2026_06_04_154533_change_columns_to_int_on_products_table.php delete mode 100644 database/migrations/2026_06_05_082126_strip_product_short_description.php delete mode 100644 database/migrations/2026_06_05_112425_add_delivery_address_to_orders.php delete mode 100644 database/migrations/2026_06_06_181952_migrate_products_to_uuidv7.php delete mode 100644 database/migrations/2026_06_06_181953_migrate_orders_to_uuidv7.php delete mode 100644 database/migrations/2026_06_07_072414_migrate_customers_to_uuidv7.php delete mode 100644 database/migrations/2026_06_07_172027_drop_date_column_from_orders_table.php delete mode 100644 database/migrations/2026_06_07_175730_add_reference_to_orders_table.php delete mode 100644 database/migrations/2026_06_07_180625_simplify_timeslot_into_orders.php delete mode 100644 database/migrations/2026_06_07_193825_update_shop_employee_exception_table.php delete mode 100644 database/migrations/2026_06_08_164207_add_employee_matricule_virtual_index_to_orders_table.php delete mode 100644 database/migrations/2026_06_10_221046_make_invoicing_and_sell_unit_not_nullable_on_products_table.php delete mode 100644 database/migrations/2026_06_11_091414_move_invalid_orders_and_make_employee_non_nullable.php delete mode 100644 database/migrations/2026_06_11_104029_add_last_login_at_to_customers_table.php delete mode 100644 database/migrations/2026_06_11_160000_migrate_weights_to_grams.php delete mode 100644 database/migrations/2026_06_12_120149_convert_weight_variable_to_boolean_in_order_lines_product.php delete mode 100644 database/migrations/2026_06_12_122322_populate_null_discounted_price_in_order_lines_product.php delete mode 100644 database/migrations/2026_06_13_151618_migrate_shops_and_pickup_exceptions_to_uuidv7.php delete mode 100644 database/migrations/2026_10_01_123336_add_last_sync_to_employees.php delete mode 100644 database/migrations/2026_10_01_150950_fix_employee_service_code.php delete mode 100644 database/migrations/2026_10_01_163000_create_settings_table.php delete mode 100644 database/migrations/2026_10_02_130500_fix_ambiguous_employee_codes.php delete mode 100644 database/migrations/2026_10_02_143800_fix_orders_employee_column.php delete mode 100644 database/migrations/2026_10_02_222500_drop_xml_incos_table.php delete mode 100644 database/migrations/2026_10_07_100650_recalculate_products_order.php delete mode 100644 database/migrations/2026_11_02_111000_fix_inco_id_in_order_lines_product.php create mode 100644 database/schema/mysql-schema.sql diff --git a/app/Models/Setting.php b/app/Models/Setting.php index 38a37906..031940b7 100644 --- a/app/Models/Setting.php +++ b/app/Models/Setting.php @@ -36,11 +36,17 @@ class Setting extends Model public static function getSingleton(): self { - return self::query()->firstOrCreate( - ['id' => self::SINGLETON_ID], - [ - 'employee_sites' => [], - ] - ); + $setting = self::query()->find(self::SINGLETON_ID); + + if ($setting !== null) { + return $setting; + } + + $setting = new self(); + $setting->id = self::SINGLETON_ID; + $setting->employee_sites = []; + $setting->save(); + + return $setting; } } diff --git a/database/migrations/2014_10_12_000000_create_users_table.php b/database/migrations/2014_10_12_000000_create_users_table.php deleted file mode 100644 index 5ae30430..00000000 --- a/database/migrations/2014_10_12_000000_create_users_table.php +++ /dev/null @@ -1,41 +0,0 @@ -id(); - $table->string('firstname'); - $table->string('lastname'); - $table->date('date_of_birth'); - $table->string('email')->unique(); - $table->timestamp('email_verified_at')->nullable(); - $table->string('password'); - $table->integer('role'); - $table->rememberToken(); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('users'); - } -} diff --git a/database/migrations/2014_10_12_100000_create_password_resets_table.php b/database/migrations/2014_10_12_100000_create_password_resets_table.php deleted file mode 100644 index efa36a8a..00000000 --- a/database/migrations/2014_10_12_100000_create_password_resets_table.php +++ /dev/null @@ -1,35 +0,0 @@ -id(); - $table->string('email')->index(); - $table->string('token'); - $table->timestamp('created_at')->nullable(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('password_resets'); - } -} diff --git a/database/migrations/2018_12_23_120000_create_shoppingcart_table.php b/database/migrations/2018_12_23_120000_create_shoppingcart_table.php deleted file mode 100644 index b3db1b63..00000000 --- a/database/migrations/2018_12_23_120000_create_shoppingcart_table.php +++ /dev/null @@ -1,37 +0,0 @@ -string('identifier'); - $table->string('instance'); - $table->longText('content'); - $table->nullableTimestamps(); - - $table->primary(['identifier', 'instance']); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::drop('shoppingcart'); - } -} diff --git a/database/migrations/2019_08_19_000000_create_failed_jobs_table.php b/database/migrations/2019_08_19_000000_create_failed_jobs_table.php deleted file mode 100644 index cb397212..00000000 --- a/database/migrations/2019_08_19_000000_create_failed_jobs_table.php +++ /dev/null @@ -1,38 +0,0 @@ -id(); - $table->string('uuid')->unique(); - $table->text('connection'); - $table->text('queue'); - $table->longText('payload'); - $table->longText('exception'); - $table->timestamp('failed_at')->useCurrent(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('failed_jobs'); - } -} diff --git a/database/migrations/2020_11_04_132346_create_contents.php b/database/migrations/2020_11_04_132346_create_contents.php deleted file mode 100644 index 8d6a90a7..00000000 --- a/database/migrations/2020_11_04_132346_create_contents.php +++ /dev/null @@ -1,35 +0,0 @@ -id(); - $table->string('key'); - $table->text('value'); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('content'); - } -} diff --git a/database/migrations/2020_11_04_132538_create_settings.php b/database/migrations/2020_11_04_132538_create_settings.php deleted file mode 100644 index 90826dc1..00000000 --- a/database/migrations/2020_11_04_132538_create_settings.php +++ /dev/null @@ -1,35 +0,0 @@ -id(); - $table->string('key'); - $table->string('value'); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('settings'); - } -} diff --git a/database/migrations/2020_11_04_133603_create_faqs.php b/database/migrations/2020_11_04_133603_create_faqs.php deleted file mode 100644 index b9bc172c..00000000 --- a/database/migrations/2020_11_04_133603_create_faqs.php +++ /dev/null @@ -1,35 +0,0 @@ -id(); - $table->string('question'); - $table->text('answer'); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('faqs'); - } -} diff --git a/database/migrations/2020_11_05_084122_create_ranges.php b/database/migrations/2020_11_05_084122_create_ranges.php deleted file mode 100644 index 7010232d..00000000 --- a/database/migrations/2020_11_05_084122_create_ranges.php +++ /dev/null @@ -1,38 +0,0 @@ -id(); - $table->string('name'); - $table->string('slug'); - $table->string('description'); - $table->string('picture')->nullable(); - $table->boolean('status')->default(0); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('ranges'); - } -} diff --git a/database/migrations/2020_11_05_084142_create_products.php b/database/migrations/2020_11_05_084142_create_products.php deleted file mode 100644 index 64e2a377..00000000 --- a/database/migrations/2020_11_05_084142_create_products.php +++ /dev/null @@ -1,45 +0,0 @@ -id(); - $table->string('name'); - $table->text('description'); - $table->string('picture')->nullable(); - $table->float('price'); - $table->float('price_buy')->nullable(); - $table->unsignedBigInteger('stock'); - $table->string('reference'); - $table->string('slug'); - $table->boolean('status'); - $table->foreignId('range_id')->constrained('ranges'); - $table->float('margin')->default(0); - $table->timestamps(); - $table->softDeletes(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('products'); - } -} diff --git a/database/migrations/2020_11_05_105239_create_old_slugs.php b/database/migrations/2020_11_05_105239_create_old_slugs.php deleted file mode 100644 index b3942997..00000000 --- a/database/migrations/2020_11_05_105239_create_old_slugs.php +++ /dev/null @@ -1,36 +0,0 @@ -id(); - $table->foreignId('product_id')->nullable()->constrained('products'); - $table->foreignId('range_id')->nullable()->constrained('ranges'); - $table->string('slug'); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('old_slug'); - } -} diff --git a/database/migrations/2020_11_09_113830_create_stats.php b/database/migrations/2020_11_09_113830_create_stats.php deleted file mode 100644 index 6e528d07..00000000 --- a/database/migrations/2020_11_09_113830_create_stats.php +++ /dev/null @@ -1,37 +0,0 @@ -id(); - $table->foreignId('product_id')->constrained('products'); - $table->date('date'); - $table->float('margin')->default(0); - $table->unsignedBigInteger('nb_sale')->default(0); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('stats'); - } -} diff --git a/database/migrations/2020_11_09_125215_create_orders_status.php b/database/migrations/2020_11_09_125215_create_orders_status.php deleted file mode 100644 index fda182ec..00000000 --- a/database/migrations/2020_11_09_125215_create_orders_status.php +++ /dev/null @@ -1,33 +0,0 @@ -id(); - $table->string('label'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('orders_status'); - } -} diff --git a/database/migrations/2020_11_09_125304_create_orders.php b/database/migrations/2020_11_09_125304_create_orders.php deleted file mode 100644 index 419f02c7..00000000 --- a/database/migrations/2020_11_09_125304_create_orders.php +++ /dev/null @@ -1,38 +0,0 @@ -id(); - $table->string('reference')->unique(); - $table->date('date'); - $table->string('commentaire')->nullable(); - $table->float('total'); - $table->foreignId('status_id')->constrained('orders_status'); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('orders'); - } -} diff --git a/database/migrations/2020_11_09_161858_create_orders_products.php b/database/migrations/2020_11_09_161858_create_orders_products.php deleted file mode 100644 index 588c541d..00000000 --- a/database/migrations/2020_11_09_161858_create_orders_products.php +++ /dev/null @@ -1,34 +0,0 @@ -foreignId('product_id')->constrained('products'); - $table->foreignId('order_id')->constrained('orders'); - $table->unsignedInteger('quantity')->default(1); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('orders_products'); - } -} diff --git a/database/migrations/2021_02_04_175136_create_customers_table.php b/database/migrations/2021_02_04_175136_create_customers_table.php deleted file mode 100644 index d378372f..00000000 --- a/database/migrations/2021_02_04_175136_create_customers_table.php +++ /dev/null @@ -1,42 +0,0 @@ -id(); - - $table->bigInteger('crm_id')->unsigned()->unique(); - - $table->string('email')->unique(); - $table->string('hashcode')->unique(); - - $table->rememberToken(); - - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('customers'); - } -} diff --git a/database/migrations/2021_02_04_180000_constrain_orders_to_customers.php b/database/migrations/2021_02_04_180000_constrain_orders_to_customers.php deleted file mode 100644 index 85c2b03f..00000000 --- a/database/migrations/2021_02_04_180000_constrain_orders_to_customers.php +++ /dev/null @@ -1,35 +0,0 @@ -foreignId('customer_id')->after('id')->constrained('customers'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('orders', function (Blueprint $table) { - $table->dropForeign(['customer_id']); - $table->dropColumn('customer_id'); - }); - } -} diff --git a/database/migrations/2021_03_16_111337_add_fields_to_products.php b/database/migrations/2021_03_16_111337_add_fields_to_products.php deleted file mode 100644 index 11dd40c4..00000000 --- a/database/migrations/2021_03_16_111337_add_fields_to_products.php +++ /dev/null @@ -1,49 +0,0 @@ -string('picture_large')->nullable()->after('picture'); - $table->string('sell_unit')->nullable()->after('stock'); - // Lier à une liste de valeurs. - $table->float('weight')->unsigned()->nullable()->after('sell_unit'); - $table->string('weight_unit')->nullable()->after('weight'); - // Lier à une liste de valeurs. - $table->string('product_type')->default('inco')->after('id'); - // Lier à une liste de valeurs. - // Mise en avant. - $table->boolean('star')->default(0)->after('slug'); - // Produit star. - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('products', function (Blueprint $table) { - $table->dropColumn('picture_large'); - $table->dropColumn('sell_unit'); - $table->dropColumn('weight'); - $table->dropColumn('weight_unit'); - $table->dropColumn('product_type'); - $table->dropColumn('star'); - }); - } -} diff --git a/database/migrations/2021_03_16_135155_create_food_products.php b/database/migrations/2021_03_16_135155_create_food_products.php deleted file mode 100644 index 002ddcde..00000000 --- a/database/migrations/2021_03_16_135155_create_food_products.php +++ /dev/null @@ -1,111 +0,0 @@ -id(); - - // Liaison à la table produits. - $table->foreignId('product_id')->constrained('products'); - - $table->unsignedInteger('no_art')->nullable(); - - // Autre info (venues de INCO). - $table->text('ingredients')->nullable(); - $table->text('preparation')->nullable(); - $table->unsignedInteger('servings')->nullable(); - $table->text('allergens')->nullable(); - $table->text('selling_argument')->nullable(); - - // Valeurs nutritionnelles ref. - $table->float('nv_ref_weight_g')->unsigned()->nullable(); - // Taille de la référence en grammes. - $table->float('nv_kj')->unsigned()->nullable(); - // Energie Kj. - $table->float('nv_kcal')->unsigned()->nullable(); - // Energie Kcal. - $table->float('nv_fat_g')->unsigned()->nullable(); - // Graisses. - $table->float('nv_sat_fat_g')->unsigned()->nullable(); - // Dont acides gras saturés. - $table->float('nv_carb_g')->unsigned()->nullable(); - // Glucides. - $table->float('nv_sugar_g')->unsigned()->nullable(); - // Dont sucres. - $table->float('nv_fiber_g')->unsigned()->nullable(); - // Fibres alimentaires. - $table->float('nv_protein_g')->unsigned()->nullable(); - // Protéines. - $table->float('nv_salt_g')->unsigned()->nullable(); - // Sel. - // Valeurs nutritionnelles par portion. - $table->float('nv_serving_size_g')->unsigned()->nullable(); - // Taille portion en grammes. - $table->float('nv_serving_kj')->unsigned()->nullable(); - // Energie Kj. - $table->float('nv_serving_kcal')->unsigned()->nullable(); - // Energie Kcal. - $table->float('nv_serving_fat_g')->unsigned()->nullable(); - // Graisses. - $table->float('nv_serving_sat_fat_g')->unsigned()->nullable(); - // Dont acides gras saturés. - $table->float('nv_serving_carb_g')->unsigned()->nullable(); - // Glucides. - $table->float('nv_serving_sugar_g')->unsigned()->nullable(); - // Dont sucres. - $table->float('nv_serving_fiber_g')->unsigned()->nullable(); - // Fibres alimentaires. - $table->float('nv_serving_protein_g')->unsigned()->nullable(); - // Protéines. - $table->float('nv_serving_salt_g')->unsigned()->nullable(); - // Sel. - // Apports journaliers. - $table->float('nv_daily_energy')->unsigned()->nullable(); - // Energie % recommandé. - $table->float('nv_daily_fat')->unsigned()->nullable(); - // Graisses. - $table->float('nv_daily_sat_fat')->unsigned()->nullable(); - // Dont acides gras saturés. - $table->float('nv_daily_carb')->unsigned()->nullable(); - // Glucides. - $table->float('nv_daily_sugar')->unsigned()->nullable(); - // Dont sucres. - $table->float('nv_daily_fiber')->unsigned()->nullable(); - // Fibres alimentaires. - $table->float('nv_daily_protein')->unsigned()->nullable(); - // Protéines. - $table->float('nv_daily_salt')->unsigned()->nullable(); - // Sel. - // Nutriscore. - $table->string('nutriscore')->nullable(); - $table->text('nutriscore_args')->nullable(); - - $table->timestamps(); - $table->collation = 'utf8mb4_unicode_ci'; - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('food_products'); - } -} diff --git a/database/migrations/2021_03_16_140753_create_products_products.php b/database/migrations/2021_03_16_140753_create_products_products.php deleted file mode 100644 index 8d9c5a65..00000000 --- a/database/migrations/2021_03_16_140753_create_products_products.php +++ /dev/null @@ -1,37 +0,0 @@ -foreignId('product_id')->constrained('products'); - // Produit considéré. - $table->foreignId('associated_id')->constrained('products'); - // Produit à afficher dans 'vous aimerez aussi'. - $table->collation = 'utf8mb4_unicode_ci'; - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('products_products'); - } -} diff --git a/database/migrations/2021_03_17_093244_add_fields_to_contents.php b/database/migrations/2021_03_17_093244_add_fields_to_contents.php deleted file mode 100644 index b96efc4c..00000000 --- a/database/migrations/2021_03_17_093244_add_fields_to_contents.php +++ /dev/null @@ -1,38 +0,0 @@ -string('title')->nullable()->after('key'); - $table->text('chapeau')->nullable()->after('value'); - $table->string('banner')->nullable()->after('chapeau'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('contents', function (Blueprint $table) { - $table->dropColumn('title'); - $table->dropColumn('chapeau'); - $table->dropColumn('banner'); - }); - } -} diff --git a/database/migrations/2021_03_27_163403_create_order_lines_table.php b/database/migrations/2021_03_27_163403_create_order_lines_table.php deleted file mode 100644 index b88c3fc4..00000000 --- a/database/migrations/2021_03_27_163403_create_order_lines_table.php +++ /dev/null @@ -1,49 +0,0 @@ -id(); - - $table->foreignId('order_id')->constrained('orders'); - $table->foreignId('product_id')->nullable()->constrained('products'); - // Future foreign keys to shipping tables, and other expanses which are not products. - $table->unsignedInteger('quantity')->default(1); - // Nullable fields below. - $table->float('unit_price')->default(0); - $table->float('unit_tax')->default(0); - $table->float('unit_discount')->default(0); - $table->float('tax_rate')->default(0); - $table->float('total_ttc')->default(0); - $table->float('total_ht')->default(0); - $table->float('total_tax')->default(0); - $table->float('total_discount')->default(0); - $table->string('commentaire')->nullable(); - - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('order_lines'); - } -} diff --git a/database/migrations/2021_03_29_114933_create_timeslots_table.php b/database/migrations/2021_03_29_114933_create_timeslots_table.php deleted file mode 100644 index 3b3b7d9b..00000000 --- a/database/migrations/2021_03_29_114933_create_timeslots_table.php +++ /dev/null @@ -1,36 +0,0 @@ -id(); - $table->foreignId('order_id')->constrained('orders'); - $table->string('day'); - $table->string('time'); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('timeslots'); - } -} diff --git a/database/migrations/2021_04_06_153634_create_discount_types_table.php b/database/migrations/2021_04_06_153634_create_discount_types_table.php deleted file mode 100644 index a129193e..00000000 --- a/database/migrations/2021_04_06_153634_create_discount_types_table.php +++ /dev/null @@ -1,33 +0,0 @@ -id(); - $table->string('label'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('discount_types'); - } -} diff --git a/database/migrations/2021_04_06_154003_create_promotions_table.php b/database/migrations/2021_04_06_154003_create_promotions_table.php deleted file mode 100644 index 424a211b..00000000 --- a/database/migrations/2021_04_06_154003_create_promotions_table.php +++ /dev/null @@ -1,37 +0,0 @@ -id(); - $table->foreignId('discount_type_id')->default(1)->constrained('discount_types'); - $table->float('discount_value')->default(0); - $table->timestamp('date_start')->nullable(); - $table->timestamp('date_end')->nullable(); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('promotions'); - } -} diff --git a/database/migrations/2021_04_07_100613_create_product_promotion_table.php b/database/migrations/2021_04_07_100613_create_product_promotion_table.php deleted file mode 100644 index 9f6ed961..00000000 --- a/database/migrations/2021_04_07_100613_create_product_promotion_table.php +++ /dev/null @@ -1,36 +0,0 @@ -foreignId('product_id')->constrained('products'); - // Produit considéré. - $table->foreignId('promotion_id')->constrained('promotions'); - // Promotion associée. - $table->collation = 'utf8mb4_unicode_ci'; - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('product_promotion'); - } -} diff --git a/database/migrations/2021_04_07_153852_create_tax_rates_table.php b/database/migrations/2021_04_07_153852_create_tax_rates_table.php deleted file mode 100644 index aea8a749..00000000 --- a/database/migrations/2021_04_07_153852_create_tax_rates_table.php +++ /dev/null @@ -1,34 +0,0 @@ -id(); - $table->string('label'); - $table->float('rate'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('tax_rates'); - } -} diff --git a/database/migrations/2021_04_07_154718_add_fields_to_products_table.php b/database/migrations/2021_04_07_154718_add_fields_to_products_table.php deleted file mode 100644 index aeb4cc01..00000000 --- a/database/migrations/2021_04_07_154718_add_fields_to_products_table.php +++ /dev/null @@ -1,35 +0,0 @@ -foreignId('tax_rate_id')->after('price_buy')->default(1)->constrained('tax_rates'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('products', function (Blueprint $table) { - $table->dropForeign(['tax_rate_id']); - $table->dropColumn('tax_rate_id'); - }); - } -} diff --git a/database/migrations/2021_04_09_081311_create_tags_table.php b/database/migrations/2021_04_09_081311_create_tags_table.php deleted file mode 100644 index da370abf..00000000 --- a/database/migrations/2021_04_09_081311_create_tags_table.php +++ /dev/null @@ -1,35 +0,0 @@ -id(); - $table->string('label'); - $table->string('slug'); - $table->collation = 'utf8mb4_unicode_ci'; - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('tags'); - } -} diff --git a/database/migrations/2021_04_09_081345_create_product_tag_table.php b/database/migrations/2021_04_09_081345_create_product_tag_table.php deleted file mode 100644 index befb6d2d..00000000 --- a/database/migrations/2021_04_09_081345_create_product_tag_table.php +++ /dev/null @@ -1,35 +0,0 @@ -foreignId('product_id')->constrained('products'); - // Produit considéré. - $table->foreignId('tag_id')->constrained('tags'); - // Tag associée. - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('product_tag'); - } -} diff --git a/database/migrations/2021_04_13_142701_remove_deprecated_tables.php b/database/migrations/2021_04_13_142701_remove_deprecated_tables.php deleted file mode 100644 index 56ee00f4..00000000 --- a/database/migrations/2021_04_13_142701_remove_deprecated_tables.php +++ /dev/null @@ -1,30 +0,0 @@ -id(); - $table->string('label'); - $table->string('slug'); - $table->unique('slug'); - $table->string('commentaire')->nullable(); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('sliders'); - } -} diff --git a/database/migrations/2021_04_14_115954_create_slides_table.php b/database/migrations/2021_04_14_115954_create_slides_table.php deleted file mode 100644 index e3b30743..00000000 --- a/database/migrations/2021_04_14_115954_create_slides_table.php +++ /dev/null @@ -1,46 +0,0 @@ -id(); - $table->foreignId('slider_id')->default(1)->constrained('sliders'); - - $table->string('title'); - $table->text('text')->nullable(); - $table->string('picture')->nullable(); - $table->string('link_label')->nullable(); - $table->string('link')->nullable(); - $table->boolean('link_new_tab')->default(false); - $table->integer('order')->default(1); - - $table->timestamp('date_start')->nullable(); - $table->timestamp('date_end')->nullable(); - - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('slides'); - } -} diff --git a/database/migrations/2021_04_19_145945_extend_champ_description_in_ranges_table.php b/database/migrations/2021_04_19_145945_extend_champ_description_in_ranges_table.php deleted file mode 100644 index 351c7be0..00000000 --- a/database/migrations/2021_04_19_145945_extend_champ_description_in_ranges_table.php +++ /dev/null @@ -1,33 +0,0 @@ -text('description')->change(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('ranges', function (Blueprint $table) { - }); - } -} diff --git a/database/migrations/2021_04_19_155920_change_optional_fields_in_products_table.php b/database/migrations/2021_04_19_155920_change_optional_fields_in_products_table.php deleted file mode 100644 index e19b9355..00000000 --- a/database/migrations/2021_04_19_155920_change_optional_fields_in_products_table.php +++ /dev/null @@ -1,34 +0,0 @@ -integer('stock')->nullable()->change(); - $table->string('reference')->nullable()->change(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('products', function (Blueprint $table) { - }); - } -} diff --git a/database/migrations/2021_04_20_154225_create_timeslot_settings_table.php b/database/migrations/2021_04_20_154225_create_timeslot_settings_table.php deleted file mode 100644 index adbef2db..00000000 --- a/database/migrations/2021_04_20_154225_create_timeslot_settings_table.php +++ /dev/null @@ -1,43 +0,0 @@ -id(); - - $table->enum('day_index', [0, 1, 2, 3, 4, 5, 6])->nullable()->unique(); - $table->string('morning_start')->nullable(); - $table->string('morning_end')->nullable(); - $table->string('afternoon_start')->nullable(); - $table->string('afternoon_end')->nullable(); - $table->string('interval')->nullable(); - $table->unsignedInteger('max_orders_per_interval')->nullable(); - $table->string('min_order_preparation')->nullable(); - - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('timeslot_settings'); - } -} diff --git a/database/migrations/2021_04_21_092030_create_jobs_table.php b/database/migrations/2021_04_21_092030_create_jobs_table.php deleted file mode 100644 index b5f2b233..00000000 --- a/database/migrations/2021_04_21_092030_create_jobs_table.php +++ /dev/null @@ -1,38 +0,0 @@ -bigIncrements('id'); - $table->string('queue')->index(); - $table->longText('payload'); - $table->unsignedTinyInteger('attempts'); - $table->unsignedInteger('reserved_at')->nullable(); - $table->unsignedInteger('available_at'); - $table->unsignedInteger('created_at'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('jobs'); - } -} diff --git a/database/migrations/2021_04_21_101455_create_xml_incos_table.php b/database/migrations/2021_04_21_101455_create_xml_incos_table.php deleted file mode 100644 index a9bf2e71..00000000 --- a/database/migrations/2021_04_21_101455_create_xml_incos_table.php +++ /dev/null @@ -1,53 +0,0 @@ -id(); - - $table->boolean('prod_saison'); - - $table->string('allegations')->nullable(); - $table->text('descriptif')->nullable(); - $table->json('picture'); - $table->text('astuces')->nullable(); - $table->string('lib_conso')->nullable(); - $table->string('nb_portion', 20)->nullable(); - $table->string('typ_portion', 200)->nullable(); - $table->string('pds_moy_theo', 20)->nullable(); - - $table->text('conseil_prepa')->nullable(); - $table->text('arg_vente')->nullable(); - $table->text('lst_ing')->nullable(); - $table->text('lib_allergene')->nullable(); - - $table->json('nutritional_values'); - - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('xml_incos'); - } -} diff --git a/database/migrations/2021_04_21_154354_create_collecte_exceptions_table.php b/database/migrations/2021_04_21_154354_create_collecte_exceptions_table.php deleted file mode 100644 index 791f1600..00000000 --- a/database/migrations/2021_04_21_154354_create_collecte_exceptions_table.php +++ /dev/null @@ -1,35 +0,0 @@ -id(); - $table->date('date'); - $table->string('comment')->nullable(); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('collecte_exceptions'); - } -} diff --git a/database/migrations/2021_04_21_165607_create_magasins_table.php b/database/migrations/2021_04_21_165607_create_magasins_table.php deleted file mode 100644 index b9ef45cc..00000000 --- a/database/migrations/2021_04_21_165607_create_magasins_table.php +++ /dev/null @@ -1,43 +0,0 @@ -id(); - $table->string('name'); - $table->string('address'); - $table->string('postcode'); - $table->string('city'); - $table->string('phone')->nullable(); - $table->string('latitude')->nullable(); - $table->string('longitude')->nullable(); - $table->text('gmaps_placeid')->nullable(); - $table->text('gmaps_link_href')->nullable(); - $table->text('gmaps_embed_href')->nullable(); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('magasins'); - } -} diff --git a/database/migrations/2021_04_22_153147_make_child_of_magasins_time_settings_table.php b/database/migrations/2021_04_22_153147_make_child_of_magasins_time_settings_table.php deleted file mode 100644 index f5d4831e..00000000 --- a/database/migrations/2021_04_22_153147_make_child_of_magasins_time_settings_table.php +++ /dev/null @@ -1,56 +0,0 @@ -dropUnique('timeslot_settings_day_index_unique'); - $table->foreignId('magasin_id')->after('id')->default(1)->constrained('magasins'); - $table->unique(['magasin_id', 'day_index']); - }); - - Schema::table('timeslot_settings', function (Blueprint $table) { - $table->unsignedBigInteger('magasin_id')->default(null)->change(); - }); - - Schema::table('collecte_exceptions', function (Blueprint $table) { - $table->foreignId('magasin_id')->after('id')->default(1)->constrained('magasins'); - }); - - Schema::table('collecte_exceptions', function (Blueprint $table) { - $table->unsignedBigInteger('magasin_id')->default(null)->change(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('timeslot_settings', function (Blueprint $table) { - $table->dropForeign(['magasin_id']); - $table->dropUnique('timeslot_settings_magasin_id_day_index_unique'); - $table->dropColumn('magasin_id'); - $table->unique('day_index'); - }); - - Schema::table('collecte_exceptions', function (Blueprint $table) { - $table->dropForeign(['magasin_id']); - $table->dropColumn('magasin_id'); - }); - } -} diff --git a/database/migrations/2021_04_23_112008_add_magasin_to_timeslots_table.php b/database/migrations/2021_04_23_112008_add_magasin_to_timeslots_table.php deleted file mode 100644 index fd9dcc8a..00000000 --- a/database/migrations/2021_04_23_112008_add_magasin_to_timeslots_table.php +++ /dev/null @@ -1,39 +0,0 @@ -foreignId('magasin_id')->after('order_id')->default(1)->constrained('magasins'); - }); - - Schema::table('timeslots', function (Blueprint $table) { - $table->unsignedBigInteger('magasin_id')->default(null)->change(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('timeslots', function (Blueprint $table) { - $table->dropForeign(['magasin_id']); - $table->dropColumn('magasin_id'); - }); - } -} diff --git a/database/migrations/2021_04_26_161004_make_unique_no_art_inf_food_products_table.php b/database/migrations/2021_04_26_161004_make_unique_no_art_inf_food_products_table.php deleted file mode 100644 index e88b27d7..00000000 --- a/database/migrations/2021_04_26_161004_make_unique_no_art_inf_food_products_table.php +++ /dev/null @@ -1,33 +0,0 @@ -unique('no_art'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('food_products', function (Blueprint $table) { - }); - } -} diff --git a/database/migrations/2021_05_03_173156_alter_products_table.php b/database/migrations/2021_05_03_173156_alter_products_table.php deleted file mode 100644 index 822b5ce3..00000000 --- a/database/migrations/2021_05_03_173156_alter_products_table.php +++ /dev/null @@ -1,36 +0,0 @@ -string('product_type')->default(null)->change(); - $table->string('product_type')->nullable()->change(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('products', function (Blueprint $table) { - $table->string('product_type')->default('inco')->change(); - $table->string('product_type')->nullable(false)->change(); - }); - } -} diff --git a/database/migrations/2021_05_06_121330_create_tool_products_table.php b/database/migrations/2021_05_06_121330_create_tool_products_table.php deleted file mode 100644 index ef45ac44..00000000 --- a/database/migrations/2021_05_06_121330_create_tool_products_table.php +++ /dev/null @@ -1,39 +0,0 @@ -id(); - - // Liaison à la table produits. - $table->foreignId('product_id')->constrained('products'); - - // Longeur, largeur, puissance, usage, conseils ? - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('tool_products'); - } -} diff --git a/database/migrations/2021_05_06_121546_create_anifood_products_table.php b/database/migrations/2021_05_06_121546_create_anifood_products_table.php deleted file mode 100644 index 9c643e25..00000000 --- a/database/migrations/2021_05_06_121546_create_anifood_products_table.php +++ /dev/null @@ -1,39 +0,0 @@ -id(); - - // Liaison à la table produits. - $table->foreignId('product_id')->constrained('products'); - - // Compositions, portions ? - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('anifood_products'); - } -} diff --git a/database/migrations/2021_05_06_121656_create_garment_products_table.php b/database/migrations/2021_05_06_121656_create_garment_products_table.php deleted file mode 100644 index 2d6f77c5..00000000 --- a/database/migrations/2021_05_06_121656_create_garment_products_table.php +++ /dev/null @@ -1,39 +0,0 @@ -id(); - - // Liaison à la table produits. - $table->foreignId('product_id')->constrained('products'); - - // Taille, couleur, matière ? - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('garment_products'); - } -} diff --git a/database/migrations/2021_05_07_091803_add_management_flags_to_tags_table.php b/database/migrations/2021_05_07_091803_add_management_flags_to_tags_table.php deleted file mode 100644 index 0243d06c..00000000 --- a/database/migrations/2021_05_07_091803_add_management_flags_to_tags_table.php +++ /dev/null @@ -1,44 +0,0 @@ -integer('order')->after('slug')->default(1); - $table->boolean('status')->after('order')->default(1); - }); - - // Necessaire incrémentation des ordres pour l'existant. - $tags = Tag::all(); - foreach ($tags as $tag) { - $tag->order = $tag->id; - $tag->save(); - } - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('tags', function (Blueprint $table) { - $table->dropColumn('order'); - $table->dropColumn('status'); - }); - } -} diff --git a/database/migrations/2021_05_25_100049_add_fields_to_anifood_products_table.php b/database/migrations/2021_05_25_100049_add_fields_to_anifood_products_table.php deleted file mode 100644 index 9e56febf..00000000 --- a/database/migrations/2021_05_25_100049_add_fields_to_anifood_products_table.php +++ /dev/null @@ -1,36 +0,0 @@ -text('composition')->nullable()->after('product_id'); - $table->unsignedInteger('servings')->nullable()->after('composition')->nullable(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('anifood_products', function (Blueprint $table) { - $table->dropColumn('composition'); - $table->dropColumn('servings'); - }); - } -} diff --git a/database/migrations/2021_05_25_101151_add_fields_to_garment_products_table.php b/database/migrations/2021_05_25_101151_add_fields_to_garment_products_table.php deleted file mode 100644 index e7aa9b19..00000000 --- a/database/migrations/2021_05_25_101151_add_fields_to_garment_products_table.php +++ /dev/null @@ -1,38 +0,0 @@ -string('size')->nullable()->after('product_id'); - $table->string('color')->nullable()->after('size'); - $table->string('material')->nullable()->after('color'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('garment_products', function (Blueprint $table) { - $table->dropColumn('material'); - $table->dropColumn('color'); - $table->dropColumn('size'); - }); - } -} diff --git a/database/migrations/2021_06_07_124924_add_orderable_dates_to_products_table.php b/database/migrations/2021_06_07_124924_add_orderable_dates_to_products_table.php deleted file mode 100644 index 346ad7fc..00000000 --- a/database/migrations/2021_06_07_124924_add_orderable_dates_to_products_table.php +++ /dev/null @@ -1,36 +0,0 @@ -timestamp('orderable_start')->nullable()->after('status'); - $table->timestamp('orderable_end')->nullable()->after('orderable_start'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('products', function (Blueprint $table) { - $table->dropColumn('orderable_end'); - $table->dropColumn('orderable_start'); - }); - } -} diff --git a/database/migrations/2021_07_20_141844_create_salaries_table.php b/database/migrations/2021_07_20_141844_create_salaries_table.php deleted file mode 100644 index 1c5fb9ae..00000000 --- a/database/migrations/2021_07_20_141844_create_salaries_table.php +++ /dev/null @@ -1,41 +0,0 @@ -id(); - // Liaison à la table customers. - $table->foreignId('customer_id')->nullable()->constrained('customers'); - $table->string('matricule'); - $table->string('nom')->nullable(); - $table->string('prenom')->nullable(); - $table->timestamps(); - }); - - DB::statement('ALTER TABLE `salaries` ADD `code` VARBINARY(50) AFTER `prenom`'); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('salaries'); - } -} diff --git a/database/migrations/2021_07_27_103748_add_required_for_order_export_fields_to_products_table.php b/database/migrations/2021_07_27_103748_add_required_for_order_export_fields_to_products_table.php deleted file mode 100644 index 4c7d7076..00000000 --- a/database/migrations/2021_07_27_103748_add_required_for_order_export_fields_to_products_table.php +++ /dev/null @@ -1,40 +0,0 @@ -string('order_unit')->nullable()->after('sell_unit'); - // Unité de commande. - // Add invoicing_unit. - $table->string('invoicing_unit')->nullable()->after('price'); - // Unité de facturation. - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('products', function (Blueprint $table) { - $table->dropColumn('order_unit'); - $table->dropColumn('invoicing_unit'); - }); - } -} diff --git a/database/migrations/2021_09_24_091612_add_code_societe_to_salaries_table.php b/database/migrations/2021_09_24_091612_add_code_societe_to_salaries_table.php deleted file mode 100644 index 30c2320a..00000000 --- a/database/migrations/2021_09_24_091612_add_code_societe_to_salaries_table.php +++ /dev/null @@ -1,36 +0,0 @@ -integer('code_societe')->nullable()->after('prenom'); - // Code societe de rattachement (pour regate). - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('salaries', function (Blueprint $table) { - $table->dropColumn('code_societe'); - }); - } -} diff --git a/database/migrations/2021_11_18_144311_alter_price_to_products_table.php b/database/migrations/2021_11_18_144311_alter_price_to_products_table.php deleted file mode 100644 index 93f7dd18..00000000 --- a/database/migrations/2021_11_18_144311_alter_price_to_products_table.php +++ /dev/null @@ -1,36 +0,0 @@ -decimal('price', 8, 3)->change(); - $table->decimal('price_buy', 8, 3)->change(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('products', function (Blueprint $table) { - $table->decimal('price', 8, 2)->change(); - $table->decimal('price_buy', 8, 2)->change(); - }); - } -} diff --git a/database/migrations/2022_03_12_115802_add_nom_to_xml_incos_table.php b/database/migrations/2022_03_12_115802_add_nom_to_xml_incos_table.php deleted file mode 100644 index 4aa8ec1f..00000000 --- a/database/migrations/2022_03_12_115802_add_nom_to_xml_incos_table.php +++ /dev/null @@ -1,34 +0,0 @@ -string('nom')->nullable()->after('id'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('xml_incos', function (Blueprint $table) { - $table->dropColumn('nom'); - }); - } -} diff --git a/database/migrations/2022_04_14_143040_remove_crm_id_from_customers.php b/database/migrations/2022_04_14_143040_remove_crm_id_from_customers.php deleted file mode 100644 index f6bf66b2..00000000 --- a/database/migrations/2022_04_14_143040_remove_crm_id_from_customers.php +++ /dev/null @@ -1,35 +0,0 @@ -dropColumn('crm_id'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('customers', function (Blueprint $table) { - $table->bigInteger('crm_id')->unsigned()->unique() - ->after('id'); - }); - } -} diff --git a/database/migrations/2022_09_12_160131_add_brand_to_products.php b/database/migrations/2022_09_12_160131_add_brand_to_products.php deleted file mode 100644 index 83246c86..00000000 --- a/database/migrations/2022_09_12_160131_add_brand_to_products.php +++ /dev/null @@ -1,34 +0,0 @@ -string('brand')->nullable()->after('name'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('products', function (Blueprint $table) { - $table->dropColumn('brand'); - }); - } -} diff --git a/database/migrations/2022_09_14_090354_add_fields_to_salaries.php b/database/migrations/2022_09_14_090354_add_fields_to_salaries.php deleted file mode 100644 index 15343e83..00000000 --- a/database/migrations/2022_09_14_090354_add_fields_to_salaries.php +++ /dev/null @@ -1,45 +0,0 @@ -timestamp('start_date')->nullable()->after('prenom'); - $table->timestamp('end_date')->nullable()->after('start_date'); - $table->string('etablissement')->after('end_date'); - $table->string('site')->after('etablissement'); - $table->string('service')->after('site'); - // On supprime la colonne code_societe, on connectera les points de collecte à proposer via le site. - $table->dropColumn('code_societe'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('salaries', function (Blueprint $table) { - $table->dropColumn('start_date'); - $table->dropColumn('end_date'); - $table->dropColumn('etablissement'); - $table->dropColumn('site'); - $table->dropColumn('service'); - $table->integer('code_societe')->nullable()->after('prenom'); - }); - } -} diff --git a/database/migrations/2022_09_20_171712_link_magasin_to_salaries.php b/database/migrations/2022_09_20_171712_link_magasin_to_salaries.php deleted file mode 100644 index f8fe23e8..00000000 --- a/database/migrations/2022_09_20_171712_link_magasin_to_salaries.php +++ /dev/null @@ -1,36 +0,0 @@ -foreignId('magasin_id')->nullable()->after('service')->constrained('magasins'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('salaries', function (Blueprint $table) { - $table->dropForeign(['magasin_id']); - $table->dropColumn('magasin_id'); - }); - } -} diff --git a/database/migrations/2022_10_11_163252_add_variable_weight_to_products_table.php b/database/migrations/2022_10_11_163252_add_variable_weight_to_products_table.php deleted file mode 100644 index cc010f74..00000000 --- a/database/migrations/2022_10_11_163252_add_variable_weight_to_products_table.php +++ /dev/null @@ -1,34 +0,0 @@ -boolean('weight_variable')->after('weight_unit')->default(0); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('products', function (Blueprint $table) { - $table->dropColumn('weight_variable'); - }); - } -} diff --git a/database/migrations/2022_10_20_111255_alter_ranges_description_table.php b/database/migrations/2022_10_20_111255_alter_ranges_description_table.php deleted file mode 100644 index 2e37abdc..00000000 --- a/database/migrations/2022_10_20_111255_alter_ranges_description_table.php +++ /dev/null @@ -1,34 +0,0 @@ -text('description')->default(null)->nullable()->change(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('ranges', function (Blueprint $table) { - $table->text('description')->default(null)->nullable()->change(); - }); - } -} diff --git a/database/migrations/2023_03_30_110313_alter_product_serving_table.php b/database/migrations/2023_03_30_110313_alter_product_serving_table.php deleted file mode 100644 index e3b7f68d..00000000 --- a/database/migrations/2023_03_30_110313_alter_product_serving_table.php +++ /dev/null @@ -1,34 +0,0 @@ -string('servings', 20)->nullable()->change(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('food_products', function (Blueprint $table) { - $table->integer('servings')->default(null)->nullable()->change(); - }); - } -} diff --git a/database/migrations/2023_07_04_151150_alter_code_salaries_table.php b/database/migrations/2023_07_04_151150_alter_code_salaries_table.php deleted file mode 100644 index f1e51236..00000000 --- a/database/migrations/2023_07_04_151150_alter_code_salaries_table.php +++ /dev/null @@ -1,36 +0,0 @@ -string('code', 50)->unique()->change(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('salaries', function (Blueprint $table) { - $table->dropUnique('salaries_code_unique'); - }); - DB::statement('ALTER TABLE `salaries` MODIFY `code` VARBINARY(50) AFTER `prenom`'); - } -} diff --git a/database/migrations/2023_07_04_151446_format_day_in_timeslots_table.php b/database/migrations/2023_07_04_151446_format_day_in_timeslots_table.php deleted file mode 100644 index f1852da9..00000000 --- a/database/migrations/2023_07_04_151446_format_day_in_timeslots_table.php +++ /dev/null @@ -1,58 +0,0 @@ -date('date')->default('1999-01-01')->after('magasin_id'); - }); - foreach (DB::table('timeslots')->get() as $timeslot) { - // L'ancienne date est castée au format m/d/Y, une date FR comme le 30/06/2023 sera donc buguée. - // On récupère l'ancienne date non castée et on en crée une date valide. - $date = Carbon::createFromFormat('d/m/Y', $timeslot->day); - DB::table('timeslots')->where('id', $timeslot->id)->update(['date' => $date]); - } - Schema::table('timeslots', function (Blueprint $table) { - $table->dropColumn('day'); - $table->renameColumn('date', 'day'); - }); - // Not removing default above because it doesn't work. - Schema::table('timeslots', function (Blueprint $table) { - $table->date('day')->default(null)->change(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('timeslots', function (Blueprint $table) { - $table->string('date')->after('magasin_id'); - }); - foreach (DB::table('timeslots')->get() as $timeslot) { - $dateStr = Carbon::create($timeslot->day)->format('d/m/Y'); - DB::table('timeslots')->where('id', $timeslot->id)->update(['date' => $dateStr]); - } - Schema::table('timeslots', function (Blueprint $table) { - $table->dropColumn('day'); - $table->renameColumn('date', 'day'); - }); - } -} diff --git a/database/migrations/2023_07_26_091913_add_order_products_table.php b/database/migrations/2023_07_26_091913_add_order_products_table.php deleted file mode 100644 index 54fba6c5..00000000 --- a/database/migrations/2023_07_26_091913_add_order_products_table.php +++ /dev/null @@ -1,41 +0,0 @@ -integer('order')->default(1)->after('margin')->comment('Ordonnancement du produit.'); - }); - - $allProducts = Product::all(); - foreach ($allProducts as $key => $product) { - $product->order = ($key + 1); - $product->saveOrFail(); - } - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('products', function (Blueprint $table) { - $table->dropColumn('order'); - }); - } -} diff --git a/database/migrations/2023_07_27_145254_alter_birth_users_table.php b/database/migrations/2023_07_27_145254_alter_birth_users_table.php deleted file mode 100644 index af389392..00000000 --- a/database/migrations/2023_07_27_145254_alter_birth_users_table.php +++ /dev/null @@ -1,34 +0,0 @@ -dropColumn('date_of_birth'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('users', function (Blueprint $table) { - $table->date('date_of_birth')->nullable()->after('lastname'); - }); - } -} diff --git a/database/migrations/2023_07_27_150324_alter_role_users_table.php b/database/migrations/2023_07_27_150324_alter_role_users_table.php deleted file mode 100644 index 4a4ae768..00000000 --- a/database/migrations/2023_07_27_150324_alter_role_users_table.php +++ /dev/null @@ -1,35 +0,0 @@ -', 'equipe.web@ldc.fr')->get() as $user) { - $user->role = 2; - $user->saveOrFail(); - } - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - foreach (User::all() as $user) { - $user->role = 1; - $user->saveOrFail(); - } - } -} diff --git a/database/migrations/2023_07_27_153349_alter_clean_salaries_table.php b/database/migrations/2023_07_27_153349_alter_clean_salaries_table.php deleted file mode 100644 index f0211c7d..00000000 --- a/database/migrations/2023_07_27_153349_alter_clean_salaries_table.php +++ /dev/null @@ -1,49 +0,0 @@ -date('start_date')->nullable()->change(); - $table->date('end_date')->nullable()->change(); - $table->string('nom')->nullable(false)->change(); - $table->string('prenom')->nullable(false)->change(); - $table->string('code', 10)->nullable(false)->change(); - DB::statement( - 'ALTER TABLE `salaries` CHANGE COLUMN `magasin_id` `magasin_id` BIGINT(20) UNSIGNED NOT NULL AFTER `service`;' - ); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('salaries', function (Blueprint $table) { - $table->timestamp('start_date')->nullable()->change(); - $table->timestamp('end_date')->nullable()->change(); - $table->string('nom')->nullable()->change(); - $table->string('prenom')->nullable()->change(); - $table->string('code', 50)->nullable()->change(); - DB::statement( - 'ALTER TABLE `salaries` CHANGE COLUMN `magasin_id` `magasin_id` BIGINT(20) UNSIGNED NULL AFTER `service`;' - ); - }); - } -} diff --git a/database/migrations/2025_02_10_112337_add_type_to_exceptions_table.php b/database/migrations/2025_02_10_112337_add_type_to_exceptions_table.php deleted file mode 100644 index 6d40b5da..00000000 --- a/database/migrations/2025_02_10_112337_add_type_to_exceptions_table.php +++ /dev/null @@ -1,46 +0,0 @@ -string('type') - ->default('Jour férié') - ->after('comment') - ->comment('Type of exception day.'); - }); - - DB::table('collecte_exceptions') - ->where('comment', 'Jour férié') - ->update(['type' => 'Jour férié']); - - DB::table('collecte_exceptions') - ->where('comment', '<>', 'Jour férié') - ->update(['type' => 'Autre']); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('collecte_exceptions', function (Blueprint $table) { - $table->dropColumn('type'); - }); - } -} diff --git a/database/migrations/2026_02_04_102119_add_connected_field_in_slides_table.php b/database/migrations/2026_02_04_102119_add_connected_field_in_slides_table.php deleted file mode 100644 index ec0303ec..00000000 --- a/database/migrations/2026_02_04_102119_add_connected_field_in_slides_table.php +++ /dev/null @@ -1,31 +0,0 @@ -boolean('connected')->default(false) - ->comment('Slide visible only for connected customers.')->after('link_new_tab'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('slides', function (Blueprint $table) { - $table->dropColumn('connected'); - }); - } -} diff --git a/database/migrations/2026_02_25_102520_reorder_all_products.php b/database/migrations/2026_02_25_102520_reorder_all_products.php deleted file mode 100644 index f7ddb314..00000000 --- a/database/migrations/2026_02_25_102520_reorder_all_products.php +++ /dev/null @@ -1,31 +0,0 @@ -orderBy('order')->get(); - $order = 1; - foreach ($products as $product) { - $product->order = $order; - $product->saveOrFail(); - $order++; - } - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - // Nothing to revert. - } -}; diff --git a/database/migrations/2026_02_25_111055_add_boolean_display_old_value_for_promotions_table.php b/database/migrations/2026_02_25_111055_add_boolean_display_old_value_for_promotions_table.php deleted file mode 100644 index bae1b066..00000000 --- a/database/migrations/2026_02_25_111055_add_boolean_display_old_value_for_promotions_table.php +++ /dev/null @@ -1,34 +0,0 @@ -boolean('is_old_price_displayed')->comment('Should the old price be displayed ?')->after('discount_value'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('promotions', function (Blueprint $table) { - $table->dropColumn('is_old_price_displayed'); - }); - } -} diff --git a/database/migrations/2026_04_09_111244_delete_promotion_tag.php b/database/migrations/2026_04_09_111244_delete_promotion_tag.php deleted file mode 100644 index 23ff3dfd..00000000 --- a/database/migrations/2026_04_09_111244_delete_promotion_tag.php +++ /dev/null @@ -1,38 +0,0 @@ -where('tag_id', 13) - ->delete(); - - Tag::where('slug', 'promotion')->delete(); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - $promotion = new Tag(); - $promotion->label = 'Promotion'; - $promotion->slug = Str::slug($promotion->label); - $promotion->save(); - } -} diff --git a/database/migrations/2026_04_27_152343_add_unique_to_password_resets.php b/database/migrations/2026_04_27_152343_add_unique_to_password_resets.php deleted file mode 100644 index fd23af21..00000000 --- a/database/migrations/2026_04_27_152343_add_unique_to_password_resets.php +++ /dev/null @@ -1,30 +0,0 @@ -unique(['email']); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('password_resets', function (Blueprint $table) { - $table->dropUnique(['email']); - }); - } -}; diff --git a/database/migrations/2026_04_29_110121_rename_table_password_resets_to_customer_password_resets.php b/database/migrations/2026_04_29_110121_rename_table_password_resets_to_customer_password_resets.php deleted file mode 100644 index 762e846b..00000000 --- a/database/migrations/2026_04_29_110121_rename_table_password_resets_to_customer_password_resets.php +++ /dev/null @@ -1,30 +0,0 @@ -rename('customer_password_resets'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('customer_password_resets', function (Blueprint $table) { - $table->rename('password_resets'); - }); - } -}; diff --git a/database/migrations/2026_04_29_120913_remove_id_from_customer_password_resets.php b/database/migrations/2026_04_29_120913_remove_id_from_customer_password_resets.php deleted file mode 100644 index 34f87acf..00000000 --- a/database/migrations/2026_04_29_120913_remove_id_from_customer_password_resets.php +++ /dev/null @@ -1,30 +0,0 @@ -dropColumn('id'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('customer_password_resets', function (Blueprint $table) { - $table->id(); - }); - } -}; diff --git a/database/migrations/2026_05_06_164734_fix_slides_table.php b/database/migrations/2026_05_06_164734_fix_slides_table.php deleted file mode 100644 index ba00f4c8..00000000 --- a/database/migrations/2026_05_06_164734_fix_slides_table.php +++ /dev/null @@ -1,34 +0,0 @@ -unsignedInteger('order') - ->nullable(false) - ->change(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('slides', function (Blueprint $table) { - $table->integer('order') - ->nullable(false) - ->change(); - }); - } -}; diff --git a/database/migrations/2026_05_07_090552_delete_sliders_table.php b/database/migrations/2026_05_07_090552_delete_sliders_table.php deleted file mode 100644 index 1a6ac197..00000000 --- a/database/migrations/2026_05_07_090552_delete_sliders_table.php +++ /dev/null @@ -1,30 +0,0 @@ -dropForeign(['slider_id']); - $table->dropColumn('slider_id'); - }); - Schema::drop('sliders'); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_07_104436_migrate_slides_pictures.php b/database/migrations/2026_05_07_104436_migrate_slides_pictures.php deleted file mode 100644 index acdb4d73..00000000 --- a/database/migrations/2026_05_07_104436_migrate_slides_pictures.php +++ /dev/null @@ -1,59 +0,0 @@ -get()->map(function (object $slide) use ($disk) { - if ($slide->picture === null) { - return; - } - - $diskFilePath = "images/slides/{$slide->picture}"; - - if (! $disk->exists($diskFilePath)) { - throw new \RuntimeException("Missing file {$diskFilePath}"); - } - - $fileInfo = new \SplFileInfo($disk->path($diskFilePath)); - - $newFilePath = FileStorageHelper::storeFile( - new Slide(), - $fileInfo - ); - - DB::table('slides') - ->where('id', $slide->id) - ->update([ - 'picture' => $newFilePath, - ]); - }); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_07_115830_add_image_attributes_on_sliders.php b/database/migrations/2026_05_07_115830_add_image_attributes_on_sliders.php deleted file mode 100644 index f6541201..00000000 --- a/database/migrations/2026_05_07_115830_add_image_attributes_on_sliders.php +++ /dev/null @@ -1,32 +0,0 @@ -string('picture_title')->nullable()->after('picture'); - $table->string('picture_alt')->nullable()->after('picture'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('slides', function (Blueprint $table) { - $table->dropColumn('picture_title'); - $table->dropColumn('picture_alt'); - }); - } -}; diff --git a/database/migrations/2026_05_07_123948_add_status_to_slides.php b/database/migrations/2026_05_07_123948_add_status_to_slides.php deleted file mode 100644 index 5fb1c17a..00000000 --- a/database/migrations/2026_05_07_123948_add_status_to_slides.php +++ /dev/null @@ -1,30 +0,0 @@ -boolean('status')->after('order'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('slides', function (Blueprint $table) { - $table->dropColumn('status'); - }); - } -}; diff --git a/database/migrations/2026_05_12_162815_update_order_on_tags.php b/database/migrations/2026_05_12_162815_update_order_on_tags.php deleted file mode 100644 index 79c956dc..00000000 --- a/database/migrations/2026_05_12_162815_update_order_on_tags.php +++ /dev/null @@ -1,30 +0,0 @@ -integer('order')->unsigned()->change(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('tags', function (Blueprint $table) { - $table->integer('order')->change(); - }); - } -}; diff --git a/database/migrations/2026_05_12_172419_drop_anifoods_product_table.php b/database/migrations/2026_05_12_172419_drop_anifoods_product_table.php deleted file mode 100644 index 2c609640..00000000 --- a/database/migrations/2026_05_12_172419_drop_anifoods_product_table.php +++ /dev/null @@ -1,25 +0,0 @@ -dropColumn('product_type'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_13_165615_resole_salarie_shop_dynamically.php b/database/migrations/2026_05_13_165615_resole_salarie_shop_dynamically.php deleted file mode 100644 index 866a8620..00000000 --- a/database/migrations/2026_05_13_165615_resole_salarie_shop_dynamically.php +++ /dev/null @@ -1,131 +0,0 @@ -get(['id', 'magasin_id', 'site', 'service']); - - $magasin_salaries_exceptions = []; - $magasin_salaries = []; - - foreach ($salaries as $salarie) { - $resolved = $this->resolveNormalShop((string) $salarie->site, (string) $salarie->service); - - if ($resolved->magasin_id !== $salarie->magasin_id) { - $magasin_salaries_exceptions[] = [ - 'magasin_id' => $salarie->magasin_id, - 'salarie_id' => $salarie->id, - ]; - } else { - $key = $salarie->site . '_' . $resolved->service_id; - if (! isset($magasin_salaries[$key])) { - $magasin_salaries[$key] = [ - 'site_code' => $salarie->site, - 'service_code' => $resolved->service_id, - 'magasin_id' => $resolved->magasin_id, - ]; - } - } - } - - Schema::table('magasins', function (Blueprint $table) { - $table->boolean('default') - ->default(false) - ->after('gmaps_embed_href'); - }); - - Schema::table('salaries', function (Blueprint $table) { - $table->dropForeign(['magasin_id']); - $table->dropColumn('magasin_id'); - }); - - Schema::create('magasin_salarie', function (Blueprint $table) { - $table->id(); - $table->string('site_code'); - $table->string('service_code')->nullable(); - $table->foreignId('magasin_id')->constrained('magasins', 'id'); - $table->unique(['site_code', 'service_code']); - $table->comment('Permet de résoudre le magasin pour un salarie en fonction du site et éventuellement du service'); - }); - - Schema::create('magasin_salaries_exceptions', function (Blueprint $table) { - $table->foreignId('salarie_id')->constrained('salaries', 'id'); - $table->foreignId('magasin_id')->constrained('magasins', 'id'); - $table->primary(['salarie_id', 'magasin_id']); - $table->comment('Exceptions pour certains salariés afin de pallier au manque de cohérence coté régate'); - }); - - DB::transaction(function () use ($magasin_salaries, $magasin_salaries_exceptions) { - DB::table('magasins')->where('id', 1)->update(['default' => true]); - - if (! empty($magasin_salaries)) { - DB::table('magasin_salarie')->insert(array_values($magasin_salaries)); - } - - foreach (array_chunk($magasin_salaries_exceptions, 500) as $chunk) { - DB::table('magasin_salaries_exceptions')->insert($chunk); - } - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } - - /** - * Règles d'exceptions legacy en usage au 13/05/26 au moins. - * - * @return object{service_id:string|null,magasin_id:int} - */ - private function resolveNormalShop(string $site, string $service): object - { - $magasinId = match ($site) { - 'LDCCAV' => 3, // Cavol. - 'DDE' => 8, // Dinde. - 'DPE' => 9, // DPE. - 'CEPACPE' => match (true) { - in_array($service, ['CEPACP060', 'CEPACP070', 'CEPACP072']) => 6, // CPE. - in_array($service, ['CEPACP065', 'CEPACP066']) => 11, // PLB. - default => 10, // CEPA. - }, - 'LDCPLB' => 11, // PLB. - 'TPWISS' => 7, // Wissous. - - // Saint Laurent. - 'SL' => 1, - 'GDFROI' => 1, - 'SLELA' => 1, - default => 1, - }; - - // La règle ne dépend du service que pour le site "cepacpe". - // Pour les autres, la règle s'applique à tout le site (service = null). - $resolvedService = ($site === 'CEPACPE') ? $service : null; - - return (object) [ - 'service_id' => $resolvedService, - 'magasin_id' => $magasinId, - ]; - } -}; diff --git a/database/migrations/2026_05_15_085114_rename_tables.php b/database/migrations/2026_05_15_085114_rename_tables.php deleted file mode 100644 index 9150e872..00000000 --- a/database/migrations/2026_05_15_085114_rename_tables.php +++ /dev/null @@ -1,71 +0,0 @@ -dropForeign('salaries_customer_id_foreign'); - $table->foreign(['customer_id'])->references('id')->on('customers')->cascadeOnUpdate()->nullOnDelete(); - }); - - Schema::table('shop_employee_exception', function (Blueprint $table) { - $table->dropForeign('magasin_salaries_exceptions_salarie_id_foreign'); - $table->dropForeign('magasin_salaries_exceptions_magasin_id_foreign'); - $table->renameColumn('salarie_id', 'employee_id'); - $table->renameColumn('magasin_id', 'shop_id'); - $table->foreign(['employee_id'])->references('id')->on('employees')->cascadeOnUpdate()->cascadeOnDelete(); - $table->foreign(['shop_id'])->references('id')->on('shops')->cascadeOnUpdate()->cascadeOnDelete(); - }); - - Schema::table('shop_employees', function (Blueprint $table) { - $table->dropForeign('magasin_salarie_magasin_id_foreign'); - $table->renameColumn('magasin_id', 'shop_id'); - $table->foreign(['shop_id'])->references('id')->on('shops')->cascadeOnUpdate()->cascadeOnDelete(); - }); - - Schema::table('timeslot_exceptions', function (Blueprint $table) { - $table->dropForeign('collecte_exceptions_magasin_id_foreign'); - $table->renameColumn('magasin_id', 'shop_id'); - $table->foreign(['shop_id'])->references('id')->on('shops')->cascadeOnUpdate()->cascadeOnDelete(); - }); - - Schema::table('timeslot_settings', function (Blueprint $table) { - $table->dropForeign('timeslot_settings_magasin_id_foreign'); - $table->dropUnique('timeslot_settings_magasin_id_day_index_unique'); - $table->renameColumn('magasin_id', 'shop_id'); - $table->renameColumn('day_index', 'week_day'); - $table->foreign(['shop_id'])->references('id')->on('shops')->cascadeOnUpdate()->cascadeOnDelete(); - $table->unique(['shop_id', 'week_day']); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_15_094440_drop_discount_type_table.php b/database/migrations/2026_05_15_094440_drop_discount_type_table.php deleted file mode 100644 index 2bfd0b1c..00000000 --- a/database/migrations/2026_05_15_094440_drop_discount_type_table.php +++ /dev/null @@ -1,30 +0,0 @@ -dropForeign('promotions_discount_type_id_foreign'); - $table->renameColumn('discount_type_id', 'discount_type'); - }); - Schema::drop('discount_types'); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_15_095409_drop_ordre_status_table.php b/database/migrations/2026_05_15_095409_drop_ordre_status_table.php deleted file mode 100644 index d6ced9f5..00000000 --- a/database/migrations/2026_05_15_095409_drop_ordre_status_table.php +++ /dev/null @@ -1,30 +0,0 @@ -dropForeign('orders_status_id_foreign'); - $table->renameColumn('status_id', 'status'); - }); - Schema::drop('order_status'); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_15_095736_drop_order_products.php b/database/migrations/2026_05_15_095736_drop_order_products.php deleted file mode 100644 index 3c4b89ed..00000000 --- a/database/migrations/2026_05_15_095736_drop_order_products.php +++ /dev/null @@ -1,30 +0,0 @@ -dropForeign('orders_products_order_id_foreign'); - $table->dropForeign('orders_products_product_id_foreign'); - }); - Schema::drop('order_products'); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_15_100312_drop_tax_rates.php b/database/migrations/2026_05_15_100312_drop_tax_rates.php deleted file mode 100644 index 3c2cccfa..00000000 --- a/database/migrations/2026_05_15_100312_drop_tax_rates.php +++ /dev/null @@ -1,30 +0,0 @@ -dropForeign('products_tax_rate_id_foreign'); - $table->renameColumn('tax_rate_id', 'tax_rate'); - }); - Schema::drop('tax_rates'); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_15_102945_drop_settings.php b/database/migrations/2026_05_15_102945_drop_settings.php deleted file mode 100644 index c8636592..00000000 --- a/database/migrations/2026_05_15_102945_drop_settings.php +++ /dev/null @@ -1,25 +0,0 @@ -selectRaw('matricule, COUNT(matricule) as counts') - ->groupBy('matricule') - ->having('counts', '>', 1) - ->get(); - - // * Garder uniquement le plus récent - foreach ($duplicates as $duplicate) { - $idsToDelete = DB::table('employees') - ->where('matricule', $duplicate->matricule) - ->orderBy('id', 'desc') - ->skip(1) - ->take(PHP_INT_MAX) - ->pluck('id'); - - DB::table('employees')->whereIn('id', $idsToDelete)->delete(); - } - - Schema::table('employees', function (Blueprint $table) { - $table->unique('matricule'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_15_130940_add_unique_to_pages.php b/database/migrations/2026_05_15_130940_add_unique_to_pages.php deleted file mode 100644 index f624e72c..00000000 --- a/database/migrations/2026_05_15_130940_add_unique_to_pages.php +++ /dev/null @@ -1,31 +0,0 @@ -renameColumn('key', 'slug'); - $table->renameColumn('value', 'content'); - $table->renameColumn('chapeau', 'heading'); - $table->unique('slug'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_15_131427_remove_heading_from_pages_table.php b/database/migrations/2026_05_15_131427_remove_heading_from_pages_table.php deleted file mode 100644 index ba74cd09..00000000 --- a/database/migrations/2026_05_15_131427_remove_heading_from_pages_table.php +++ /dev/null @@ -1,29 +0,0 @@ -dropColumn('banner'); - $table->dropColumn('heading'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_15_133554_rename_promotions.php b/database/migrations/2026_05_15_133554_rename_promotions.php deleted file mode 100644 index 2b2a8c23..00000000 --- a/database/migrations/2026_05_15_133554_rename_promotions.php +++ /dev/null @@ -1,34 +0,0 @@ -dropForeign('product_promotion_product_id_foreign'); - $table->dropForeign('product_promotion_promotion_id_foreign'); - $table->renameColumn('promotion_id', 'offer_id'); - $table->foreign(['product_id'])->references('id')->on('products')->cascadeOnDelete()->cascadeOnUpdate(); - $table->foreign(['offer_id'])->references('id')->on('offers')->cascadeOnDelete()->cascadeOnUpdate(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_15_165156_add_order_to_faqs_table.php b/database/migrations/2026_05_15_165156_add_order_to_faqs_table.php deleted file mode 100644 index 8719c0c3..00000000 --- a/database/migrations/2026_05_15_165156_add_order_to_faqs_table.php +++ /dev/null @@ -1,43 +0,0 @@ -integer('order')->unsigned()->after('answer')->default(0); - }); - - $i = 0; - DB::table('faqs')->get()->each(function ($faq) use (&$i) { - DB::table('faqs')->where('id', $faq->id) - ->update(['order' => $i++]); - }); - - Schema::table('faqs', function (Blueprint $table) { - $table->integer('order')->unsigned()->after('answer')->change(); - $table->unique('order'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('faqs', function (Blueprint $table) { - $table->dropUnique(['order']); - $table->dropColumn('order'); - }); - } -}; diff --git a/database/migrations/2026_05_15_172544_add_seo_fields_on_pages_table.php b/database/migrations/2026_05_15_172544_add_seo_fields_on_pages_table.php deleted file mode 100644 index 68365671..00000000 --- a/database/migrations/2026_05_15_172544_add_seo_fields_on_pages_table.php +++ /dev/null @@ -1,68 +0,0 @@ -string('seo_title')->after('slug'); - $table->string('seo_description')->after('seo_title'); - }); - - DB::table('pages')->where('slug', 'accueil') - ->update([ - 'seo_title' => 'Accueil', - 'seo_description' => 'Page d\'accueil de la boutique.', - ]); - - DB::table('pages')->where('slug', 'contact') - ->update([ - 'seo_title' => 'Contactez-nous', - 'seo_description' => 'Procédure afin de contacter les gérants de la boutique.', - ]); - - DB::table('pages')->where('slug', 'legals') - ->update([ - 'seo_title' => 'Mentions légales & CGU', - 'seo_description' => 'Mentions légales et conditions générales d\'utilisations de la boutique.', - ]); - - DB::table('pages')->where('slug', 'cgv') - ->update([ - 'seo_title' => 'CGV', - 'seo_description' => 'Conditions générales de ventes de la boutique.', - ]); - - DB::table('pages')->where('slug', 'confidentialite') - ->update([ - 'seo_title' => 'Politique de confidentialité', - 'seo_description' => 'Politique de confidentialité de la boutique.', - ]); - - DB::table('pages')->where('slug', 'faq') - ->update([ - 'title' => 'Foire aux questions', - 'seo_title' => 'FAQ', - 'seo_description' => 'Foire aux questions fréquemment posées.', - ]); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_18_113005_migrate_old_slugs_to_redirect_package.php b/database/migrations/2026_05_18_113005_migrate_old_slugs_to_redirect_package.php deleted file mode 100644 index 8bc0e760..00000000 --- a/database/migrations/2026_05_18_113005_migrate_old_slugs_to_redirect_package.php +++ /dev/null @@ -1,67 +0,0 @@ -get()->map(function ($oldSlug) { - $isProduct = $oldSlug->product_id !== null; - $modelTable = $isProduct ? 'products' : 'ranges'; - $modelId = $oldSlug->product_id ?? $oldSlug->range_id; - - $oldSlugValue = $oldSlug->slug; - $newSlugValue = DB::table($modelTable)->where('id', $modelId)->first('slug')->slug; - - $model = $isProduct ? new Product() : new Range(); - // * Legacy Url for ranges - $oldQuery = $isProduct ? "/produit/{$oldSlugValue}" : "/gamme-de-produits/{$oldSlugValue}"; - $newQuery = self::formatRedirectionQuery($model->getFrontUrl($newSlugValue)); - - if ($oldQuery === $newQuery) { - return; - } - - DB::table('uwil_redirections')->insert([ - 'hash' => $oldQuery, - 'old_model_slug' => $oldSlugValue, - 'old_query' => $oldQuery, - 'new_query' => $newQuery, - 'model_redirectable_id' => $modelId, - 'model_redirectable_type' => $model->getMorphClass(), - 'redirect_type' => RedirectionType::model, - 'redirect_code' => 301, - ]); - }); - - Schema::drop('old_slugs'); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } - - private static function formatRedirectionQuery(string $url): string - { - return Str::of($url) - ->chopStart(\config('app.url')) - ->start('/') - ->value(); - } -}; diff --git a/database/migrations/2026_05_18_125014_migrate_ranges_pictures.php b/database/migrations/2026_05_18_125014_migrate_ranges_pictures.php deleted file mode 100644 index 527fb9ab..00000000 --- a/database/migrations/2026_05_18_125014_migrate_ranges_pictures.php +++ /dev/null @@ -1,59 +0,0 @@ -get()->map(function (object $range) use ($disk) { - if ($range->picture === null) { - return; - } - - $diskFilePath = "images/gammes/{$range->picture}"; - - if (! $disk->exists($diskFilePath)) { - throw new \RuntimeException("Missing file {$diskFilePath}"); - } - - $fileInfo = new \SplFileInfo($disk->path($diskFilePath)); - - $newFilePath = FileStorageHelper::storeFile( - new Range(), - $fileInfo - ); - - DB::table('ranges') - ->where('id', $range->id) - ->update([ - 'picture' => $newFilePath, - ]); - }); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_18_142859_add_order_to_ranges.php b/database/migrations/2026_05_18_142859_add_order_to_ranges.php deleted file mode 100644 index 0ba98dd3..00000000 --- a/database/migrations/2026_05_18_142859_add_order_to_ranges.php +++ /dev/null @@ -1,43 +0,0 @@ -integer('order')->unsigned()->after('status')->default(0); - }); - - $i = 0; - DB::table('ranges')->get()->each(function ($faq) use (&$i) { - DB::table('ranges')->where('id', $faq->id) - ->update(['order' => $i++]); - }); - - Schema::table('ranges', function (Blueprint $table) { - $table->integer('order')->unsigned()->after('status')->change(); - $table->unique('order'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('ranges', function (Blueprint $table) { - $table->dropUnique(['order']); - $table->dropColumn('order'); - }); - } -}; diff --git a/database/migrations/2026_05_18_152042_add_picture_title_to_ranges_table.php b/database/migrations/2026_05_18_152042_add_picture_title_to_ranges_table.php deleted file mode 100644 index a4af8d60..00000000 --- a/database/migrations/2026_05_18_152042_add_picture_title_to_ranges_table.php +++ /dev/null @@ -1,45 +0,0 @@ -string('picture_title')->nullable()->after('picture'); - $table->string('picture_alt')->nullable()->after('picture'); - }); - - DB::table('ranges')->get()->map(function ($range) { - DB::table('ranges')->where('id', $range->id)->update([ - 'picture_title' => $range->name, - 'picture_alt' => $range->name, - ]); - }); - - Schema::table('ranges', function (Blueprint $table) { - $table->string('picture_title')->change(); - $table->string('picture_alt')->change(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('ranges', function (Blueprint $table) { - $table->dropColumn('picture_title'); - $table->dropColumn('picture_alt'); - }); - } -}; diff --git a/database/migrations/2026_05_18_152043_add_picture_title_to_products_table.php b/database/migrations/2026_05_18_152043_add_picture_title_to_products_table.php deleted file mode 100644 index 427da53a..00000000 --- a/database/migrations/2026_05_18_152043_add_picture_title_to_products_table.php +++ /dev/null @@ -1,53 +0,0 @@ -string('picture_title')->nullable()->after('picture'); - $table->string('picture_alt')->nullable()->after('picture'); - $table->string('picture_large_title')->nullable()->after('picture_large'); - $table->string('picture_large_alt')->nullable()->after('picture_large'); - }); - - DB::table('products')->get()->map(function ($product) { - DB::table('products')->where('id', $product->id)->update([ - 'picture_title' => $product->name, - 'picture_alt' => $product->name, - 'picture_large_title' => $product->name, - 'picture_large_alt' => $product->name, - ]); - }); - - Schema::table('products', function (Blueprint $table) { - $table->string('picture_title')->change(); - $table->string('picture_alt')->change(); - $table->string('picture_large_title')->change(); - $table->string('picture_large_alt')->change(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('products', function (Blueprint $table) { - $table->dropColumn('picture_title'); - $table->dropColumn('picture_alt'); - $table->dropColumn('picture_large_title'); - $table->dropColumn('picture_large_alt'); - }); - } -}; diff --git a/database/migrations/2026_05_19_094421_change_some_columns_on_products_table.php b/database/migrations/2026_05_19_094421_change_some_columns_on_products_table.php deleted file mode 100644 index 95a9a64e..00000000 --- a/database/migrations/2026_05_19_094421_change_some_columns_on_products_table.php +++ /dev/null @@ -1,32 +0,0 @@ -where(['stock' => null])->update(['stock' => 0]); - Schema::table('products', function (Blueprint $table) { - $table->integer('stock')->default(0)->change(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('products', function (Blueprint $table) { - $table->integer('stock')->nullable()->change(); - }); - } -}; diff --git a/database/migrations/2026_05_19_101521_change_order_status.php b/database/migrations/2026_05_19_101521_change_order_status.php deleted file mode 100644 index 699b2c3a..00000000 --- a/database/migrations/2026_05_19_101521_change_order_status.php +++ /dev/null @@ -1,26 +0,0 @@ -whereNotIn('status', [1, 3, 7])->update(['status' => 1]); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - // Do nothing. - } -}; diff --git a/database/migrations/2026_05_19_101521_migrate_products_pictures.php b/database/migrations/2026_05_19_101521_migrate_products_pictures.php deleted file mode 100644 index 6546921e..00000000 --- a/database/migrations/2026_05_19_101521_migrate_products_pictures.php +++ /dev/null @@ -1,84 +0,0 @@ -get()->map(function (object $product) use ($disk) { - if ($product->picture === null) { - return; - } - - $newFilePath = null; - $diskFilePath = "images/produits/{$product->picture}"; - - if ($disk->exists($diskFilePath)) { - $fileInfo = new \SplFileInfo($disk->path($diskFilePath)); - - $newFilePath = FileStorageHelper::storeFile( - new Range(), - $fileInfo - ); - } - - DB::table('products') - ->where('id', $product->id) - ->update([ - 'picture' => $newFilePath, - ]); - }); - }); - - DB::transaction(function () use ($disk) { - DB::table('products')->get()->map(function (object $product) use ($disk) { - if ($product->picture_large === null) { - return; - } - - $newFilePath = null; - $diskFilePath = "images/produits/{$product->picture_large}"; - - if ($disk->exists($diskFilePath)) { - $fileInfo = new \SplFileInfo($disk->path($diskFilePath)); - - $newFilePath = FileStorageHelper::storeFile( - new Range(), - $fileInfo - ); - } - - DB::table('products') - ->where('id', $product->id) - ->update([ - 'picture_large' => $newFilePath, - ]); - }); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_19_101522_change_some_columns_2_on_products_table.php b/database/migrations/2026_05_19_101522_change_some_columns_2_on_products_table.php deleted file mode 100644 index 83ba9045..00000000 --- a/database/migrations/2026_05_19_101522_change_some_columns_2_on_products_table.php +++ /dev/null @@ -1,34 +0,0 @@ -string('brand')->change(); - $table->unique('order'); - $table->dropColumn('price_buy'); // * Non utilisé, juste presente en bo - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('products', function (Blueprint $table) { - $table->string('brand')->nullable()->change(); - $table->dropUnique(['order']); - $table->float('price_buy')->nullable()->after('invoicing_unit'); - }); - } -}; diff --git a/database/migrations/2026_05_20_113304_add_sort_order_to_product_product_table.php b/database/migrations/2026_05_20_113304_add_sort_order_to_product_product_table.php deleted file mode 100644 index d48a7c7e..00000000 --- a/database/migrations/2026_05_20_113304_add_sort_order_to_product_product_table.php +++ /dev/null @@ -1,30 +0,0 @@ -integer('sort_order')->default(0); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('product_product', function (Blueprint $table) { - $table->dropColumn('sort_order'); - }); - } -}; diff --git a/database/migrations/2026_05_20_123658_remove_margin_from_products_table.php b/database/migrations/2026_05_20_123658_remove_margin_from_products_table.php deleted file mode 100644 index 76595abd..00000000 --- a/database/migrations/2026_05_20_123658_remove_margin_from_products_table.php +++ /dev/null @@ -1,30 +0,0 @@ -dropColumn('margin'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('products', function (Blueprint $table) { - $table->float('margin')->unsigned()->default(0)->after('range_id'); - }); - } -}; diff --git a/database/migrations/2026_05_20_160028_change_product_inco_relation_with_product.php b/database/migrations/2026_05_20_160028_change_product_inco_relation_with_product.php deleted file mode 100644 index c7c239c0..00000000 --- a/database/migrations/2026_05_20_160028_change_product_inco_relation_with_product.php +++ /dev/null @@ -1,42 +0,0 @@ -unique('product_id'); - $table->dropUnique('food_products_no_art_unique'); - }); - DB::table('product_incos') - ->whereNull('no_art') - ->delete(); - Schema::table('product_incos', function (Blueprint $table) { - $table->integer('no_art')->unsigned()->change(); - $table->unique(['no_art']); - }); - Schema::table('product_incos', function (Blueprint $table) { - $table->dropForeign('food_products_product_id_foreign'); - $table->foreign(['product_id'])->references('id')->on('products') - ->cascadeOnDelete()->cascadeOnUpdate(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_21_103837_change_product_order_column.php b/database/migrations/2026_05_21_103837_change_product_order_column.php deleted file mode 100644 index 9e767189..00000000 --- a/database/migrations/2026_05_21_103837_change_product_order_column.php +++ /dev/null @@ -1,35 +0,0 @@ -orderBy('order', 'desc')->get(); - $i = $products->count() + 1; - $products->each(function ($product) use (&$i) { - DB::table('products')->where('id', $product->id) - ->update(['order' => $i--]); - }); - Schema::table('products', function (Blueprint $table) { - $table->bigInteger('order')->unsigned()->change(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_21_120644_remove_home_statis_page.php b/database/migrations/2026_05_21_120644_remove_home_statis_page.php deleted file mode 100644 index 8c910fc5..00000000 --- a/database/migrations/2026_05_21_120644_remove_home_statis_page.php +++ /dev/null @@ -1,25 +0,0 @@ -where('slug', 'accueil')->delete(); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_21_122658_rename_offers_to_discounts.php b/database/migrations/2026_05_21_122658_rename_offers_to_discounts.php deleted file mode 100644 index dbe00747..00000000 --- a/database/migrations/2026_05_21_122658_rename_offers_to_discounts.php +++ /dev/null @@ -1,38 +0,0 @@ -dropForeign('product_offer_offer_id_foreign'); - $table->dropForeign('product_offer_product_id_foreign'); - $table->renameColumn('offer_id', 'discount_id'); - }); - Schema::rename('product_offer', 'product_discount'); - Schema::rename('offers', 'discounts'); - Schema::table('product_discount', function (Blueprint $table) { - $table->foreign(['product_id'])->references('id')->on('products') - ->cascadeOnDelete()->cascadeOnUpdate(); - $table->foreign(['discount_id'])->references('id')->on('discounts') - ->cascadeOnDelete()->cascadeOnUpdate(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_21_131414_rename_offers_discounts.php b/database/migrations/2026_05_21_131414_rename_offers_discounts.php deleted file mode 100644 index fb4a859a..00000000 --- a/database/migrations/2026_05_21_131414_rename_offers_discounts.php +++ /dev/null @@ -1,25 +0,0 @@ -foreignId('discount_id')->nullable()->after('range_id') - ->constrained('discounts', 'id') - ->nullOnDelete()->cascadeOnUpdate(); - }); - - DB::table('discount_product')->get()->each(function ($table) { - DB::table('products')->where('id', $table->product_id) - ->update([ - 'discount_id' => $table->discount_id, - ]); - }); - - Schema::drop('discount_product'); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_21_163851_simplify_shops_map.php b/database/migrations/2026_05_21_163851_simplify_shops_map.php deleted file mode 100644 index 1d75f613..00000000 --- a/database/migrations/2026_05_21_163851_simplify_shops_map.php +++ /dev/null @@ -1,30 +0,0 @@ -dropColumn('gmaps_placeid'); - $table->dropColumn('gmaps_link_href'); - $table->dropColumn('gmaps_embed_href'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_22_101939_remove_time_slot_settings.php b/database/migrations/2026_05_22_101939_remove_time_slot_settings.php deleted file mode 100644 index 1c89f1ab..00000000 --- a/database/migrations/2026_05_22_101939_remove_time_slot_settings.php +++ /dev/null @@ -1,25 +0,0 @@ -dropColumn('time'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_22_102934_rename_shop_column_on_timeslots_table.php b/database/migrations/2026_05_22_102934_rename_shop_column_on_timeslots_table.php deleted file mode 100644 index e8db88cc..00000000 --- a/database/migrations/2026_05_22_102934_rename_shop_column_on_timeslots_table.php +++ /dev/null @@ -1,30 +0,0 @@ -dropForeign('timeslots_magasin_id_foreign'); - $table->renameColumn('magasin_id', 'shop_id'); - $table->foreign('shop_id')->references('id')->on('shops'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_22_104824_rename_time_slot_exceptions_table.php b/database/migrations/2026_05_22_104824_rename_time_slot_exceptions_table.php deleted file mode 100644 index 50496f20..00000000 --- a/database/migrations/2026_05_22_104824_rename_time_slot_exceptions_table.php +++ /dev/null @@ -1,25 +0,0 @@ -foreignId('shop_id') - ->constrained('shops', 'id') - ->cascadeOnUpdate()->cascadeOnDelete(); - $table->foreignId('pickup_exception_id') - ->constrained('pickup_exceptions', 'id') - ->cascadeOnUpdate()->cascadeOnDelete(); - - $table->unique(['shop_id', 'pickup_exception_id']); - }); - - Schema::table('pickup_exceptions', function (Blueprint $table) { - $table->renameColumn('comment', 'label'); - $table->dropForeign('timeslot_exceptions_shop_id_foreign'); - $table->boolean('repeatable')->after('label'); - $table->string('repeat_frequency')->after('repeatable')->default('Weekly') - ->comment('Enum Domain\Enums\RepeatFrequency'); - $table->string('label')->change(); - $table->dropColumn('type'); - }); - - DB::table('pickup_exceptions')->get()->each(function ($v) { - DB::table('shop_pickup_exception')->insertOrIgnore([ - 'shop_id' => $v->shop_id, - 'pickup_exception_id' => $v->id, - ]); - }); - - Schema::table('pickup_exceptions', function (Blueprint $table) { - $table->dropColumn('shop_id'); - }); - - $duplicates = DB::table('pickup_exceptions') - ->selectRaw('MIN(id) as keep_id, date, label') - ->groupBy('date', 'label') - ->havingRaw('COUNT(*) > 1') - ->get(); - - foreach ($duplicates as $duplicate) { - $dupIds = DB::table('pickup_exceptions') - ->where('date', $duplicate->date) - ->where('label', $duplicate->label) - ->where('id', '!=', $duplicate->keep_id) - ->pluck('id'); - - $shopIdsToLink = DB::table('shop_pickup_exception') - ->whereIn('pickup_exception_id', $dupIds) - ->pluck('shop_id'); - - $newLinks = $shopIdsToLink->map(fn ($shopId) => [ - 'shop_id' => $shopId, - 'pickup_exception_id' => $duplicate->keep_id, - ])->toArray(); - - DB::table('shop_pickup_exception')->insertOrIgnore($newLinks); - DB::table('shop_pickup_exception')->whereIn('pickup_exception_id', $dupIds)->delete(); - DB::table('pickup_exceptions')->whereIn('id', $dupIds)->delete(); - } - - Schema::table('pickup_exceptions', function (Blueprint $table) { - $table->unique(['date', 'label']); - }); - - $repeatables = [ - '2026-01-01' => '1er janvier', - '2026-04-06' => 'Lundi de Pâques', - '2026-05-01' => '1er mai', - '2026-05-08' => '8 mai', - '2026-05-14' => 'Ascension', - '2026-05-25' => 'Lundi de Pentecôte', - '2026-07-14' => '14 juillet', - '2026-08-15' => 'Assomption', - '2026-11-01' => 'Toussaint', - '2026-11-11' => '11 novembre', - '2026-12-25' => 'Jour de Noël', - ]; - - DB::table('pickup_exceptions') - ->whereIn('label', $repeatables) - ->delete(); - - // ! Dont run on migrate fresh - if (DB::table('pickup_exceptions')->count()) { - DB::table('pickup_exceptions')->insert( - collect($repeatables)->map(fn ($label, $date) => [ - 'date' => $date, - 'label' => $label, - 'repeatable' => true, - 'repeat_frequency' => 'Yearly', - 'created_at' => Date::now(), - 'updated_at' => Date::now(), - ])->all() - ); - } - - $repeatableExceptionIds = DB::table('pickup_exceptions')->whereIn('label', $repeatables)->pluck('id'); - $shopIds = DB::table('shops')->pluck('id'); - - $shopIds->each(function ($shopId) use ($repeatableExceptionIds) { - $records = $repeatableExceptionIds->map(fn ($exceptionId) => [ - 'shop_id' => $shopId, - 'pickup_exception_id' => $exceptionId, - ])->toArray(); - - DB::table('shop_pickup_exception')->upsert( - $records, - ['shop_id', 'pickup_exception_id'], - [] - ); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_26_095455_add_auto_updated_on_pickup_exceptions_table.php b/database/migrations/2026_05_26_095455_add_auto_updated_on_pickup_exceptions_table.php deleted file mode 100644 index 3ac36509..00000000 --- a/database/migrations/2026_05_26_095455_add_auto_updated_on_pickup_exceptions_table.php +++ /dev/null @@ -1,36 +0,0 @@ -boolean('auto_updated')->after('repeat_frequency'); - }); - - // * Previous migration made repeatable as autoupdated. - - DB::table('pickup_exceptions')->where('repeatable', true) - ->update(['auto_updated' => true]); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('pickup_exceptions', function (Blueprint $table) { - $table->dropColumn('auto_updated'); - }); - } -}; diff --git a/database/migrations/2026_05_26_143214_add_replacements_day_to_shop_pickup_exception_table.php b/database/migrations/2026_05_26_143214_add_replacements_day_to_shop_pickup_exception_table.php deleted file mode 100644 index 2180a3ea..00000000 --- a/database/migrations/2026_05_26_143214_add_replacements_day_to_shop_pickup_exception_table.php +++ /dev/null @@ -1,32 +0,0 @@ -date('replacement_date')->nullable()->after('pickup_exception_id'); - $blueprint->dateTime('order_deadline_at')->nullable()->after('replacement_date'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('shop_pickup_exception', function (Blueprint $blueprint) { - $blueprint->dropColumn('replacement_date'); - $blueprint->dropColumn('order_deadline_at'); - }); - } -}; diff --git a/database/migrations/2026_05_26_154849_convert_all_dates_to_utc.php b/database/migrations/2026_05_26_154849_convert_all_dates_to_utc.php deleted file mode 100644 index 67128545..00000000 --- a/database/migrations/2026_05_26_154849_convert_all_dates_to_utc.php +++ /dev/null @@ -1,119 +0,0 @@ - ['created_at'], - 'customers' => ['created_at', 'updated_at'], - 'discounts' => ['date_start', 'date_end', 'created_at', 'updated_at'], - 'failed_jobs' => ['failed_at'], - 'faqs' => ['created_at', 'updated_at'], - 'order_lines' => ['created_at', 'updated_at'], - 'orders' => ['created_at', 'updated_at'], - 'pages' => ['created_at', 'updated_at'], - 'pickup_exceptions' => ['created_at', 'updated_at'], - 'product_incos' => ['created_at', 'updated_at'], - 'products' => ['orderable_start', 'orderable_end', 'created_at', 'updated_at', 'deleted_at'], - 'ranges' => ['created_at', 'updated_at'], - 'shop_pickup_exception' => ['order_deadline_at'], - 'shoppingcart' => ['created_at', 'updated_at'], - 'shops' => ['created_at', 'updated_at'], - 'slides' => ['date_start', 'date_end', 'created_at', 'updated_at'], - 'stats' => ['created_at', 'updated_at'], - 'timeslots' => ['created_at', 'updated_at'], - 'users' => ['email_verified_at', 'created_at', 'updated_at'], - 'uwil_redirections' => ['created_at', 'updated_at'], - 'xml_incos' => ['created_at', 'updated_at'], - ]; - - public function up(): void - { - foreach ($this->schemaMapping as $table => $columns) { - $this->migrateTableTimezones($table, $columns, 'Europe/Paris', 'UTC'); - } - } - - public function down(): void - { - foreach ($this->schemaMapping as $table => $columns) { - $this->migrateTableTimezones($table, $columns, 'UTC', 'Europe/Paris'); - } - } - - /** - * @param array $columns - * - * @phpcs:disable - */ - private function migrateTableTimezones(string $table, array $columns, string $fromTz, string $toTz): void - { - if (! Schema::hasTable($table)) { - return; - } - - $hasId = Schema::hasColumn($table, 'id'); - - $query = DB::table($table)->where(function ($q) use ($columns) { - foreach ($columns as $column) { - $q->orWhereNotNull($column); - } - }); - - if ($hasId) { - $query->orderBy('id')->chunkById(500, function ($rows) use ($table, $columns, $fromTz, $toTz) { - foreach ($rows as $row) { - $updateData = []; - foreach ($columns as $column) { - if (! empty($row->{$column})) { - $updateData[$column] = $this->convertTz($row->{$column}, $fromTz, $toTz); - } - } - - if (! empty($updateData)) { - DB::table($table)->where('id', $row->id)->update($updateData); - } - } - }, 'id'); - } else { - $firstColumn = reset($columns); - - $query->orderBy($firstColumn) - ->chunk(500, function ($rows) use ($table, $columns, $fromTz, $toTz) { - foreach ($rows as $row) { - $updateData = []; - foreach ($columns as $column) { - if (! empty($row->{$column})) { - $updateData[$column] = $this->convertTz($row->{$column}, $fromTz, $toTz); - } - } - - if (! empty($updateData)) { - DB::table($table)->where((array) $row)->update($updateData); - } - } - }); - } - } - - private function convertTz(string $value, string $fromTz, string $toTz): string - { - try { - return Carbon::createFromFormat('Y-m-d H:i:s', $value, $fromTz) - ->setTimezone($toTz) - ->format('Y-m-d H:i:s'); - } catch (\Exception) { - return Carbon::parse($value, $fromTz) - ->setTimezone($toTz) - ->format('Y-m-d H:i:s'); - } - } -}; diff --git a/database/migrations/2026_05_28_095941_remove_order_comment.php b/database/migrations/2026_05_28_095941_remove_order_comment.php deleted file mode 100644 index d0c8bada..00000000 --- a/database/migrations/2026_05_28_095941_remove_order_comment.php +++ /dev/null @@ -1,30 +0,0 @@ -dropColumn('commentaire'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('orders', function (Blueprint $table) { - $table->string('commentaire')->nullable()->after('date'); - }); - } -}; diff --git a/database/migrations/2026_05_28_101213_consolidate_order.php b/database/migrations/2026_05_28_101213_consolidate_order.php deleted file mode 100644 index b7bd1d1f..00000000 --- a/database/migrations/2026_05_28_101213_consolidate_order.php +++ /dev/null @@ -1,58 +0,0 @@ -dropForeign('orders_customer_id_foreign'); - $table->json('employee')->nullable()->after('id')->comment('Domain\Models\ValueObjects\OrderEmployee'); - }); - DB::table('orders') - ->join('customers', 'orders.customer_id', '=', 'customers.id') - ->join('employees', 'customers.id', '=', 'employees.customer_id') - ->get([ - 'orders.id', - 'employees.matricule', - 'employees.nom', - 'employees.prenom', - 'employees.etablissement', - 'employees.site', - 'employees.service', - ])->each(function ($order) { - DB::table('orders')->where('id', $order->id) - ->update([ - 'employee' => json_encode([ - 'matricule' => $order->matricule, - 'firstname' => $order->nom, - 'lastname' => $order->prenom, - 'facility' => $order->etablissement, - 'site' => $order->site, - 'service' => $order->service, - ], \JSON_THROW_ON_ERROR), - ]); - }); - - Schema::table('orders', function (Blueprint $table) { - $table->dropColumn('customer_id'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_28_101213_convert_discount_value_as_int.php b/database/migrations/2026_05_28_101213_convert_discount_value_as_int.php deleted file mode 100644 index e723849f..00000000 --- a/database/migrations/2026_05_28_101213_convert_discount_value_as_int.php +++ /dev/null @@ -1,35 +0,0 @@ -get()->each(function ($discounts) { - DB::table('discounts')->where('id', $discounts->id)->update([ - 'discount_value' => $discounts->discount_type === 1 ? // ? Is Amount in euro - $discounts->discount_value * 100 : $discounts->discount_value, - ]); - }); - Schema::table('discounts', function (Blueprint $table) { - $table->integer('discount_value')->unsigned()->change(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_28_101213_convert_order_total_as_int.php b/database/migrations/2026_05_28_101213_convert_order_total_as_int.php deleted file mode 100644 index 8265d6a5..00000000 --- a/database/migrations/2026_05_28_101213_convert_order_total_as_int.php +++ /dev/null @@ -1,36 +0,0 @@ -get()->each(function ($orders) { - DB::table('orders')->where('id', $orders->id)->update([ - 'total' => $orders->total * 100, - ]); - }); - // * Delete lone negative order amount. - DB::table('orders')->where('id', 2096)->delete(); - Schema::table('orders', function (Blueprint $table) { - $table->integer('total')->unsigned()->change(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_28_101213_convert_product_prices_as_int.php b/database/migrations/2026_05_28_101213_convert_product_prices_as_int.php deleted file mode 100644 index ce7ddf12..00000000 --- a/database/migrations/2026_05_28_101213_convert_product_prices_as_int.php +++ /dev/null @@ -1,29 +0,0 @@ -get()->each(function ($product) { - DB::table('products')->where('id', $product->id)->update([ - 'price' => $product->price * 100, - ]); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_28_101213_rename_columns_on_discount_table.php b/database/migrations/2026_05_28_101213_rename_columns_on_discount_table.php deleted file mode 100644 index d965b467..00000000 --- a/database/migrations/2026_05_28_101213_rename_columns_on_discount_table.php +++ /dev/null @@ -1,29 +0,0 @@ -renameColumn('discount_value', 'value'); - $table->renameColumn('discount_type', 'type'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_05_28_102411_consolidate_order_lines.php b/database/migrations/2026_05_28_102411_consolidate_order_lines.php deleted file mode 100644 index d26ff89e..00000000 --- a/database/migrations/2026_05_28_102411_consolidate_order_lines.php +++ /dev/null @@ -1,163 +0,0 @@ -get()->each(function ($line) { - DB::table('order_lines')->where('id', $line->id)->update([ - 'unit_price' => $line->unit_price * 100, - 'unit_tax' => $line->unit_tax * 100, - 'unit_discount' => $line->unit_discount * 100, - 'tax_rate' => match ($line->tax_rate) { - // * Enum TaxRate - 20.0 => 1, - 5.5 => 2, - default => throw new \UnexpectedValueException( - "unhandled value '{$line->tax_rate}' for tax_rate" - ) - }, - 'total_ttc' => $line->total_ttc * 100, - 'total_ht' => $line->total_ht * 100, - 'total_tax' => $line->total_tax * 100, - 'total_discount' => $line->total_discount * 100, - ]); - }); - - Schema::table('order_lines', function (Blueprint $table) { - $table->integer('unit_price')->unsigned()->change(); - $table->integer('unit_tax')->unsigned()->change(); - $table->integer('unit_discount')->unsigned()->change(); - $table->smallInteger('tax_rate')->unsigned()->change(); - $table->integer('total_ttc')->unsigned()->change(); - $table->integer('total_ht')->unsigned()->change(); - $table->integer('total_tax')->unsigned()->change(); - $table->integer('total_discount')->unsigned()->change(); - }); - - Schema::table('order_lines', function (Blueprint $table) { - $table->dropColumn('commentaire'); - $table->dropForeign('order_lines_order_id_foreign'); - $table->dropForeign('order_lines_product_id_foreign'); - $table->foreign(['order_id'])->references('id')->on('orders') - ->cascadeOnUpdate()->cascadeOnDelete(); - $table->json('product')->after('order_id')->comment('Domain\Models\ValueObjects\OrderLineProduct'); - }); - - DB::table('order_lines') - ->join('products', 'order_lines.product_id', '=', 'products.id') - ->join('product_incos', 'products.id', '=', 'product_incos.product_id') - ->get([ - 'order_lines.id', - 'order_lines.tax_rate', - 'products.id as prod_id', - 'products.picture', - 'product_incos.no_art', - 'products.discount_id', - 'products.reference', - 'products.name', - 'products.brand', - 'products.weight', - 'products.weight_unit', - 'products.weight_variable', - 'products.order_unit', - 'products.price', - 'products.invoicing_unit', - 'products.status', - ])->each(function ($line) { - $discount = DB::table('discounts')->where('id', $line->discount_id)->first(); - - $discountedPrice = match ($discount?->type ?? null) { - null => null, - 1 => $this->calculateAmountDiscount((int) $line->price, $discount->value), - 2 => $this->calculatePercentDiscount((int) $line->price, $discount->value), - }; - - $priceKgTtc = $this->calculatePriceKgTtc( - basePriceHt: $discountedPrice ?? (int) $line->price, - taxRateEnum: $line->tax_rate, - status: (bool) $line->status, - invoicingUnit: $line->invoicing_unit, - weight: (int) $line->weight, - weightUnit: $line->weight_unit - ); - - $actualTaxRate = match ($line->tax_rate) { - 1 => 20.0, - 2 => 5.5, - default => 0.0, - }; - - DB::table('order_lines')->where('id', $line->id)->update([ - 'product' => json_encode([ - 'inco_id' => $line->no_art, - 'reference' => $line->reference, - 'name' => $line->name, - 'brand' => $line->brand, - 'weight' => $line->weight, - 'weight_unit' => $line->weight_unit, - 'weight_variable' => $line->weight_variable, - 'order_unit' => $line->order_unit, - 'price' => (int) $line->price, - 'discounted_price' => $discountedPrice, - 'price_kg_ttc' => $priceKgTtc, - 'tax_rate' => $actualTaxRate, - 'original_id' => $line->prod_id, - 'picture' => $line->picture, - ], \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES), - ]); - }); - - Schema::table('order_lines', function (Blueprint $table) { - $table->dropColumn('product_id'); - }); - } - - // * A ce moment Cart Calculator est arrondi à deux decimales - - private function calculatePercentDiscount(int $price, int $percentBy100): int - { - $percent = $percentBy100 / 100; - - // * Arrondir a deux décimales et tronquer comme dans le calculator. - return intval(round($price * ($percent / 100), 2)); - } - - private function calculateAmountDiscount(int $priceInCents, int $amountInCents): int - { - return $priceInCents - $amountInCents; - } - - private function calculatePriceKgTtc(int $basePriceHt, int $taxRateEnum, bool $status, string | int | null $invoicingUnit, int $weight, string | int | null $weightUnit): int - { - $taxMultiplier = match ($taxRateEnum) { - 1 => 1.20, // 20% - 2 => 1.055, // 5.5% - default => 1.0, - }; - - $priceTtc = $basePriceHt * $taxMultiplier; - - if ($status && $invoicingUnit === 'PCE' && $weight > 0) { - $weightInGrams = $weightUnit === 'KG' ? $weight * 1000 : $weight; - $ratio = 1000 / $weightInGrams; - - return intval(round($priceTtc * $ratio)); - } - - return intval(round($priceTtc)); - } -}; diff --git a/database/migrations/2026_06_01_130113_update_sliders_links.php b/database/migrations/2026_06_01_130113_update_sliders_links.php deleted file mode 100644 index 58c9ab3f..00000000 --- a/database/migrations/2026_06_01_130113_update_sliders_links.php +++ /dev/null @@ -1,36 +0,0 @@ -where('link', 'https://www.laboutiquedecocotte.fr/produits?search=Lou%C3%A9') - ->update([ - 'link' => '/produits?brand[]=loue', - 'link_label' => 'Volailles de Loué', - ]); - DB::table('slides') - ->where('link', 'https://www.laboutiquedecocotte.fr/produits?search=le+gaulois') - ->update([ - 'link' => '/produits?brand[]=legaulois', - 'link_label' => 'Produits Le Gaulois', - ]); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_06_01_150709_update_page_title.php b/database/migrations/2026_06_01_150709_update_page_title.php deleted file mode 100644 index ddae3044..00000000 --- a/database/migrations/2026_06_01_150709_update_page_title.php +++ /dev/null @@ -1,27 +0,0 @@ -where(['title' => 'CONDITIONS GENERALES DE VENTE']) - ->update(['title' => 'Conditions Generales de Vente']); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_06_03_143713_add_short_description_to_products_table.php b/database/migrations/2026_06_03_143713_add_short_description_to_products_table.php deleted file mode 100644 index 16d3810d..00000000 --- a/database/migrations/2026_06_03_143713_add_short_description_to_products_table.php +++ /dev/null @@ -1,58 +0,0 @@ -text('short_description')->nullable()->after('description'); - }); - - DB::table('products')->orderBy('id')->chunk(100, function ($products) { - foreach ($products as $product) { - if (empty($product->description)) { - continue; - } - - $shortDescription = null; - - if (preg_match('/]*>(.*?)<\/p>/is', $product->description, $matches)) { - $shortDescription = trim(strip_tags($matches[1])); - - $shortDescription = html_entity_decode($shortDescription); - } - - if (empty($shortDescription) && ! empty($product->description)) { - $shortDescription = Str::of($product->description)->stripTags()->limit(150, ''); - } - - DB::table('products') - ->where('id', $product->id) - ->update([ - 'short_description' => $shortDescription ?: null, - ]); - } - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('products', function (Blueprint $blueprint) { - $blueprint->dropColumn('short_description'); - }); - } -}; diff --git a/database/migrations/2026_06_04_154533_change_columns_to_int_on_products_table.php b/database/migrations/2026_06_04_154533_change_columns_to_int_on_products_table.php deleted file mode 100644 index fd3a731a..00000000 --- a/database/migrations/2026_06_04_154533_change_columns_to_int_on_products_table.php +++ /dev/null @@ -1,32 +0,0 @@ -integer('price')->change(); - $table->unsignedTinyInteger('tax_rate')->default(1)->change(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('products', function (Blueprint $table) { - $table->decimal('price', 8, 3)->change(); - $table->unsignedBigInteger('tax_rate')->default(1)->change(); - }); - } -}; diff --git a/database/migrations/2026_06_05_082126_strip_product_short_description.php b/database/migrations/2026_06_05_082126_strip_product_short_description.php deleted file mode 100644 index 03eaf640..00000000 --- a/database/migrations/2026_06_05_082126_strip_product_short_description.php +++ /dev/null @@ -1,30 +0,0 @@ -get()->each(function ($product) { - \DB::table('products')->where('id', $product->id) - ->update([ - 'short_description' => str(strval($product->short_description)) - ->limit(90, '...', true), - ]); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_06_05_112425_add_delivery_address_to_orders.php b/database/migrations/2026_06_05_112425_add_delivery_address_to_orders.php deleted file mode 100644 index 490d71d9..00000000 --- a/database/migrations/2026_06_05_112425_add_delivery_address_to_orders.php +++ /dev/null @@ -1,73 +0,0 @@ -json('delivery_address')->nullable()->after('employee'); - }); - - DB::table('timeslots') - ->join('shops', 'timeslots.shop_id', '=', 'shops.id') - ->select('timeslots.id as timeslot_id', 'timeslots.order_id', 'shops.*') - ->orderBy('timeslots.id') - ->chunkById(500, function ($records) { - foreach ($records as $record) { - $payload = json_encode([ - 'name' => ! empty($record->name) ? $record->name : self::DEFAULT_NAME, - 'address' => ! empty($record->address) ? $record->address : self::DEFAULT_ADDRESS, - 'postcode' => ! empty($record->postcode) ? $record->postcode : self::DEFAULT_POSTCODE, - 'city' => ! empty($record->city) ? $record->city : self::DEFAULT_CITY, - 'phone' => $record->phone ?? null, - 'latitude' => $record->latitude ?? null, - 'longitude' => $record->longitude ?? null, - ], JSON_UNESCAPED_UNICODE); - - DB::table('orders') - ->where('id', $record->order_id) - ->update(['delivery_address' => $payload]); - } - }, 'timeslots.id', 'timeslot_id'); - - $defaultPayload = json_encode([ - 'name' => self::DEFAULT_NAME, - 'address' => self::DEFAULT_ADDRESS, - 'postcode' => self::DEFAULT_POSTCODE, - 'city' => self::DEFAULT_CITY, - 'phone' => null, - 'latitude' => null, - 'longitude' => null, - ], JSON_UNESCAPED_UNICODE); - - DB::table('orders') - ->whereNull('delivery_address') - ->update(['delivery_address' => $defaultPayload]); - - Schema::table('orders', function (Blueprint $table) { - $table->json('delivery_address')->nullable(false)->change(); - }); - } - - public function down(): void - { - Schema::table('orders', function (Blueprint $table) { - $table->dropColumn('delivery_address'); - }); - } -}; diff --git a/database/migrations/2026_06_06_181952_migrate_products_to_uuidv7.php b/database/migrations/2026_06_06_181952_migrate_products_to_uuidv7.php deleted file mode 100644 index a1faf9d1..00000000 --- a/database/migrations/2026_06_06_181952_migrate_products_to_uuidv7.php +++ /dev/null @@ -1,190 +0,0 @@ -addTemporaryUuidColumn('products'); - $productMap = $this->generateProductUuids(); - - $this->makeUuidColumnRequired('products'); - - $this->updateOrderLinesJson($productMap); - - $productFkTables = ['product_incos', 'product_tag', 'stats']; - $this->updateForeignKeysForTables($productFkTables, 'products', 'product_id'); - - $this->updateProductProductTable(); - - $this->swapIdColumn('products'); - - $this->recreateForeignKeys($productFkTables, 'product_id', 'id', 'products'); - - Schema::table('product_product', function (Blueprint $table) { - $table->foreign('product_id')->references('id')->on('products')->cascadeOnDelete(); - $table->foreign('associated_id')->references('id')->on('products')->cascadeOnDelete(); - }); - - Schema::enableForeignKeyConstraints(); - } - - /** - * @throws \RuntimeException - */ - public function down(): void - { - throw new \RuntimeException( - 'This migration is irreversible: the transformation of products from integer IDs to UUIDv7 cannot be rolled back.' - ); - } - - private function dropForeignKeysForColumn(string $tableName, string $columnName): void - { - $fks = Schema::getForeignKeys($tableName); - foreach ($fks as $fk) { - if (in_array($columnName, $fk['columns'])) { - Schema::table($tableName, function (Blueprint $table) use ($fk) { - $table->dropForeign($fk['name']); - }); - } - } - } - - private function recreateForeignKeys(array $tables, string $columnName, string $references, string $onTable): void - { - foreach ($tables as $tableName) { - Schema::table($tableName, function (Blueprint $table) use ($columnName, $references, $onTable) { - $table->foreign($columnName)->references($references)->on($onTable)->cascadeOnDelete(); - }); - } - } - - private function addTemporaryUuidColumn(string $tableName): void - { - Schema::table($tableName, function (Blueprint $table) { - $table->uuid('uuid')->nullable()->after('id'); - }); - } - - private function makeUuidColumnRequired(string $tableName): void - { - Schema::table($tableName, function (Blueprint $table) { - $table->uuid('uuid')->nullable(false)->change(); - }); - } - - private function generateProductUuids(): array - { - $products = DB::table('products')->get(['id', 'reference', 'created_at']); - $productMap = []; - - foreach ($products as $product) { - $createdAt = $product->created_at ? Carbon::parse($product->created_at) : now(); - $uuid = UuidV7::generate($createdAt->toDateTimeImmutable()); - $productMap[$product->id] = ['uuid' => $uuid, 'reference' => $product->reference]; - - DB::table('products')->where('id', $product->id)->update(['uuid' => $uuid]); - } - - return $productMap; - } - - private function updateOrderLinesJson(array $productMap): void - { - $orderLines = DB::table('order_lines')->get(['id', 'product']); - foreach ($orderLines as $line) { - $productData = json_decode($line->product, true); - if (isset($productData['reference'])) { - $oldRef = $productData['reference']; - unset($productData['reference']); - - $foundUuid = null; - foreach ($productMap as $p) { - if ((string) $p['reference'] === (string) $oldRef) { - $foundUuid = $p['uuid']; - break; - } - } - - if ($foundUuid) { - $productData['original_id'] = UuidV7::fromString($foundUuid)->toBase58(); - } else { - $productData['original_id'] = $oldRef; - } - - DB::table('order_lines')->where('id', $line->id)->update([ - 'product' => json_encode($productData, JSON_UNESCAPED_SLASHES), - ]); - } - } - } - - private function updateForeignKeysForTables(array $tables, string $parentTable, string $columnName): void - { - $newColumn = 'new_' . $columnName; - foreach ($tables as $tableName) { - Schema::table($tableName, function (Blueprint $table) use ($newColumn, $columnName) { - $table->uuid($newColumn)->nullable()->after($columnName); - }); - - DB::table($tableName) - ->join($parentTable, "{$tableName}.{$columnName}", '=', "{$parentTable}.id") - ->update(["{$tableName}.{$newColumn}" => DB::raw("{$parentTable}.uuid")]); - - $this->dropForeignKeysForColumn($tableName, $columnName); - - Schema::table($tableName, function (Blueprint $table) use ($newColumn, $columnName) { - $table->dropColumn($columnName); - $table->renameColumn($newColumn, $columnName); - $table->uuid($columnName)->nullable(false)->change(); - }); - } - } - - private function updateProductProductTable(): void - { - Schema::table('product_product', function (Blueprint $table) { - $table->uuid('new_product_id')->nullable()->after('product_id'); - $table->uuid('new_associated_id')->nullable()->after('associated_id'); - }); - - DB::table('product_product') - ->join('products as p1', 'product_product.product_id', '=', 'p1.id') - ->join('products as p2', 'product_product.associated_id', '=', 'p2.id') - ->update([ - 'product_product.new_product_id' => DB::raw('p1.uuid'), - 'product_product.new_associated_id' => DB::raw('p2.uuid'), - ]); - - $this->dropForeignKeysForColumn('product_product', 'product_id'); - $this->dropForeignKeysForColumn('product_product', 'associated_id'); - - Schema::table('product_product', function (Blueprint $table) { - $table->dropColumn(['product_id', 'associated_id']); - $table->renameColumn('new_product_id', 'product_id'); - $table->renameColumn('new_associated_id', 'associated_id'); - $table->uuid('product_id')->nullable(false)->change(); - $table->uuid('associated_id')->nullable(false)->change(); - }); - } - - private function swapIdColumn(string $tableName): void - { - Schema::table($tableName, function (Blueprint $table) { - $table->dropColumn(['id', 'reference', 'created_at']); - $table->renameColumn('uuid', 'id'); - $table->primary('id'); - }); - } -}; diff --git a/database/migrations/2026_06_06_181953_migrate_orders_to_uuidv7.php b/database/migrations/2026_06_06_181953_migrate_orders_to_uuidv7.php deleted file mode 100644 index 5d3b4594..00000000 --- a/database/migrations/2026_06_06_181953_migrate_orders_to_uuidv7.php +++ /dev/null @@ -1,119 +0,0 @@ -addTemporaryUuidColumn('orders'); - $this->generateOrderUuids(); - - $this->makeUuidColumnRequired('orders'); - - $orderFkTables = ['order_lines', 'timeslots']; - $this->updateForeignKeysForTables($orderFkTables, 'orders', 'order_id'); - - $this->swapIdColumn('orders'); - - $this->recreateForeignKeys($orderFkTables, 'order_id', 'id', 'orders'); - - Schema::enableForeignKeyConstraints(); - } - - /** - * @throws \RuntimeException - */ - public function down(): void - { - throw new \RuntimeException( - 'This migration is irreversible: the transformation of orders from integer IDs to UUIDv7 cannot be rolled back.' - ); - } - - private function dropForeignKeysForColumn(string $tableName, string $columnName): void - { - $fks = Schema::getForeignKeys($tableName); - foreach ($fks as $fk) { - if (in_array($columnName, $fk['columns'])) { - Schema::table($tableName, function (Blueprint $table) use ($fk) { - $table->dropForeign($fk['name']); - }); - } - } - } - - private function recreateForeignKeys(array $tables, string $columnName, string $references, string $onTable): void - { - foreach ($tables as $tableName) { - Schema::table($tableName, function (Blueprint $table) use ($columnName, $references, $onTable) { - $table->foreign($columnName)->references($references)->on($onTable)->cascadeOnDelete(); - }); - } - } - - private function addTemporaryUuidColumn(string $tableName): void - { - Schema::table($tableName, function (Blueprint $table) { - $table->uuid('uuid')->nullable()->after('id'); - }); - } - - private function makeUuidColumnRequired(string $tableName): void - { - Schema::table($tableName, function (Blueprint $table) { - $table->uuid('uuid')->nullable(false)->change(); - }); - } - - private function generateOrderUuids(): void - { - $orders = DB::table('orders')->get(['id', 'created_at']); - - foreach ($orders as $order) { - $createdAt = $order->created_at ? Carbon::parse($order->created_at) : now(); - $uuid = UuidV7::generate($createdAt->toDateTimeImmutable()); - DB::table('orders')->where('id', $order->id)->update(['uuid' => $uuid]); - } - } - - private function updateForeignKeysForTables(array $tables, string $parentTable, string $columnName): void - { - $newColumn = 'new_' . $columnName; - foreach ($tables as $tableName) { - Schema::table($tableName, function (Blueprint $table) use ($newColumn, $columnName) { - $table->uuid($newColumn)->nullable()->after($columnName); - }); - - DB::table($tableName) - ->join($parentTable, "{$tableName}.{$columnName}", '=', "{$parentTable}.id") - ->update(["{$tableName}.{$newColumn}" => DB::raw("{$parentTable}.uuid")]); - - $this->dropForeignKeysForColumn($tableName, $columnName); - - Schema::table($tableName, function (Blueprint $table) use ($newColumn, $columnName) { - $table->dropColumn($columnName); - $table->renameColumn($newColumn, $columnName); - $table->uuid($columnName)->nullable(false)->change(); - }); - } - } - - private function swapIdColumn(string $tableName): void - { - Schema::table($tableName, function (Blueprint $table) { - $table->dropColumn(['id', 'reference', 'created_at']); - $table->renameColumn('uuid', 'id'); - $table->primary('id'); - }); - } -}; diff --git a/database/migrations/2026_06_07_072414_migrate_customers_to_uuidv7.php b/database/migrations/2026_06_07_072414_migrate_customers_to_uuidv7.php deleted file mode 100644 index afd3ce7c..00000000 --- a/database/migrations/2026_06_07_072414_migrate_customers_to_uuidv7.php +++ /dev/null @@ -1,130 +0,0 @@ -addTemporaryUuidColumn('customers'); - $this->generateCustomerUuids(); - - $this->makeUuidColumnRequired('customers'); - - $customerFkTables = ['employees']; - $this->updateForeignKeysForTables($customerFkTables, 'customers', 'customer_id'); - - $this->changeHashcodeColumnToUuid('customers'); - $this->swapIdColumn('customers'); - - $this->recreateForeignKeys($customerFkTables, 'customer_id', 'id', 'customers'); - - Schema::enableForeignKeyConstraints(); - } - - /** - * @throws \RuntimeException - */ - public function down(): void - { - throw new \RuntimeException( - 'This migration is irreversible: the transformation of customers from integer IDs to UUIDv7 cannot be rolled back.' - ); - } - - private function dropForeignKeysForColumn(string $tableName, string $columnName): void - { - $fks = Schema::getForeignKeys($tableName); - foreach ($fks as $fk) { - if (in_array($columnName, $fk['columns'])) { - Schema::table($tableName, function (Blueprint $table) use ($fk) { - $table->dropForeign($fk['name']); - }); - } - } - } - - private function recreateForeignKeys(array $tables, string $columnName, string $references, string $onTable): void - { - foreach ($tables as $tableName) { - Schema::table($tableName, function (Blueprint $table) use ($columnName, $references, $onTable) { - // Assuming cascadeOnUpdate()->nullOnDelete() based on earlier migrations, - // or just cascadeOnDelete() if that's what we want. - // Looking at old table for employees it was cascadeOnUpdate()->nullOnDelete(). - $table->foreign($columnName)->references($references)->on($onTable)->cascadeOnUpdate()->nullOnDelete(); - }); - } - } - - private function addTemporaryUuidColumn(string $tableName): void - { - Schema::table($tableName, function (Blueprint $table) { - $table->uuid('uuid')->nullable()->after('id'); - }); - } - - private function makeUuidColumnRequired(string $tableName): void - { - Schema::table($tableName, function (Blueprint $table) { - $table->uuid('uuid')->nullable(false)->change(); - }); - } - - private function generateCustomerUuids(): void - { - $customers = DB::table('customers')->get(['id', 'created_at']); - - foreach ($customers as $customer) { - $createdAt = $customer->created_at ? Carbon::parse($customer->created_at) : now(); - $uuid = UuidV7::generate($createdAt->toDateTimeImmutable()); - DB::table('customers')->where('id', $customer->id)->update(['uuid' => $uuid]); - } - } - - private function updateForeignKeysForTables(array $tables, string $parentTable, string $columnName): void - { - $newColumn = 'new_' . $columnName; - foreach ($tables as $tableName) { - Schema::table($tableName, function (Blueprint $table) use ($newColumn, $columnName) { - $table->uuid($newColumn)->nullable()->after($columnName); - }); - - DB::table($tableName) - ->join($parentTable, "{$tableName}.{$columnName}", '=', "{$parentTable}.id") - ->update(["{$tableName}.{$newColumn}" => DB::raw("{$parentTable}.uuid")]); - - $this->dropForeignKeysForColumn($tableName, $columnName); - - Schema::table($tableName, function (Blueprint $table) use ($newColumn, $columnName) { - $table->dropColumn($columnName); - $table->renameColumn($newColumn, $columnName); - $table->uuid($columnName)->nullable()->change(); // customer_id in employees is nullable - }); - } - } - - private function changeHashcodeColumnToUuid(string $tableName): void - { - Schema::table($tableName, function (Blueprint $table) { - $table->uuid('hashcode')->nullable(false)->change(); - }); - } - - private function swapIdColumn(string $tableName): void - { - Schema::table($tableName, function (Blueprint $table) { - $table->dropColumn('id'); - $table->renameColumn('uuid', 'id'); - $table->primary('id'); - }); - } -}; diff --git a/database/migrations/2026_06_07_172027_drop_date_column_from_orders_table.php b/database/migrations/2026_06_07_172027_drop_date_column_from_orders_table.php deleted file mode 100644 index c22a5c45..00000000 --- a/database/migrations/2026_06_07_172027_drop_date_column_from_orders_table.php +++ /dev/null @@ -1,30 +0,0 @@ -dropColumn('date'); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('orders', function (Blueprint $table) { - $table->date('date')->nullable(); - }); - } -}; diff --git a/database/migrations/2026_06_07_175730_add_reference_to_orders_table.php b/database/migrations/2026_06_07_175730_add_reference_to_orders_table.php deleted file mode 100644 index 8ab76e1e..00000000 --- a/database/migrations/2026_06_07_175730_add_reference_to_orders_table.php +++ /dev/null @@ -1,46 +0,0 @@ -string('reference')->nullable()->after('id'); - }); - - DB::table('orders')->orderBy('id') - ->chunk(100, function ($orders) { - foreach ($orders as $order) { - $reference = UidUuid::fromString($order->id)->toBase58(); - DB::table('orders') - ->where('id', $order->id) - ->update(['reference' => $reference]); - } - }); - - Schema::table('orders', function (Blueprint $table) { - $table->string('reference')->nullable(false)->unique()->change(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('orders', function (Blueprint $table) { - $table->dropColumn('reference'); - }); - } -}; diff --git a/database/migrations/2026_06_07_180625_simplify_timeslot_into_orders.php b/database/migrations/2026_06_07_180625_simplify_timeslot_into_orders.php deleted file mode 100644 index eebfd609..00000000 --- a/database/migrations/2026_06_07_180625_simplify_timeslot_into_orders.php +++ /dev/null @@ -1,39 +0,0 @@ -foreignId('shop_id')->after('id')->nullable()->constrained('shops')->nullOnDelete(); - $table->date('pickup_day')->after('delivery_address')->nullable(); - }); - - DB::table('orders') - ->join('timeslots', 'orders.id', '=', 'timeslots.order_id') - ->update([ - 'orders.shop_id' => DB::raw('timeslots.shop_id'), - 'orders.pickup_day' => DB::raw('timeslots.day'), - ]); - - Schema::dropIfExists('timeslots'); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_06_07_193825_update_shop_employee_exception_table.php b/database/migrations/2026_06_07_193825_update_shop_employee_exception_table.php deleted file mode 100644 index 34666584..00000000 --- a/database/migrations/2026_06_07_193825_update_shop_employee_exception_table.php +++ /dev/null @@ -1,46 +0,0 @@ -string('matricule')->nullable(); - }); - - DB::statement(' - UPDATE shop_employee_exception - JOIN employees ON employees.id = shop_employee_exception.employee_id - SET shop_employee_exception.matricule = employees.matricule - '); - - Schema::table('shop_employee_exception', function (Blueprint $table) { - $table->dropForeign(['employee_id']); - $table->dropPrimary(); - $table->dropColumn('employee_id'); - - $table->string('matricule')->nullable(false)->change(); - $table->primary(['matricule', 'shop_id']); - $table->foreign('matricule')->references('matricule') - ->on('employees')->cascadeOnUpdate()->cascadeOnDelete(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_06_08_164207_add_employee_matricule_virtual_index_to_orders_table.php b/database/migrations/2026_06_08_164207_add_employee_matricule_virtual_index_to_orders_table.php deleted file mode 100644 index 404e2f83..00000000 --- a/database/migrations/2026_06_08_164207_add_employee_matricule_virtual_index_to_orders_table.php +++ /dev/null @@ -1,30 +0,0 @@ -string('employee_matricule')->virtualAs("JSON_UNQUOTE(JSON_EXTRACT(employee, '$.matricule'))")->index(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('orders', function (Blueprint $table) { - $table->dropColumn('employee_matricule'); - }); - } -}; diff --git a/database/migrations/2026_06_10_221046_make_invoicing_and_sell_unit_not_nullable_on_products_table.php b/database/migrations/2026_06_10_221046_make_invoicing_and_sell_unit_not_nullable_on_products_table.php deleted file mode 100644 index e73043c5..00000000 --- a/database/migrations/2026_06_10_221046_make_invoicing_and_sell_unit_not_nullable_on_products_table.php +++ /dev/null @@ -1,32 +0,0 @@ -string('invoicing_unit')->nullable(false)->change(); - $table->string('sell_unit')->nullable(false)->change(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('products', function (Blueprint $table) { - $table->string('invoicing_unit')->nullable()->change(); - $table->string('sell_unit')->nullable()->change(); - }); - } -}; diff --git a/database/migrations/2026_06_11_091414_move_invalid_orders_and_make_employee_non_nullable.php b/database/migrations/2026_06_11_091414_move_invalid_orders_and_make_employee_non_nullable.php deleted file mode 100644 index 85e347a7..00000000 --- a/database/migrations/2026_06_11_091414_move_invalid_orders_and_make_employee_non_nullable.php +++ /dev/null @@ -1,56 +0,0 @@ -uuid('id')->primary(); - $table->unsignedBigInteger('shop_id')->nullable(); - $table->string('reference')->unique(); - $table->json('employee')->nullable()->comment('Domain\ValueObjects\OrderEmployee'); - $table->json('delivery_address'); - $table->date('pickup_day')->nullable(); - $table->unsignedInteger('total'); - $table->unsignedBigInteger('status'); - $table->timestamp('updated_at')->nullable(); - $table->string('employee_matricule')->virtualAs("JSON_UNQUOTE(JSON_EXTRACT(employee, '$.matricule'))")->index(); - }); - - $invalidOrders = DB::table('orders')->whereNull('employee')->get(); - $insertData = collect($invalidOrders)->map(function ($order) { - $data = (array) $order; - unset($data['employee_matricule']); - - return $data; - })->toArray(); - - if (! empty($insertData)) { - DB::table('invalid_orders')->insert($insertData); - } - - DB::table('orders')->whereNull('employee')->delete(); - - Schema::table('orders', function (Blueprint $table) { - $table->json('employee')->nullable(false)->change(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_06_11_104029_add_last_login_at_to_customers_table.php b/database/migrations/2026_06_11_104029_add_last_login_at_to_customers_table.php deleted file mode 100644 index 2134910e..00000000 --- a/database/migrations/2026_06_11_104029_add_last_login_at_to_customers_table.php +++ /dev/null @@ -1,30 +0,0 @@ -timestamp('last_login_at')->nullable(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('customers', function (Blueprint $table) { - $table->dropColumn('last_login_at'); - }); - } -}; diff --git a/database/migrations/2026_06_11_160000_migrate_weights_to_grams.php b/database/migrations/2026_06_11_160000_migrate_weights_to_grams.php deleted file mode 100644 index 6339d447..00000000 --- a/database/migrations/2026_06_11_160000_migrate_weights_to_grams.php +++ /dev/null @@ -1,80 +0,0 @@ - - */ - private const UNIT_TO_GRAMS = [ - 'G' => 1, - 'KG' => 1000, - 'T' => 1_000_000, - ]; - - public function up(): void - { - $this->migrateOrderLineWeights(); - $this->migrateProductWeights(); - - Schema::table('products', function (Blueprint $table) { - $table->unsignedInteger('weight')->nullable()->default(null)->change(); - $table->dropColumn('weight_unit'); - }); - } - - private function migrateProductWeights(): void - { - DB::table('products') - ->where('weight_unit', 'KG') - ->update(['weight' => DB::raw('weight * 1000')]); - - DB::table('products') - ->where('weight_unit', 'T') - ->update(['weight' => DB::raw('weight * 1000000')]); - } - - private function migrateOrderLineWeights(): void - { - DB::table('order_lines') - ->whereNotNull('product') - ->orderBy('id') - ->chunk(500, function ($lines): void { - foreach ($lines as $line) { - $data = json_decode($line->product, true); - - if (! is_array($data) || ! isset($data['weight'])) { - continue; - } - - $unit = strtoupper((string) ($data['weight_unit'] ?? 'G')); - $factor = self::UNIT_TO_GRAMS[$unit] ?? 1; - - // * Convert to grams - $data['weight'] = (int) round((float) $data['weight'] * $factor); - - // * Remove weight_unit - unset($data['weight_unit']); - - DB::table('order_lines') - ->where('id', $line->id) - ->update([ - 'product' => json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), - ]); - } - }); - } - - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_06_12_120149_convert_weight_variable_to_boolean_in_order_lines_product.php b/database/migrations/2026_06_12_120149_convert_weight_variable_to_boolean_in_order_lines_product.php deleted file mode 100644 index dd0ff80b..00000000 --- a/database/migrations/2026_06_12_120149_convert_weight_variable_to_boolean_in_order_lines_product.php +++ /dev/null @@ -1,41 +0,0 @@ -orderBy('id')->chunk(500, function ($lines) { - foreach ($lines as $line) { - if (! is_string($line->product)) { - continue; - } - - $product = json_decode($line->product, true); - - if (isset($product['weight_variable']) && is_int($product['weight_variable'])) { - $product['weight_variable'] = (bool) $product['weight_variable']; - - DB::table('order_lines') - ->where('id', $line->id) - ->update(['product' => json_encode($product, \JSON_UNESCAPED_SLASHES)]); - } - } - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_06_12_122322_populate_null_discounted_price_in_order_lines_product.php b/database/migrations/2026_06_12_122322_populate_null_discounted_price_in_order_lines_product.php deleted file mode 100644 index 51190c04..00000000 --- a/database/migrations/2026_06_12_122322_populate_null_discounted_price_in_order_lines_product.php +++ /dev/null @@ -1,48 +0,0 @@ -orderBy('id')->chunk(500, function ($lines) { - foreach ($lines as $line) { - if (! is_string($line->product)) { - continue; - } - - $product = json_decode($line->product, true); - $updated = false; - - // If discounted_price is null or missing, set it to price - if (! isset($product['discounted_price']) || $product['discounted_price'] === null || $product['discounted_price'] === '') { - if (isset($product['price'])) { - $product['discounted_price'] = $product['price']; - $updated = true; - } - } - - if ($updated) { - DB::table('order_lines') - ->where('id', $line->id) - ->update(['product' => json_encode($product, \JSON_UNESCAPED_SLASHES)]); - } - } - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_06_13_151618_migrate_shops_and_pickup_exceptions_to_uuidv7.php b/database/migrations/2026_06_13_151618_migrate_shops_and_pickup_exceptions_to_uuidv7.php deleted file mode 100644 index 87e77644..00000000 --- a/database/migrations/2026_06_13_151618_migrate_shops_and_pickup_exceptions_to_uuidv7.php +++ /dev/null @@ -1,183 +0,0 @@ -addTemporaryUuidColumn('shops'); - $this->generateUuidsForTable('shops'); - $this->makeUuidColumnRequired('shops'); - - $shopFkTables = [ - 'orders' => ['onDelete' => 'set null', 'nullable' => true], - 'shop_employee_exception' => ['onDelete' => 'cascade', 'nullable' => false], - 'shop_employees' => ['onDelete' => 'cascade', 'nullable' => false], - 'shop_pickup_exception' => ['onDelete' => 'cascade', 'nullable' => false], - ]; - $this->updateForeignKeysForTables($shopFkTables, 'shops', 'shop_id'); - $this->recreatePrimaryAndUniqueKeys($shopFkTables, 'shop_id'); - $this->swapIdColumn('shops'); - $this->recreateForeignKeys($shopFkTables, 'shop_id', 'id', 'shops'); - - // * Process Pickup Exceptions - $this->addTemporaryUuidColumn('pickup_exceptions'); - $this->generateUuidsForTable('pickup_exceptions'); - $this->makeUuidColumnRequired('pickup_exceptions'); - - $pickupExceptionFkTables = [ - 'shop_pickup_exception' => ['onDelete' => 'cascade', 'nullable' => false], - ]; - $this->updateForeignKeysForTables($pickupExceptionFkTables, 'pickup_exceptions', 'pickup_exception_id'); - $this->recreatePrimaryAndUniqueKeys($pickupExceptionFkTables, 'pickup_exception_id'); - $this->swapIdColumn('pickup_exceptions'); - $this->recreateForeignKeys($pickupExceptionFkTables, 'pickup_exception_id', 'id', 'pickup_exceptions'); - - Schema::enableForeignKeyConstraints(); - } - - /** - * @throws \RuntimeException - */ - public function down(): void - { - throw new \RuntimeException( - 'This migration is irreversible: the transformation of shops and pickup exceptions from integer IDs to UUIDv7 cannot be rolled back.' - ); - } - - private function dropForeignKeysForColumn(string $tableName, string $columnName): void - { - $database = DB::getDatabaseName(); - - $foreignKeys = DB::table('information_schema.KEY_COLUMN_USAGE') - ->select('CONSTRAINT_NAME') - ->where('TABLE_SCHEMA', $database) - ->where('TABLE_NAME', $tableName) - ->where('COLUMN_NAME', $columnName) - ->whereNotNull('REFERENCED_TABLE_NAME') - ->distinct() - ->pluck('CONSTRAINT_NAME'); - - foreach ($foreignKeys as $foreignKeyName) { - DB::statement(sprintf( - 'ALTER TABLE `%s` DROP FOREIGN KEY `%s`', - $tableName, - $foreignKeyName - )); - } - } - - private function recreateForeignKeys(array $tables, string $columnName, string $references, string $onTable): void - { - foreach ($tables as $tableName => $options) { - Schema::table($tableName, function (Blueprint $table) use ($columnName, $references, $onTable, $options) { - $fk = $table->foreign($columnName)->references($references)->on($onTable)->onUpdate('cascade'); - if ($options['onDelete'] === 'cascade') { - $fk->cascadeOnDelete(); - } elseif ($options['onDelete'] === 'set null') { - $fk->nullOnDelete(); - } - }); - } - } - - private function addTemporaryUuidColumn(string $tableName): void - { - Schema::table($tableName, function (Blueprint $table) { - $table->uuid('uuid')->nullable()->after('id'); - }); - } - - private function makeUuidColumnRequired(string $tableName): void - { - Schema::table($tableName, function (Blueprint $table) { - $table->uuid('uuid')->nullable(false)->change(); - }); - } - - private function generateUuidsForTable(string $tableName): void - { - $records = DB::table($tableName)->get(['id', 'created_at']); - - foreach ($records as $record) { - $createdAt = $record->created_at ? Carbon::parse($record->created_at) : now(); - $uuid = UuidV7::generate($createdAt->toDateTimeImmutable()); - DB::table($tableName)->where('id', $record->id)->update(['uuid' => $uuid]); - } - } - - private function updateForeignKeysForTables(array $tables, string $parentTable, string $columnName): void - { - $newColumn = 'new_' . $columnName; - foreach ($tables as $tableName => $options) { - Schema::table($tableName, function (Blueprint $table) use ($newColumn, $columnName) { - $table->uuid($newColumn)->nullable()->after($columnName); - }); - - DB::table($tableName) - ->join($parentTable, "{$tableName}.{$columnName}", '=', "{$parentTable}.id") - ->update(["{$tableName}.{$newColumn}" => DB::raw("{$parentTable}.uuid")]); - - $this->dropForeignKeysForColumn($tableName, $columnName); - if ($tableName === 'shop_employee_exception') { - $this->dropForeignKeysForColumn($tableName, 'matricule'); - } - - Schema::table($tableName, function (Blueprint $table) use ($newColumn, $columnName, $tableName) { - if ($tableName === 'shop_employee_exception') { - $table->dropPrimary(['matricule', 'shop_id']); - } - if ($tableName === 'shop_pickup_exception' && $columnName === 'shop_id') { - $table->dropUnique(['shop_id', 'pickup_exception_id']); - } - - $table->dropColumn($columnName); - $table->renameColumn($newColumn, $columnName); - }); - - Schema::table($tableName, function (Blueprint $table) use ($columnName, $options) { - if ($options['nullable']) { - $table->uuid($columnName)->nullable()->change(); - } else { - $table->uuid($columnName)->nullable(false)->change(); - } - }); - } - } - - private function recreatePrimaryAndUniqueKeys(array $tables, string $columnName): void - { - foreach ($tables as $tableName => $options) { - Schema::table($tableName, function (Blueprint $table) use ($tableName, $columnName) { - if ($tableName === 'shop_employee_exception') { - $table->primary(['matricule', 'shop_id']); - $table->foreign('matricule')->references('matricule')->on('employees')->cascadeOnDelete()->cascadeOnUpdate(); - } - if ($tableName === 'shop_pickup_exception' && $columnName === 'pickup_exception_id') { - $table->unique(['shop_id', 'pickup_exception_id']); - } - }); - } - } - - private function swapIdColumn(string $tableName): void - { - Schema::table($tableName, function (Blueprint $table) { - $table->dropColumn('id'); - $table->renameColumn('uuid', 'id'); - $table->primary('id'); - }); - } -}; diff --git a/database/migrations/2026_10_01_123336_add_last_sync_to_employees.php b/database/migrations/2026_10_01_123336_add_last_sync_to_employees.php deleted file mode 100644 index 42c48d8e..00000000 --- a/database/migrations/2026_10_01_123336_add_last_sync_to_employees.php +++ /dev/null @@ -1,30 +0,0 @@ -timestamp('last_sync')->after('code')->nullable(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::table('employees', function (Blueprint $table) { - $table->dropColumn('last_sync'); - }); - } -}; diff --git a/database/migrations/2026_10_01_150950_fix_employee_service_code.php b/database/migrations/2026_10_01_150950_fix_employee_service_code.php deleted file mode 100644 index d7e3f3ef..00000000 --- a/database/migrations/2026_10_01_150950_fix_employee_service_code.php +++ /dev/null @@ -1,38 +0,0 @@ -orderBy('id') - ->chunk(100, function ($employees) { - foreach ($employees as $employee) { - DB::table('employees') - ->where('id', $employee->id) - ->update([ - 'service' => Str::of($employee->service) - ->replaceFirst($employee->site, '') - ->replaceMatches('/[^\d]/', ''), - ]); - } - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_10_01_163000_create_settings_table.php b/database/migrations/2026_10_01_163000_create_settings_table.php deleted file mode 100644 index d492bfe4..00000000 --- a/database/migrations/2026_10_01_163000_create_settings_table.php +++ /dev/null @@ -1,38 +0,0 @@ -id(); - $table->json('employee_sites')->nullable(); - $table->timestamps(); - }); - - DB::table('settings')->insert([ - 'id' => 1, - 'employee_sites' => json_encode([]), - 'created_at' => now(), - 'updated_at' => now(), - ]); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - Schema::dropIfExists('settings'); - } -}; diff --git a/database/migrations/2026_10_02_130500_fix_ambiguous_employee_codes.php b/database/migrations/2026_10_02_130500_fix_ambiguous_employee_codes.php deleted file mode 100644 index 165b5719..00000000 --- a/database/migrations/2026_10_02_130500_fix_ambiguous_employee_codes.php +++ /dev/null @@ -1,41 +0,0 @@ -where('matricule', '0117621') - ->where('code', 'gd363CYO') - ->update(['code' => 'gd363CYQ']); - - DB::table('employees') - ->where('matricule', '0117628') - ->where('code', 'diHNo574') - ->update(['code' => 'djHNa574']); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - DB::table('employees') - ->where('matricule', '0117621') - ->where('code', 'gd363CYQ') - ->update(['code' => 'gd363CYO']); - - DB::table('employees') - ->where('matricule', '0117628') - ->where('code', 'djHNa574') - ->update(['code' => 'diHNo574']); - } -}; diff --git a/database/migrations/2026_10_02_143800_fix_orders_employee_column.php b/database/migrations/2026_10_02_143800_fix_orders_employee_column.php deleted file mode 100644 index 71ea7c97..00000000 --- a/database/migrations/2026_10_02_143800_fix_orders_employee_column.php +++ /dev/null @@ -1,68 +0,0 @@ -whereNotNull('employee') - ->orderBy('id') - ->chunk(500, function ($orders): void { - foreach ($orders as $order) { - $data = json_decode((string) $order->employee, true); - if (! is_array($data)) { - continue; - } - - $site = $data['site'] ?? ''; - $site = match ($site) { - 'LDC SERVICES' => 'LDCSER', - 'LDC VOLAILLES' => 'LDCVOL', - 'LDC TER' => 'LDCTER', - default => $site, - }; - $data['site'] = $site; - - $service = $data['service'] ?? ''; - $data['service'] = (string) Str::of((string) $service) - ->replaceFirst((string) $site, '') - ->replaceMatches('/[^\d]/', ''); - - DB::table('orders') - ->where('id', $order->id) - ->update([ - 'employee' => json_encode($data, JSON_THROW_ON_ERROR), - ]); - } - }); - - DB::table('employees') - ->where('site', 'LDC SERVICES') - ->update(['site' => 'LDCSER']); - - DB::table('employees') - ->where('site', 'LDC VOLAILLES') - ->update(['site' => 'LDCVOL']); - - DB::table('employees') - ->where('site', 'LDC TER') - ->update(['site' => 'LDCTER']); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - throw new \Error('WONT ROLLBACK'); - } -}; diff --git a/database/migrations/2026_10_02_222500_drop_xml_incos_table.php b/database/migrations/2026_10_02_222500_drop_xml_incos_table.php deleted file mode 100644 index d4374b8e..00000000 --- a/database/migrations/2026_10_02_222500_drop_xml_incos_table.php +++ /dev/null @@ -1,25 +0,0 @@ -select('id') - ->orderBy('order', 'asc') - ->orderBy('id', 'asc') - ->cursor() - ->each(function ($product) use (&$index) { - DB::table('products') - ->where('id', $product->id) - ->update(['order' => $index++]); - }); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // DO nothing - } -} diff --git a/database/migrations/2026_11_02_111000_fix_inco_id_in_order_lines_product.php b/database/migrations/2026_11_02_111000_fix_inco_id_in_order_lines_product.php deleted file mode 100644 index e339d605..00000000 --- a/database/migrations/2026_11_02_111000_fix_inco_id_in_order_lines_product.php +++ /dev/null @@ -1,57 +0,0 @@ -pluck('no_art', 'product_id') - ->all(); - - DB::table('order_lines') - ->whereNotNull('product') - ->orderBy('id') - ->chunk(500, function ($lines) use ($incoMap): void { - foreach ($lines as $line) { - $data = json_decode((string) $line->product, true); - if (! is_array($data) || ! isset($data['original_id'])) { - continue; - } - - $productId = (string) $data['original_id']; - if (! isset($incoMap[$productId])) { - continue; - } - - $expectedNoArt = (int) $incoMap[$productId]; - $currentIncoId = isset($data['inco_id']) ? (int) $data['inco_id'] : null; - - if ($currentIncoId !== $expectedNoArt) { - $data['inco_id'] = $expectedNoArt; - - DB::table('order_lines') - ->where('id', $line->id) - ->update([ - 'product' => json_encode($data, \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES), - ]); - } - } - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - { - // Data repair migration, no rollback. - } -}; diff --git a/database/schema/mysql-schema.sql b/database/schema/mysql-schema.sql new file mode 100644 index 00000000..c5718374 --- /dev/null +++ b/database/schema/mysql-schema.sql @@ -0,0 +1,703 @@ +/*M!999999\- enable the sandbox mode */ +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; +DROP TABLE IF EXISTS `customer_password_resets`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `customer_password_resets` ( + `email` varchar(255) NOT NULL, + `token` varchar(255) NOT NULL, + `created_at` timestamp NULL DEFAULT NULL, + UNIQUE KEY `password_resets_email_unique` (`email`), + KEY `password_resets_email_index` (`email`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `customers`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `customers` ( + `id` char(36) NOT NULL, + `email` varchar(255) NOT NULL, + `hashcode` char(36) NOT NULL, + `remember_token` varchar(100) DEFAULT NULL, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + `last_login_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `customers_email_unique` (`email`), + UNIQUE KEY `customers_hashcode_unique` (`hashcode`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `discounts`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `discounts` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `type` bigint(20) unsigned NOT NULL DEFAULT 1, + `value` int(10) unsigned NOT NULL, + `is_old_price_displayed` tinyint(1) NOT NULL COMMENT 'Should the old price be displayed ?', + `date_start` timestamp NULL DEFAULT NULL, + `date_end` timestamp NULL DEFAULT NULL, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `promotions_discount_type_id_foreign` (`type`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `employees`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `employees` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `customer_id` char(36) DEFAULT NULL, + `matricule` varchar(255) NOT NULL, + `nom` varchar(255) NOT NULL, + `prenom` varchar(255) NOT NULL, + `start_date` date DEFAULT NULL, + `end_date` date DEFAULT NULL, + `etablissement` varchar(255) NOT NULL, + `site` varchar(255) NOT NULL, + `service` varchar(255) NOT NULL, + `code` varchar(10) NOT NULL, + `last_sync` timestamp NULL DEFAULT NULL, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `salaries_code_unique` (`code`), + UNIQUE KEY `employees_matricule_unique` (`matricule`), + KEY `employees_customer_id_foreign` (`customer_id`), + CONSTRAINT `employees_customer_id_foreign` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `failed_jobs`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `failed_jobs` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `uuid` varchar(255) NOT NULL, + `connection` text NOT NULL, + `queue` text NOT NULL, + `payload` longtext NOT NULL, + `exception` longtext NOT NULL, + `failed_at` timestamp NOT NULL DEFAULT current_timestamp(), + PRIMARY KEY (`id`), + UNIQUE KEY `failed_jobs_uuid_unique` (`uuid`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `faqs`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `faqs` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `question` varchar(255) NOT NULL, + `answer` text NOT NULL, + `order` int(10) unsigned NOT NULL, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `faqs_order_unique` (`order`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `invalid_orders`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `invalid_orders` ( + `id` char(36) NOT NULL, + `shop_id` bigint(20) unsigned DEFAULT NULL, + `reference` varchar(255) NOT NULL, + `employee` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Domain\\ValueObjects\\OrderEmployee' CHECK (json_valid(`employee`)), + `delivery_address` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL CHECK (json_valid(`delivery_address`)), + `pickup_day` date DEFAULT NULL, + `total` int(10) unsigned NOT NULL, + `status` bigint(20) unsigned NOT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + `employee_matricule` varchar(255) GENERATED ALWAYS AS (json_unquote(json_extract(`employee`,'$.matricule'))) VIRTUAL, + PRIMARY KEY (`id`), + UNIQUE KEY `invalid_orders_reference_unique` (`reference`), + KEY `invalid_orders_employee_matricule_index` (`employee_matricule`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `jobs`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `jobs` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `queue` varchar(255) NOT NULL, + `payload` longtext NOT NULL, + `attempts` tinyint(3) unsigned NOT NULL, + `reserved_at` int(10) unsigned DEFAULT NULL, + `available_at` int(10) unsigned NOT NULL, + `created_at` int(10) unsigned NOT NULL, + PRIMARY KEY (`id`), + KEY `jobs_queue_index` (`queue`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `migrations`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `migrations` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `migration` varchar(255) NOT NULL, + `batch` int(11) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `order_lines`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `order_lines` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `order_id` char(36) NOT NULL, + `product` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT 'Domain\\Models\\ValueObjects\\OrderLineProduct' CHECK (json_valid(`product`)), + `quantity` int(10) unsigned NOT NULL DEFAULT 1, + `unit_price` int(10) unsigned NOT NULL, + `unit_tax` int(10) unsigned NOT NULL, + `unit_discount` int(10) unsigned NOT NULL, + `tax_rate` smallint(5) unsigned NOT NULL, + `total_ttc` int(10) unsigned NOT NULL, + `total_ht` int(10) unsigned NOT NULL, + `total_tax` int(10) unsigned NOT NULL, + `total_discount` int(10) unsigned NOT NULL, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `order_lines_order_id_foreign` (`order_id`), + CONSTRAINT `order_lines_order_id_foreign` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `orders`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `orders` ( + `id` char(36) NOT NULL, + `shop_id` char(36) DEFAULT NULL, + `reference` varchar(255) NOT NULL, + `employee` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL CHECK (json_valid(`employee`)), + `delivery_address` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL CHECK (json_valid(`delivery_address`)), + `pickup_day` date DEFAULT NULL, + `total` int(10) unsigned NOT NULL, + `status` bigint(20) unsigned NOT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + `employee_matricule` varchar(255) GENERATED ALWAYS AS (json_unquote(json_extract(`employee`,'$.matricule'))) VIRTUAL, + PRIMARY KEY (`id`), + UNIQUE KEY `orders_reference_unique` (`reference`), + KEY `orders_status_id_foreign` (`status`), + KEY `orders_employee_matricule_index` (`employee_matricule`), + KEY `orders_shop_id_foreign` (`shop_id`), + CONSTRAINT `orders_shop_id_foreign` FOREIGN KEY (`shop_id`) REFERENCES `shops` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `pages`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `pages` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `slug` varchar(255) NOT NULL, + `seo_title` varchar(255) NOT NULL, + `seo_description` varchar(255) NOT NULL, + `title` varchar(255) DEFAULT NULL, + `content` text NOT NULL, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `pages_slug_unique` (`slug`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `pickup_exceptions`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `pickup_exceptions` ( + `id` char(36) NOT NULL, + `date` date NOT NULL, + `label` varchar(255) NOT NULL, + `repeatable` tinyint(1) NOT NULL, + `repeat_frequency` varchar(255) NOT NULL DEFAULT 'Weekly' COMMENT 'Enum Domain\\Enums\\RepeatFrequency', + `auto_updated` tinyint(1) NOT NULL, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `pickup_exceptions_date_label_unique` (`date`,`label`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `product_incos`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `product_incos` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `product_id` char(36) NOT NULL, + `no_art` int(10) unsigned NOT NULL, + `ingredients` text DEFAULT NULL, + `preparation` text DEFAULT NULL, + `servings` varchar(20) DEFAULT NULL, + `allergens` text DEFAULT NULL, + `selling_argument` text DEFAULT NULL, + `nv_ref_weight_g` double unsigned DEFAULT NULL, + `nv_kj` double unsigned DEFAULT NULL, + `nv_kcal` double unsigned DEFAULT NULL, + `nv_fat_g` double unsigned DEFAULT NULL, + `nv_sat_fat_g` double unsigned DEFAULT NULL, + `nv_carb_g` double unsigned DEFAULT NULL, + `nv_sugar_g` double unsigned DEFAULT NULL, + `nv_fiber_g` double unsigned DEFAULT NULL, + `nv_protein_g` double unsigned DEFAULT NULL, + `nv_salt_g` double unsigned DEFAULT NULL, + `nv_serving_size_g` double unsigned DEFAULT NULL, + `nv_serving_kj` double unsigned DEFAULT NULL, + `nv_serving_kcal` double unsigned DEFAULT NULL, + `nv_serving_fat_g` double unsigned DEFAULT NULL, + `nv_serving_sat_fat_g` double unsigned DEFAULT NULL, + `nv_serving_carb_g` double unsigned DEFAULT NULL, + `nv_serving_sugar_g` double unsigned DEFAULT NULL, + `nv_serving_fiber_g` double unsigned DEFAULT NULL, + `nv_serving_protein_g` double unsigned DEFAULT NULL, + `nv_serving_salt_g` double unsigned DEFAULT NULL, + `nv_daily_energy` double unsigned DEFAULT NULL, + `nv_daily_fat` double unsigned DEFAULT NULL, + `nv_daily_sat_fat` double unsigned DEFAULT NULL, + `nv_daily_carb` double unsigned DEFAULT NULL, + `nv_daily_sugar` double unsigned DEFAULT NULL, + `nv_daily_fiber` double unsigned DEFAULT NULL, + `nv_daily_protein` double unsigned DEFAULT NULL, + `nv_daily_salt` double unsigned DEFAULT NULL, + `nutriscore` varchar(255) DEFAULT NULL, + `nutriscore_args` text DEFAULT NULL, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `product_incos_no_art_unique` (`no_art`), + KEY `product_incos_product_id_foreign` (`product_id`), + CONSTRAINT `product_incos_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `product_product`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `product_product` ( + `product_id` char(36) NOT NULL, + `associated_id` char(36) NOT NULL, + `sort_order` int(11) NOT NULL DEFAULT 0, + KEY `product_product_product_id_foreign` (`product_id`), + KEY `product_product_associated_id_foreign` (`associated_id`), + CONSTRAINT `product_product_associated_id_foreign` FOREIGN KEY (`associated_id`) REFERENCES `products` (`id`) ON DELETE CASCADE, + CONSTRAINT `product_product_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `product_tag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `product_tag` ( + `product_id` char(36) NOT NULL, + `tag_id` bigint(20) unsigned NOT NULL, + KEY `product_tag_tag_id_foreign` (`tag_id`), + KEY `product_tag_product_id_foreign` (`product_id`), + CONSTRAINT `product_tag_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE, + CONSTRAINT `product_tag_tag_id_foreign` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `products`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `products` ( + `id` char(36) NOT NULL, + `name` varchar(255) NOT NULL, + `brand` varchar(255) NOT NULL, + `description` text NOT NULL, + `short_description` text DEFAULT NULL, + `picture` varchar(255) DEFAULT NULL, + `picture_alt` varchar(255) NOT NULL, + `picture_title` varchar(255) NOT NULL, + `picture_large` varchar(255) DEFAULT NULL, + `picture_large_alt` varchar(255) NOT NULL, + `picture_large_title` varchar(255) NOT NULL, + `price` int(11) NOT NULL, + `invoicing_unit` varchar(255) NOT NULL, + `tax_rate` tinyint(3) unsigned NOT NULL DEFAULT 1, + `stock` int(11) NOT NULL DEFAULT 0, + `sell_unit` varchar(255) NOT NULL, + `order_unit` varchar(255) DEFAULT NULL, + `weight` int(10) unsigned DEFAULT NULL, + `weight_variable` tinyint(1) NOT NULL DEFAULT 0, + `slug` varchar(255) NOT NULL, + `star` tinyint(1) NOT NULL DEFAULT 0, + `status` tinyint(1) NOT NULL, + `orderable_start` timestamp NULL DEFAULT NULL, + `orderable_end` timestamp NULL DEFAULT NULL, + `range_id` bigint(20) unsigned NOT NULL, + `discount_id` bigint(20) unsigned DEFAULT NULL, + `order` bigint(20) unsigned NOT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + `deleted_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `products_order_unique` (`order`), + KEY `products_range_id_foreign` (`range_id`), + KEY `products_tax_rate_id_foreign` (`tax_rate`), + KEY `products_discount_id_foreign` (`discount_id`), + CONSTRAINT `products_discount_id_foreign` FOREIGN KEY (`discount_id`) REFERENCES `discounts` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `products_range_id_foreign` FOREIGN KEY (`range_id`) REFERENCES `ranges` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `ranges`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `ranges` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL, + `slug` varchar(255) NOT NULL, + `description` text DEFAULT NULL, + `picture` varchar(255) DEFAULT NULL, + `picture_alt` varchar(255) NOT NULL, + `picture_title` varchar(255) NOT NULL, + `status` tinyint(1) NOT NULL DEFAULT 0, + `order` int(10) unsigned NOT NULL, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `ranges_order_unique` (`order`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `settings`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `settings` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `employee_sites` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`employee_sites`)), + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +INSERT IGNORE INTO `settings` (`id`, `employee_sites`, `created_at`, `updated_at`) VALUES (1, '[]', NOW(), NOW()); +DROP TABLE IF EXISTS `shop_employee_exception`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `shop_employee_exception` ( + `shop_id` char(36) NOT NULL, + `matricule` varchar(255) NOT NULL, + PRIMARY KEY (`matricule`,`shop_id`), + KEY `shop_employee_exception_shop_id_foreign` (`shop_id`), + CONSTRAINT `shop_employee_exception_matricule_foreign` FOREIGN KEY (`matricule`) REFERENCES `employees` (`matricule`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `shop_employee_exception_shop_id_foreign` FOREIGN KEY (`shop_id`) REFERENCES `shops` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Exceptions pour certains salariés afin de pallier au manque de cohérence coté régate'; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `shop_employees`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `shop_employees` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `site_code` varchar(255) NOT NULL, + `service_code` varchar(255) DEFAULT NULL, + `shop_id` char(36) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `magasin_salarie_site_code_service_code_unique` (`site_code`,`service_code`), + KEY `shop_employees_shop_id_foreign` (`shop_id`), + CONSTRAINT `shop_employees_shop_id_foreign` FOREIGN KEY (`shop_id`) REFERENCES `shops` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Permet de résoudre le magasin pour un salarie en fonction du site et éventuellement du service'; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `shop_pickup_exception`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `shop_pickup_exception` ( + `shop_id` char(36) NOT NULL, + `pickup_exception_id` char(36) NOT NULL, + `replacement_date` date DEFAULT NULL, + `order_deadline_at` datetime DEFAULT NULL, + UNIQUE KEY `shop_pickup_exception_shop_id_pickup_exception_id_unique` (`shop_id`,`pickup_exception_id`), + KEY `shop_pickup_exception_pickup_exception_id_foreign` (`pickup_exception_id`), + CONSTRAINT `shop_pickup_exception_pickup_exception_id_foreign` FOREIGN KEY (`pickup_exception_id`) REFERENCES `pickup_exceptions` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `shop_pickup_exception_shop_id_foreign` FOREIGN KEY (`shop_id`) REFERENCES `shops` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `shoppingcart`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `shoppingcart` ( + `identifier` varchar(255) NOT NULL, + `instance` varchar(255) NOT NULL, + `content` longtext NOT NULL, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`identifier`,`instance`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `shops`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `shops` ( + `id` char(36) NOT NULL, + `name` varchar(255) NOT NULL, + `address` varchar(255) NOT NULL, + `postcode` varchar(255) NOT NULL, + `city` varchar(255) NOT NULL, + `phone` varchar(255) DEFAULT NULL, + `latitude` varchar(255) DEFAULT NULL, + `longitude` varchar(255) DEFAULT NULL, + `default` tinyint(1) NOT NULL DEFAULT 0, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `slides`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `slides` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `title` varchar(255) NOT NULL, + `text` text DEFAULT NULL, + `picture` varchar(255) DEFAULT NULL, + `picture_alt` varchar(255) DEFAULT NULL, + `picture_title` varchar(255) DEFAULT NULL, + `link_label` varchar(255) DEFAULT NULL, + `link` varchar(255) DEFAULT NULL, + `link_new_tab` tinyint(1) NOT NULL DEFAULT 0, + `connected` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Slide visible only for connected customers.', + `order` int(10) unsigned NOT NULL, + `status` tinyint(1) NOT NULL, + `date_start` timestamp NULL DEFAULT NULL, + `date_end` timestamp NULL DEFAULT NULL, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `stats`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `stats` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `product_id` char(36) NOT NULL, + `date` date NOT NULL, + `margin` double NOT NULL DEFAULT 0, + `nb_sale` bigint(20) unsigned NOT NULL DEFAULT 0, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `stats_product_id_foreign` (`product_id`), + CONSTRAINT `stats_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `tags`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `tags` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `label` varchar(255) NOT NULL, + `slug` varchar(255) NOT NULL, + `order` int(10) unsigned NOT NULL, + `status` tinyint(1) NOT NULL DEFAULT 1, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `users`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `users` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `firstname` varchar(255) NOT NULL, + `lastname` varchar(255) NOT NULL, + `email` varchar(255) NOT NULL, + `email_verified_at` timestamp NULL DEFAULT NULL, + `password` varchar(255) NOT NULL, + `role` int(11) NOT NULL, + `remember_token` varchar(100) DEFAULT NULL, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `users_email_unique` (`email`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +DROP TABLE IF EXISTS `uwil_redirections`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `uwil_redirections` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `hash` varchar(255) NOT NULL COMMENT 'Hash of the redirection (from old_query).', + `old_model_slug` varchar(255) NOT NULL COMMENT 'Old slug of the model.', + `old_query` varchar(255) NOT NULL COMMENT 'Old URL.', + `new_query` varchar(255) NOT NULL COMMENT 'New URL to redirect.', + `model_redirectable_id` bigint(20) unsigned NOT NULL COMMENT 'Primary key of the model.', + `model_redirectable_type` varchar(255) NOT NULL COMMENT 'Class of the model.', + `redirect_type` tinyint(3) unsigned NOT NULL COMMENT 'Type of the redirection (enum RedirectionType).', + `redirect_code` smallint(5) unsigned NOT NULL COMMENT 'HTTP Code of the redirection (enum RedirectionCode).', + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `uwil_redirections_hash` (`hash`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +/*M!999999\- enable the sandbox mode */ +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (1,'2014_10_12_000000_create_users_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (2,'2014_10_12_100000_create_password_resets_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (3,'2018_12_23_120000_create_shoppingcart_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (4,'2019_08_19_000000_create_failed_jobs_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (5,'2020_11_04_132346_create_contents',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (6,'2020_11_04_132538_create_settings',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (7,'2020_11_04_133603_create_faqs',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (8,'2020_11_05_084122_create_ranges',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (9,'2020_11_05_084142_create_products',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (10,'2020_11_05_105239_create_old_slugs',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (11,'2020_11_09_113830_create_stats',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (12,'2020_11_09_125215_create_orders_status',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (13,'2020_11_09_125304_create_orders',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (14,'2020_11_09_161858_create_orders_products',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (15,'2021_02_04_175136_create_customers_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (16,'2021_02_04_180000_constrain_orders_to_customers',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (17,'2021_03_16_111337_add_fields_to_products',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (18,'2021_03_16_135155_create_food_products',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (19,'2021_03_16_140753_create_products_products',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (20,'2021_03_17_093244_add_fields_to_contents',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (21,'2021_03_27_163403_create_order_lines_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (22,'2021_03_29_114933_create_timeslots_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (23,'2021_04_06_153634_create_discount_types_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (24,'2021_04_06_154003_create_promotions_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (25,'2021_04_07_100613_create_product_promotion_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (26,'2021_04_07_153852_create_tax_rates_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (27,'2021_04_07_154718_add_fields_to_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (28,'2021_04_09_081311_create_tags_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (29,'2021_04_09_081345_create_product_tag_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (30,'2021_04_13_142701_remove_deprecated_tables',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (31,'2021_04_14_115938_create_sliders_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (32,'2021_04_14_115954_create_slides_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (33,'2021_04_19_145945_extend_champ_description_in_ranges_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (34,'2021_04_19_155920_change_optional_fields_in_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (35,'2021_04_20_154225_create_timeslot_settings_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (36,'2021_04_21_092030_create_jobs_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (37,'2021_04_21_101455_create_xml_incos_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (38,'2021_04_21_154354_create_collecte_exceptions_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (39,'2021_04_21_165607_create_magasins_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (40,'2021_04_22_153147_make_child_of_magasins_time_settings_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (41,'2021_04_23_112008_add_magasin_to_timeslots_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (42,'2021_04_26_161004_make_unique_no_art_inf_food_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (43,'2021_05_03_173156_alter_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (44,'2021_05_06_121330_create_tool_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (45,'2021_05_06_121546_create_anifood_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (46,'2021_05_06_121656_create_garment_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (47,'2021_05_07_091803_add_management_flags_to_tags_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (48,'2021_05_25_100049_add_fields_to_anifood_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (49,'2021_05_25_101151_add_fields_to_garment_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (50,'2021_06_07_124924_add_orderable_dates_to_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (51,'2021_07_20_141844_create_salaries_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (52,'2021_07_27_103748_add_required_for_order_export_fields_to_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (53,'2021_09_24_091612_add_code_societe_to_salaries_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (54,'2021_11_18_144311_alter_price_to_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (55,'2022_03_12_115802_add_nom_to_xml_incos_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (56,'2022_04_14_143040_remove_crm_id_from_customers',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (57,'2022_09_12_160131_add_brand_to_products',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (58,'2022_09_14_090354_add_fields_to_salaries',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (59,'2022_09_20_171712_link_magasin_to_salaries',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (60,'2022_10_11_163252_add_variable_weight_to_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (61,'2022_10_20_111255_alter_ranges_description_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (62,'2023_03_30_110313_alter_product_serving_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (63,'2023_07_04_151150_alter_code_salaries_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (64,'2023_07_04_151446_format_day_in_timeslots_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (65,'2023_07_26_091913_add_order_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (66,'2023_07_27_145254_alter_birth_users_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (67,'2023_07_27_150324_alter_role_users_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (68,'2023_07_27_153349_alter_clean_salaries_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (69,'2024_11_13_120306_create_uwil_redirections_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (70,'2025_02_10_112337_add_type_to_exceptions_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (71,'2025_06_18_110532_alter_uwil_redirections_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (72,'2026_02_04_102119_add_connected_field_in_slides_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (73,'2026_02_25_102520_reorder_all_products',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (74,'2026_02_25_111055_add_boolean_display_old_value_for_promotions_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (75,'2026_04_09_111244_delete_promotion_tag',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (76,'2026_04_27_152343_add_unique_to_password_resets',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (77,'2026_04_29_110121_rename_table_password_resets_to_customer_password_resets',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (78,'2026_04_29_120913_remove_id_from_customer_password_resets',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (79,'2026_05_06_164734_fix_slides_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (80,'2026_05_07_090552_delete_sliders_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (81,'2026_05_07_104436_migrate_slides_pictures',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (82,'2026_05_07_115830_add_image_attributes_on_sliders',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (83,'2026_05_07_123948_add_status_to_slides',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (84,'2026_05_12_162815_update_order_on_tags',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (85,'2026_05_12_172419_drop_anifoods_product_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (86,'2026_05_12_172830_rename_food_products',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (87,'2026_05_12_174606_drop_garment_products',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (88,'2026_05_12_174709_drop_tool_products',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (89,'2026_05_12_175637_drop_product_type_on_products',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (90,'2026_05_13_165615_resole_salarie_shop_dynamically',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (91,'2026_05_15_085114_rename_tables',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (92,'2026_05_15_094440_drop_discount_type_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (93,'2026_05_15_095409_drop_ordre_status_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (94,'2026_05_15_095736_drop_order_products',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (95,'2026_05_15_100312_drop_tax_rates',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (96,'2026_05_15_102945_drop_settings',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (97,'2026_05_15_110705_add_unique_to_matricule_employees_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (98,'2026_05_15_130940_add_unique_to_pages',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (99,'2026_05_15_131427_remove_heading_from_pages_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (100,'2026_05_15_133554_rename_promotions',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (101,'2026_05_15_165156_add_order_to_faqs_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (102,'2026_05_15_172544_add_seo_fields_on_pages_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (103,'2026_05_18_113005_migrate_old_slugs_to_redirect_package',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (104,'2026_05_18_125014_migrate_ranges_pictures',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (105,'2026_05_18_142859_add_order_to_ranges',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (106,'2026_05_18_152042_add_picture_title_to_ranges_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (107,'2026_05_18_152043_add_picture_title_to_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (108,'2026_05_19_094421_change_some_columns_on_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (109,'2026_05_19_101521_change_order_status',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (110,'2026_05_19_101521_migrate_products_pictures',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (111,'2026_05_19_101522_change_some_columns_2_on_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (112,'2026_05_20_113304_add_sort_order_to_product_product_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (113,'2026_05_20_123658_remove_margin_from_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (114,'2026_05_20_160028_change_product_inco_relation_with_product',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (115,'2026_05_21_103837_change_product_order_column',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (116,'2026_05_21_120644_remove_home_statis_page',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (117,'2026_05_21_122658_rename_offers_to_discounts',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (118,'2026_05_21_131414_rename_offers_discounts',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (119,'2026_05_21_142044_change_product_discount_relation_to_belongs_to',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (120,'2026_05_21_163851_simplify_shops_map',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (121,'2026_05_22_101939_remove_time_slot_settings',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (122,'2026_05_22_102624_remove_timeslot_time',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (123,'2026_05_22_102934_rename_shop_column_on_timeslots_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (124,'2026_05_22_104824_rename_time_slot_exceptions_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (125,'2026_05_22_124529_refactor_pickup_exception',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (126,'2026_05_26_095455_add_auto_updated_on_pickup_exceptions_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (127,'2026_05_26_143214_add_replacements_day_to_shop_pickup_exception_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (128,'2026_05_26_154849_convert_all_dates_to_utc',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (129,'2026_05_28_095941_remove_order_comment',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (130,'2026_05_28_101213_consolidate_order',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (131,'2026_05_28_101213_convert_discount_value_as_int',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (132,'2026_05_28_101213_convert_order_total_as_int',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (133,'2026_05_28_101213_convert_product_prices_as_int',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (134,'2026_05_28_101213_rename_columns_on_discount_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (135,'2026_05_28_102411_consolidate_order_lines',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (136,'2026_06_01_130113_update_sliders_links',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (137,'2026_06_01_150709_update_page_title',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (138,'2026_06_03_143713_add_short_description_to_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (139,'2026_06_04_154533_change_columns_to_int_on_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (140,'2026_06_05_082126_strip_product_short_description',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (141,'2026_06_05_112425_add_delivery_address_to_orders',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (142,'2026_06_06_181952_migrate_products_to_uuidv7',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (143,'2026_06_06_181953_migrate_orders_to_uuidv7',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (144,'2026_06_07_072414_migrate_customers_to_uuidv7',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (145,'2026_06_07_172027_drop_date_column_from_orders_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (146,'2026_06_07_175730_add_reference_to_orders_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (147,'2026_06_07_180625_simplify_timeslot_into_orders',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (148,'2026_06_07_193825_update_shop_employee_exception_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (149,'2026_06_08_164207_add_employee_matricule_virtual_index_to_orders_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (150,'2026_06_10_221046_make_invoicing_and_sell_unit_not_nullable_on_products_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (151,'2026_06_11_091414_move_invalid_orders_and_make_employee_non_nullable',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (152,'2026_06_11_104029_add_last_login_at_to_customers_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (153,'2026_06_11_160000_migrate_weights_to_grams',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (154,'2026_06_12_120149_convert_weight_variable_to_boolean_in_order_lines_product',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (155,'2026_06_12_122322_populate_null_discounted_price_in_order_lines_product',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (156,'2026_06_13_151618_migrate_shops_and_pickup_exceptions_to_uuidv7',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (157,'2026_10_01_123336_add_last_sync_to_employees',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (158,'2026_10_01_150950_fix_employee_service_code',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (159,'2026_10_01_163000_create_settings_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (160,'2026_10_02_130500_fix_ambiguous_employee_codes',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (161,'2026_10_02_143800_fix_orders_employee_column',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (162,'2026_10_02_222500_drop_xml_incos_table',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (163,'2026_10_07_100650_recalculate_products_order',1); +INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (164,'2026_11_02_111000_fix_inco_id_in_order_lines_product',1); From e4db1a476ddcb250bb8c2c78fdf2716ef3f85b04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Sat, 14 Nov 2026 16:05:52 +0100 Subject: [PATCH 009/183] refactor(infra): configure PVC-less volumes, /tmp purifier cache and S3 CSP headers --- app/Http/Middleware/SecureHeaders.php | 23 +++++++++++++++++++---- config/purifier.php | 2 +- manifest.yaml | 25 +++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 5 deletions(-) diff --git a/app/Http/Middleware/SecureHeaders.php b/app/Http/Middleware/SecureHeaders.php index 59227c81..d3f92f9c 100644 --- a/app/Http/Middleware/SecureHeaders.php +++ b/app/Http/Middleware/SecureHeaders.php @@ -4,10 +4,10 @@ declare(strict_types=1); namespace App\Http\Middleware; -use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Vite; +use Illuminate\Support\Str; use Symfony\Component\HttpFoundation\Response; class SecureHeaders @@ -27,9 +27,9 @@ class SecureHeaders /** * Handle an incoming request. * - * @param \Closure(\Illuminate\Http\Request):(\Illuminate\Http\Response) $next + * @param \Closure(\Illuminate\Http\Request):(\Symfony\Component\HttpFoundation\Response) $next */ - public function handle(Request $request, Closure $next): Response + public function handle(Request $request, \Closure $next): Response { $appUrl = Config::string('app.url'); $appDebug = Config::boolean('app.debug'); @@ -58,11 +58,19 @@ class SecureHeaders $this->removeUnwantedHeaders($this->unwantedHeaderList); $response = $next($request); - $response->headers->set('Referrer-Policy', 'no-referrer-when-downgrade'); + $response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin'); $response->headers->set('X-Content-Type-Options', 'nosniff'); $response->headers->set('X-XSS-Protection', '1; mode=block'); $response->headers->set('X-Frame-Options', 'SAMEORIGIN'); $response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload'); + $response->headers->set('X-Permitted-Cross-Domain-Policies', 'none'); + $response->headers->set('Cross-Origin-Opener-Policy', 'same-origin-allow-popups'); + $response->headers->set('Cross-Origin-Resource-Policy', 'same-origin'); + $response->headers->set('Permissions-Policy', 'fullscreen=(self), geolocation=(self), camera=(), microphone=(), payment=()'); + $response->headers->set('Feature-Policy', "fullscreen 'self'; geolocation 'self';"); + + $s3PublicEndpoint = Str::of(Config::string('filesystems.disks.s3.url')) + ->chopEnd('/')->append('/')->value(); // * Ignore CSP on some conditions. if ( @@ -79,7 +87,10 @@ class SecureHeaders $cspPolicies = [ "default-src 'none';", "base-uri 'self';", + "form-action 'self';", + "frame-ancestors 'self';", "manifest-src 'self';", + "media-src 'self' blob: " . implode(' ', array_filter([$appUrl, $s3PublicEndpoint])) . ';', // * CKEDITOR Specific https://ckeditor.com/docs/ckeditor5/latest/installation/advanced/csp.html "connect-src 'self' " . implode(' ', [ 'https://yl.s-web.fr/', @@ -88,11 +99,15 @@ class SecureHeaders // * VITE DEV $viteDevSocket, $viteDevOrigin, + $s3PublicEndpoint, ]) . ';', "img-src 'self' data: blob: " . implode(' ', [ $viteDevOrigin, $openStreetMapTiles, + $s3PublicEndpoint, ]) . ' data:;', + "worker-src 'self' blob:;", + "object-src 'none';", 'child-src ' . implode(' ', []) . ';', "object-src 'none';", "font-src 'self' data: " . \implode(' ', [ diff --git a/config/purifier.php b/config/purifier.php index 19c70944..6f822dd0 100644 --- a/config/purifier.php +++ b/config/purifier.php @@ -23,7 +23,7 @@ declare(strict_types=1); return [ 'encoding' => 'UTF-8', 'finalize' => true, - 'cachePath' => storage_path('app/purifier'), + 'cachePath' => '/tmp/purifier', 'cacheFileMode' => 0755, 'settings' => [ 'default' => [ diff --git a/manifest.yaml b/manifest.yaml index 08864f07..d851ec04 100644 --- a/manifest.yaml +++ b/manifest.yaml @@ -106,6 +106,10 @@ spec: emptyDir: {} - name: laravel-views emptyDir: {} + - name: laravel-logs + emptyDir: {} + - name: tmp + emptyDir: {} containers: - name: ${CI_PROJECT_PATH_SLUG}-container image: $IMAGE_TAG @@ -125,6 +129,10 @@ spec: mountPath: /app/srcs/bootstrap/cache - name: laravel-views mountPath: /app/srcs/storage/framework/views + - name: laravel-logs + mountPath: /app/srcs/storage/logs + - name: tmp + mountPath: /tmp readinessProbe: httpGet: path: /up @@ -180,6 +188,15 @@ spec: envFrom: - configMapRef: name: ${CI_PROJECT_PATH_SLUG}-config-map + volumeMounts: + - name: laravel-cache + mountPath: /app/srcs/bootstrap/cache + - name: laravel-views + mountPath: /app/srcs/storage/framework/views + - name: laravel-logs + mountPath: /app/srcs/storage/logs + - name: tmp + mountPath: /tmp securityContext: # TODO : valider le POC # readOnlyRootFilesystem: true @@ -303,6 +320,10 @@ spec: emptyDir: {} - name: laravel-views emptyDir: {} + - name: laravel-logs + emptyDir: {} + - name: tmp + emptyDir: {} containers: - name: ${CI_PROJECT_PATH_SLUG}-scheduled image: $IMAGE_TAG @@ -321,6 +342,10 @@ spec: mountPath: /app/srcs/bootstrap/cache - name: laravel-views mountPath: /app/srcs/storage/framework/views + - name: laravel-logs + mountPath: /app/srcs/storage/logs + - name: tmp + mountPath: /tmp resources: requests: cpu: "${APP_CI_CPU_REQUEST}" From 06842155111ba65842d37792a888130dc4cbfc7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Sat, 14 Nov 2026 16:06:03 +0100 Subject: [PATCH 010/183] feat(storage): add S3 disks, temporary file factory and image optimizer service --- app/Casts/FilePathCast.php | 45 ++ app/Exceptions/ImageOptimizerException.php | 13 + app/Lib/Helpers/FileStorageHelper.php | 525 ------------------ app/Lib/Helpers/ToolboxHelper.php | 84 --- app/Lib/Helpers/ToolboxHelperCore.php | 32 -- app/Lib/PrivateS3Disk.php | 19 + app/Lib/PublicS3Disk.php | 49 ++ app/Providers/AppServiceProvider.php | 57 +- app/Services/ImageOptimizerService.php | 86 +++ app/Traits/Requests/HasPicture.php | 290 ---------- app/helpers.php | 27 + composer.json | 5 + composer.lock | 260 ++++++++- config/filesystems.php | 24 - config/storage-service.php | 18 + lang/fr/validation.php | 9 - shared/Filesystem/TemporaryFileException.php | 9 + shared/Filesystem/TemporaryFileFactory.php | 140 +++++ .../WithApp/Helpers/FileStorageHelperTest.php | 139 ----- .../Helpers/ToolboxHelperCoreHarness.php | 20 - .../WithApp/Helpers/ToolboxHelpercoreTest.php | 45 +- .../Services/ImageOptimizerServiceTest.php | 57 ++ 22 files changed, 753 insertions(+), 1200 deletions(-) create mode 100644 app/Casts/FilePathCast.php create mode 100644 app/Exceptions/ImageOptimizerException.php delete mode 100644 app/Lib/Helpers/FileStorageHelper.php create mode 100644 app/Lib/PrivateS3Disk.php create mode 100644 app/Lib/PublicS3Disk.php create mode 100644 app/Services/ImageOptimizerService.php delete mode 100644 app/Traits/Requests/HasPicture.php create mode 100644 app/helpers.php create mode 100644 config/storage-service.php create mode 100644 shared/Filesystem/TemporaryFileException.php create mode 100644 shared/Filesystem/TemporaryFileFactory.php delete mode 100644 tests/Integration/WithApp/Helpers/FileStorageHelperTest.php delete mode 100644 tests/Integration/WithApp/Helpers/ToolboxHelperCoreHarness.php create mode 100644 tests/Unit/Services/ImageOptimizerServiceTest.php diff --git a/app/Casts/FilePathCast.php b/app/Casts/FilePathCast.php new file mode 100644 index 00000000..a59274f8 --- /dev/null +++ b/app/Casts/FilePathCast.php @@ -0,0 +1,45 @@ + */ +class FilePathCast implements CastsAttributes +{ + /** @param array $attributes */ + public function get(Model $model, string $key, mixed $value, array $attributes): ?StorageFilePath + { + if ($value === null) { + return null; + } + + if (! is_string($value)) { + throw new \InvalidArgumentException('The given value is not a valid file path string.'); + } + + return new StorageFilePath($value); + } + + /** @param array $attributes */ + public function set(Model $model, string $key, mixed $value, array $attributes): ?string + { + if ($value === null) { + return null; + } + + if ($value instanceof StorageFilePath) { + return $value->value; + } + + if (is_string($value)) { + return (new StorageFilePath($value))->value; + } + + throw new \InvalidArgumentException('The given value is not a valid StorageFilePath instance or path string.'); + } +} diff --git a/app/Exceptions/ImageOptimizerException.php b/app/Exceptions/ImageOptimizerException.php new file mode 100644 index 00000000..de4ce8b6 --- /dev/null +++ b/app/Exceptions/ImageOptimizerException.php @@ -0,0 +1,13 @@ +path($path); - } - - /** - * Destroy the file associate with the attribute. - */ - public static function removeFile(Model $model, string $attribute): void - { - $path = \ltrim(\urldecode((string) $model->{$attribute}), '/'); - if (! str_starts_with($path, 'storage')) { - return; - } - $path = Str::replace(self::STORAGE_PREFIX, '', $path); - if (Storage::disk('public')->exists($path)) { - Storage::disk('public')->delete($path); - } - } - - /** - * Destroy the file associate with the attribute old value (before updated to DB). - */ - public static function removeOldFile(Model $model, string $attribute, bool $onlyIfUpdated = true): void - { - $originalValue = ToolboxHelper::getOriginal($model, $attribute); - // * Ignore If removal has to be done only if the field has changed and it actually hasnt. - if ($onlyIfUpdated && $model->{$attribute} === $originalValue) { - return; - } - - if (! is_string($originalValue)) { - return; - } - - $originalPath = \ltrim(\urldecode($originalValue), '/'); - if (! str_starts_with($originalPath, 'storage')) { - return; - } - $originalPath = Str::replace(self::STORAGE_PREFIX, '', $originalPath); - if (Storage::disk('public')->exists($originalPath)) { - Storage::disk('public')->delete($originalPath); - } - } - - /** - * Store a file using optimized storage strategy - * - * You can use filename param to overload file name. - * - * @param Model $model The model that will hold the picture. - * @param UploadedFile|\SplFileInfo|string $file The file, will just return itself is string. - * @param bool $slugify Force filename slugification. - * @param string|null $filename This string may be used to store the file. - * @param bool $private To store the file in a private space. - * - * @throws FileStorageOperationException If file copy fails. - * - * @phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh - */ - public static function storeFile( - Model $model, - UploadedFile | \SplFileInfo | string | null $file, - bool $slugify = false, - ?string $filename = null, - bool $private = false - ): string { - // phpcs:enable - $tableName = $model->getTable(); - if ($file instanceof UploadedFile) { - return self::storeUploadedFile($file, $tableName, $slugify, $filename, $private); - } - - if ($file instanceof \SplFileInfo) { - return self::storeSplFileInfo($file, $tableName, $slugify, $filename, $private); - } - - return (string) $file; - } - - private static function storeUploadedFile( - UploadedFile $file, - string $tableName, - bool $slugify, - ?string $filename, - bool $private - ): string { - $filename = $filename ?: $file->getClientOriginalName(); - $filename = $slugify ? self::slugifyFileName($filename) : $filename; - $disk = $private ? 'private' : 'public'; - $newPath = str_replace( - storage_path("app/{$disk}"), - '', - self::prepareMoveFile($tableName, $filename, $private) - ); - - $directory = pathinfo($newPath, \PATHINFO_DIRNAME); - $basename = pathinfo($newPath, \PATHINFO_BASENAME); - - if (! $private) { - $file->storePubliclyAs( - $directory, - $basename, - ['disk' => $disk] - ); - } else { - $file->storeAs( - $directory, - $basename, - ['disk' => $disk] - ); - } - - return "storage{$newPath}"; - } - - private static function storeSplFileInfo( - \SplFileInfo $file, - string $tableName, - bool $slugify, - ?string $filename, - bool $private - ): string { - $filename = $filename ?: $file->getBaseName(); - $filename = $slugify ? self::slugifyFileName($filename) : $filename; - $newPath = self::prepareMoveFile($tableName, $filename, $private); - - if (! File::copy($file->getRealPath(), $newPath)) { - throw FileStorageOperationException::copyFailed($file->getRealPath(), $newPath); - } - - if ($private) { - return \ltrim(str_replace(\storage_path('app/private'), '/storage/app/private', $newPath), '/'); - } - - return \ltrim(str_replace(\storage_path('app/public'), '/storage', $newPath), '/'); - } - - /** - * Store all files from string attribute html - * If oldHtmlString is passed, a diff is done with new and old files - * to keep only files that are present in the new html string. - * - * @param Model $model The model that will hold the picture. - * @param string|null $htmlString The html string to parse and modify files. - * @param string|null $oldHtmlString The old html string with alreadyParsed - * files using storeModelFilesFromHtml. - * @return string|null Html with files pathes replaced using storage strategy. - */ - public static function storeModelFilesFromHtml( - Model $model, - ?string $htmlString, - ?string $oldHtmlString = null - ): ?string { - if (is_null($htmlString)) { - return null; - } - - Collection::make(self::onlyUploadedFilesWithFileManager(self::findFilesInHtml($htmlString))) - ->each(function (string $path) use ($model, &$htmlString): void { - /** @var \Illuminate\Filesystem\FilesystemAdapter */ - $disk = Storage::disk('private'); - $fileInfo = new \SplFileInfo($disk->path( - ToolboxHelper::mbReplaceSingle('/uploads/', '', \urldecode($path)) - )); - $htmlString = ToolboxHelper::mbReplaceSingle( - $path, - '/' . self::storeFile($model, $fileInfo, true), - $htmlString - ); - }); - - if ($oldHtmlString) { - self::removeOldModelFilesFromHtml($htmlString, $oldHtmlString); - } - - return $htmlString; - } - - /** - * Remove all old files from string attribute html that are stored in public that - * are nove present anymore on new html string - * - * @param string $newHtmlString The html string with alreadyParsed files using storeModelFilesFromHtml. - * @param string $oldHtmlString The old html string with alreadyParsed files using storeModelFilesFromHtml. - */ - public static function removeOldModelFilesFromHtml(string $newHtmlString, string $oldHtmlString): void - { - self::removeOldFiles(self::findFilesInHtml($oldHtmlString), self::findFilesInHtml($newHtmlString)); - } - - /** - * Remove all old files that are stored in public that - * are not present anymore on new array files - * - * @param string[] $oldFiles The old array files. - * @param string[] $newFiles The new array files. - */ - public static function removeOldFiles(array $oldFiles, array $newFiles): void - { - $oldFiles = Collection::make(self::onlyUploadedFilesWithFileStorageHelper($oldFiles)); - $filesToKeep = Collection::make(self::onlyUploadedFilesWithFileStorageHelper($newFiles)); - $filesToRemove = $oldFiles->diff($filesToKeep); - $filesToRemove->each(function (string $publicStorageFilePath): void { - $path = Str::replace(self::STORAGE_PREFIX, '', \ltrim(\urldecode($publicStorageFilePath), '/')); - if (Storage::disk('public')->exists($path)) { - Storage::disk('public')->delete($path); - } - }); - } - - /** - * Remove all files from string attribute html that are stored in public - * - * @param string $htmlString The html string with alreadyParsed files using storeModelFilesFromHtml. - */ - public static function removeModelFilesOfHtml(string $htmlString): void - { - $filesToRemove = Collection::make(self::onlyUploadedFilesWithFileStorageHelper(self::findFilesInHtml($htmlString))); - $filesToRemove->each(function (string $publicStorageFilePath): void { - $path = Str::replace(self::STORAGE_PREFIX, '', \ltrim(\urldecode($publicStorageFilePath), '/')); - if (Storage::disk('public')->exists($path)) { - Storage::disk('public')->delete($path); - } - }); - } - - /** - * Find all occurence of files in html - * - * @param string $html The html string to parse and find files. - * @return string[] The array of files found in html. - */ - public static function findFilesInHtml(string $html): array - { - preg_match_all( - '/(?:href|src|url)="([^"]*)"/Ui', - $html, - $matches - ); - - return Collection::make($matches[1])->unique()->filter()->values()->all(); - } - - /** - * Filter array to get only uploaded files that exists - * on disk 'public' (using helper storage strategy) - * - * @param string[] $urls The array of urls to filter - * @return string[] The filtered array with only uploaded files that exists on disk 'public - */ - public static function onlyUploadedFilesWithFileStorageHelper(array $urls): array - { - return Collection::make($urls)->unique() - // * Filter to get only /uploads and using app url or empty - ->filter(function (string $url) { - $path = (string) (\parse_url($url, \PHP_URL_PATH) ?? ''); - - return str_starts_with(\ltrim($path, '/'), 'storage/modelfiles'); - })->filter(function (string $url) { - $path = (string) (\parse_url($url, \PHP_URL_PATH) ?? ''); - - return Storage::disk('public') - ->exists(Str::replace(self::STORAGE_PREFIX, '', \ltrim(\urldecode($path), '/'))); - })->all(); - } - - /** - * Filter array to get only uploaded files that exist on disk 'private' - * - * @param string[] $urls The array of urls to filter - * @return string[] The filtered array - */ - private static function onlyUploadedFilesWithFileManager(array $urls): array - { - $appUrl = Config::string('app.url'); - - if (empty($appUrl)) { - throw new \UnexpectedValueException('App URL must be set in config to filter uploaded files with file manager'); - } - $appHost = parse_url((string) $appUrl, PHP_URL_HOST); - - return Collection::make($urls)->unique()->filter(function (string $url) use ($appHost) { - $host = parse_url($url, PHP_URL_HOST); - - // 1. Validation du domaine (Doit être identique à l'app ou être un chemin relatif) - if ($host !== null && $host !== $appHost) { - return false; - } - - // 2. Extraction et nettoyage du chemin - $path = ltrim(urldecode((string) parse_url($url, PHP_URL_PATH)), '/'); - - // 3. Vérification du préfixe 'uploads/' et existence sur le disque - if (! str_starts_with($path, 'uploads/')) { - return false; - } - - // On retire 'uploads/' pour tester l'existence sur le disque 'private' - $diskPath = substr($path, strlen('uploads/')); - - return Storage::disk('private')->exists($diskPath); - })->values()->all(); - } - - /** - * Prepare storage path and return - * the file full path - * - * @param string $tableName Model table name. - * @param string $filename The basename for the file. - * @param bool $private May the file be stored in a private dir. - */ - private static function prepareMoveFile(string $tableName, string $filename, bool $private = false): string - { - // * Security filter - $filename = \htmlspecialchars($filename); - // * Security filter + beautifier - $filename = self::sanitizeFileName($filename); - // * Slugify filename - $ext = \pathinfo($filename, \PATHINFO_EXTENSION); - $filename = Str::slug(\pathinfo($filename, \PATHINFO_FILENAME)) . - (\strlen($ext) ? ".{$ext}" : ''); - - $folderPath = self::getStoragePath( - $private ? 'app/private/modelfiles' : 'app/public/modelfiles', - $tableName, - $filename - ); - $filename = self::getFileUniqueName($folderPath, $filename); - - return "{$folderPath}/{$filename}"; - } - - /** - * Create sub folders to store files using pattern - * storage/modelfiles/posts/10/04/19/5f - * year/month/day/sha256 first 2 letters - */ - private static function getStoragePath(string $storage_dir, string $table, string $filename): string - { - $filenameHash = \hash('sha256', $filename); - $pathFolder = \storage_path(sprintf( - '%s/%s/%s/%s/%s/%s', - $storage_dir, - $table, - gmdate('y'), - gmdate('m'), - gmdate('d'), - substr($filenameHash, 0, 2) - )); - if (! File::exists($pathFolder)) { - File::makeDirectory($pathFolder, 0755, true); - } - - return $pathFolder; - } - - /** - * Get unique filename if the path is already occupied - * - * @throws FileStorageOperationException If a unique filename cannot be obtained. - */ - private static function getFileUniqueName(string $folderPath, string $filename): string - { - $attempts = 0; - $maxAttempts = 20; - while (File::exists("{$folderPath}/{$filename}")) { - if ($attempts++ >= $maxAttempts) { - throw FileStorageOperationException::cannotGenerateUniqueFilename($folderPath, $filename); - } - $filename = Str::of(pathinfo($filename, \PATHINFO_FILENAME)) - ->append(Str::random(8) . '-') - ->append('.') - ->append(pathinfo($filename, \PATHINFO_EXTENSION)) - ->toString(); - } - - return $filename; - } - - /** - * Slugify the filename - */ - public static function slugifyFileName(string $filename): string - { - return Str::slug(pathinfo($filename, \PATHINFO_FILENAME)) . '.' . pathinfo($filename, \PATHINFO_EXTENSION); - } - - /** - * Sanitize File name for uploaded files - * - * @param string $filename The original uploaded client file name. - * @param bool $beautify Beautify the filename. - * @return string The sanitized file name. - */ - public static function sanitizeFileName(string $filename, bool $beautify = true): string - { - $filename = preg_replace('/[<>:"\/\\|?*\x00-\x1F\x7F\xA0\xAD#\[\]@!$&\'()+,;={}^~`]/u', '-', $filename) ?? $filename; - // * Avoids '.' '..' or '.hiddenFiles' . - $filename = (string) Str::of($filename)->ltrim('.-'); - // * Optional beautification - if ($beautify) { - $filename = self::beautifyFilename($filename); - } - // * Maximize filename length to 255 bytes http://serverfault.com/a/9548/44086 - /** @var string */ - $extension = pathinfo($filename, \PATHINFO_EXTENSION); - /** @var string */ - $filename = pathinfo($filename, \PATHINFO_FILENAME); - - $encoding = mb_detect_encoding($filename); - $encoding = $encoding ?: null; - - return \mb_strcut( - $filename, - 0, - 255 - (! empty($extension) ? strlen($extension) + 1 : 0), - $encoding - ) . (! empty($extension) ? ".$extension" : ''); - } - - /** - * Beautify a filename - */ - private static function beautifyFilename(string $filename): string - { - // Reduce consecutive characters. - $filename = preg_replace([ - // * "file name.zip" becomes 'file-name.zip' - '/ +/', - // * "file___name.zip" becomes 'file-name.zip' - '/_+/', - // * "file---name.zip" becomes 'file-name.zip' - '/-+/', - ], '-', $filename) ?? $filename; - $filename = preg_replace([ - // * "file--.--.-.--name.zip" becomes "file.name.zip" - '/-*\.-*/', - // * "file...name..zip" becomes "file.name.zip" - '/\.{2,}/', - ], '.', $filename) ?? $filename; - // Lowercase for windows/unix interoperability http://support.microsoft.com/kb/100625 . - $encoding = mb_detect_encoding($filename); - $filename = mb_strtolower($filename, $encoding ?: 'UTF-8'); - // * ".file-name.-" becomes "file-name" - $filename = trim($filename, '.-'); - - return $filename; - } - - /** - * Remove all model files for the given Model. - */ - public static function removeModelFiles(Model $model): void - { - $tableName = $model::query()->getModel()->getTable(); - - if (! empty(Storage::disk('public')->allFiles("modelfiles/{$tableName}"))) { - Storage::disk('public')->deleteDirectory("modelfiles/{$tableName}"); - } - if (! empty(Storage::disk('private')->allFiles("modelfiles/{$tableName}"))) { - Storage::disk('private')->deleteDirectory("modelfiles/{$tableName}"); - } - } - - public static function isMimeType(string $mimeType, \SplFileInfo $file): bool - { - if (! $file->getRealPath()) { - return false; - } - - $actualMime = File::mimeType($file->getRealPath()); - - return $actualMime ? Str::is($mimeType, $actualMime) : false; - } -} diff --git a/app/Lib/Helpers/ToolboxHelper.php b/app/Lib/Helpers/ToolboxHelper.php index d17ff34c..0e53f5e4 100644 --- a/app/Lib/Helpers/ToolboxHelper.php +++ b/app/Lib/Helpers/ToolboxHelper.php @@ -5,8 +5,6 @@ declare(strict_types=1); namespace App\Lib\Helpers; use Illuminate\Database\Eloquent\Model; -use Illuminate\Support\Facades\File; -use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; use Illuminate\Validation\Rule; @@ -102,86 +100,4 @@ class ToolboxHelper extends ToolboxHelperCore return $model->getOriginal($attribute); } - - /** - * Validate picture - * - * @param callable(string):void $fail A callback that should be called if the validation fails. - * @param object{ - * minWidth: int, - * maxWidth: int, - * minHeight: int, - * maxHeight: int - * }&\stdClass $sizes An object containing the minimum and maximum width and height for the picture. - * - * @throws \Illuminate\Validation\ValidationException If the picture is invalid. - */ - public static function validatePicture(string $attribute, ?string $value, callable $fail, object $sizes): void - { - if ($value === null) { - return; - } - - if (! ($useStorage = Storage::exists($value)) && ! File::exists($value)) { - $fail(trans('validation.custom.has_picture.file_does_not_exist', [ - 'attribute' => $attribute, - ])); - - return; - } - $fileFullPath = self::getUploadedFileFullPath($value, $useStorage); - if ( - ! \in_array(self::getUploadedFileMimeType($value, $useStorage), [ - 'image/jpeg', - 'image/jpg', - 'image/png', - 'image/gif', - ]) - ) { - $fail(trans('validation.mimetypes', [ - 'attribute' => $attribute, - 'values' => 'image/jpeg, image/jpg, image/png, image/gif', - ])); - } - if (! ($dimensions = \getimagesize($fileFullPath))) { - $fail(trans('validation.dimensions', [ - 'attribute' => $attribute, - ])); - - return; - } - - $width = intval($dimensions[0]); - $height = intval($dimensions[1]); - - $xMessage = trans('validation.custom.has_picture.width_between', [ - 'attribute' => $attribute, - 'min' => "{$sizes->minWidth}px", - 'max' => "{$sizes->maxWidth}px", - ]); - if ($sizes->minWidth === $sizes->maxWidth) { - $xMessage = trans('validation.custom.has_picture.width_equal', [ - 'attribute' => $attribute, - 'value' => "{$sizes->minWidth}px", - ]); - } - $yMessage = trans('validation.custom.has_picture.height_between', [ - 'attribute' => $attribute, - 'min' => "{$sizes->minHeight}px", - 'max' => "{$sizes->maxHeight}px", - ]); - if ($sizes->minHeight === $sizes->maxHeight) { - $yMessage = trans('validation.custom.has_picture.height_equal', [ - 'attribute' => $attribute, - 'value' => "{$sizes->minHeight}px", - ]); - } - - if (($width < $sizes->minWidth) || ($width > $sizes->maxWidth)) { - $fail($xMessage); - } - if (($height < $sizes->minHeight) || ($height > $sizes->maxHeight)) { - $fail($yMessage); - } - } } diff --git a/app/Lib/Helpers/ToolboxHelperCore.php b/app/Lib/Helpers/ToolboxHelperCore.php index 61463bde..99add04d 100644 --- a/app/Lib/Helpers/ToolboxHelperCore.php +++ b/app/Lib/Helpers/ToolboxHelperCore.php @@ -4,9 +4,6 @@ declare(strict_types=1); namespace App\Lib\Helpers; -use Illuminate\Support\Facades\File; -use Illuminate\Support\Facades\Storage; - abstract class ToolboxHelperCore { /** @@ -116,33 +113,4 @@ abstract class ToolboxHelperCore return implode($replace, $parts); } - - /** - * Get the file full path - */ - protected static function getUploadedFileFullPath(string $value, bool $useStorage): string - { - /** @var \Illuminate\Filesystem\FilesystemAdapter */ - $disk = Storage::disk(); - - if ($useStorage) { - return $disk->path($value); - } - - return realpath($value) ?: $value; - } - - /** - * Get the file mimetype - * - * @return string|false - */ - protected static function getUploadedFileMimeType(string $value, bool $useStorage) - { - if ($useStorage) { - return Storage::mimeType($value); - } - - return File::mimeType($value); - } } diff --git a/app/Lib/PrivateS3Disk.php b/app/Lib/PrivateS3Disk.php new file mode 100644 index 00000000..270b6adf --- /dev/null +++ b/app/Lib/PrivateS3Disk.php @@ -0,0 +1,19 @@ +disk = new DiskName(self::DISK_NAME, 's3'); + } +} diff --git a/app/Lib/PublicS3Disk.php b/app/Lib/PublicS3Disk.php new file mode 100644 index 00000000..5e7e5a0b --- /dev/null +++ b/app/Lib/PublicS3Disk.php @@ -0,0 +1,49 @@ +disk = new DiskName(self::DISK_NAME, 's3'); + $this->urlEndpoint = $this->s3PublicEndpoint; + $adapter = Storage::disk($this->disk->value); + + if (! ($adapter instanceof AwsS3V3Adapter)) { + throw new \UnexpectedValueException("Expected {$this->disk->value} to be a S3 disk"); + } + + $this->adapter = $adapter; + } + + public function publicUrlOf(string $path): string + { + $prefix = trim(Config::string('storage-service.prefix', 'media'), '/'); + $trimmedPath = ltrim($path, '/'); + + $fullPath = when( + str_starts_with($trimmedPath, $prefix . '/'), + $trimmedPath, + ($prefix !== '' ? "{$prefix}/{$trimmedPath}" : $trimmedPath) + ); + + return $this->adapter->url($fullPath); + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 0d41a518..aa512299 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -14,12 +14,16 @@ use App\Contracts\Repositories\UserRepository; use App\Directories\EloquentCustomerDirectory; use App\Directories\EloquentEmployeeDirectory; use App\Directories\EloquentOrderDirectory; +use App\Lib\PrivateS3Disk; +use App\Lib\PublicS3Disk; use App\Repositories\EloquentEmployeeRepository; use App\Repositories\EloquentOrderRepository; use App\Repositories\EloquentUserRepository; use App\Services\ActionExecutorService; +use Carbon\CarbonInterface; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\URL; use Illuminate\Support\Facades\Vite; @@ -46,6 +50,17 @@ class AppServiceProvider extends ServiceProvider return request()->ip() ?? request()->getClientIp(); }); + $this->app->singleton( + PrivateS3Disk::class, + fn () => new PrivateS3Disk() + ); + $this->app->singleton( + PublicS3Disk::class, + fn () => new PublicS3Disk( + Config::string('filesystems.disks.s3.url') + ) + ); + $this->app->bind(EmployeeRepository::class, EloquentEmployeeRepository::class); $this->app->bind(OrderRepository::class, EloquentOrderRepository::class); $this->app->bind(UserRepository::class, EloquentUserRepository::class); @@ -97,42 +112,36 @@ class AppServiceProvider extends ServiceProvider private function dateMacro(): void { Date::macro('toLocalInput', function ($date) { - if (! $date) { + if (! $date || (! $date instanceof CarbonInterface && ! $date instanceof \DateTimeInterface && ! is_string($date))) { return null; } - $timezone = request()->string( - 'client_timezone', - request()->string( - 'client_timezone', - 'Europe/Paris' - )->value() - )->value(); - - return Date::parse($date) - ->setTimezone($timezone) - ->format('Y-m-d\TH:i'); + return $this->withLocalTimezone($date)->format('Y-m-d\TH:i'); }); Date::macro('forHumans', function ($date) { - if (! $date) { + if (! $date || (! $date instanceof CarbonInterface && ! $date instanceof \DateTimeInterface && ! is_string($date))) { return null; } - $timezone = request()->string( - 'client_timezone', - request()->string( - 'client_timezone', - 'Europe/Paris' - )->value() - )->value(); - - return Date::parse($date) - ->setTimezone($timezone) - ->isoFormat('ddd DD/MM/Y \à HH:mm'); + return $this->withLocalTimezone($date)->isoFormat('ddd DD/MM/Y \à HH:mm'); }); } + private function withLocalTimezone(CarbonInterface | \DateTimeInterface | string $date): CarbonInterface + { + $timezone = request()->string( + 'client_timezone', + request()->string( + 'client_timezone', + 'Europe/Paris' + )->value() + )->value(); + + return Date::parse($date) + ->setTimezone($timezone); + } + private function collectionMacro(): void { Collection::macro('uniqueValues', function () { diff --git a/app/Services/ImageOptimizerService.php b/app/Services/ImageOptimizerService.php new file mode 100644 index 00000000..ecb69035 --- /dev/null +++ b/app/Services/ImageOptimizerService.php @@ -0,0 +1,86 @@ + $quality + */ + public function optimize( + UploadedFile $file, + int $quality = self::DEFAULT_QUALITY, + ): \SplFileObject { + try { + if (! $this->isImage($file)) { + return $this->toFileObject($file); + } + + $bytes = Image::fromUpload($file) + ->quality(clamp($quality, 1, 100)) + ->toBytes(); + + if ($bytes === false) { + throw new ImageOptimizerException('Could not read image bytes.'); + } + + return $this->temporaryFileFactory->newWithBytes( + $bytes, + $file->getClientOriginalName() + ); + } catch (\Throwable $e) { + $this->logger->warning( + "Image optimization skipped for [{$file->getClientOriginalName()}]: {$e->getMessage()}", + ['exception' => $e], + ); + + return $this->toFileObject($file); + } + } + + private function toFileObject(UploadedFile $file): \SplFileObject + { + $bytes = $file->get(); + + if ($bytes === false) { + throw new ImageOptimizerException('Could not read the uploaded file bytes.'); + } + + return $this->temporaryFileFactory->newWithBytes($bytes, $file->getClientOriginalName()); + } + + private function isImage(UploadedFile $file): bool + { + if (! $file->isValid() || ! $file->isReadable()) { + return false; + } + + $mime = strtolower((string) $file->getMimeType()); + + return in_array($mime, self::SUPPORTED_MIMES, true); + } +} diff --git a/app/Traits/Requests/HasPicture.php b/app/Traits/Requests/HasPicture.php deleted file mode 100644 index d041f683..00000000 --- a/app/Traits/Requests/HasPicture.php +++ /dev/null @@ -1,290 +0,0 @@ -> - */ - public function pictureRules( - string $name = 'picture', - ?int $minWith = null, - ?int $minHeight = null, - ?int $maxWith = null, - ?int $maxHeight = null, - bool $nullable = false - ): array { - $sizes = (object) [ - 'minWith' => $minWith ?? $this->minWith, - 'minHeight' => $minHeight ?? $this->minHeight, - 'maxWith' => $maxWith ?? $this->maxWith, - 'maxHeight' => $maxHeight ?? $this->maxHeight, - ]; - - return [ - $name => [ - ! $nullable ? 'required' : 'nullable', - function (string $attribute, $value, callable $fail) use ($sizes): void { - /** @var UploadedFile|string $value */ - $valuePath = is_string($value) ? $value : $value->getPathname(); - $this->validatePicture($attribute, $valuePath, $fail, $sizes); - }, - ], - ]; - } - - /** - * Images rules - * - * @return array> - */ - public function picturesRules( - string $name = 'pictures', - ?int $minWith = null, - ?int $minHeight = null, - ?int $maxWith = null, - ?int $maxHeight = null - ): array { - $sizes = (object) [ - 'minWith' => $minWith ?? $this->minWith, - 'minHeight' => $minHeight ?? $this->minHeight, - 'maxWith' => $maxWith ?? $this->maxWith, - 'maxHeight' => $maxHeight ?? $this->maxHeight, - ]; - - return [ - $name => 'sometimes|array', - "{$name}Validate" => "required_with:{$name}|array", - "{$name}Validate.*" => [ - 'required', - function (string $attribute, $value, callable $fail) use ($sizes): void { - /** @var UploadedFile|string $value */ - $valuePath = is_string($value) ? $value : $value->getPathname(); - $this->validatePicture($attribute, $valuePath, $fail, $sizes); - }, - ], - ]; - } - - /** - * Validate picture - * - * @param callable(string):void $fail - * @param object{minWith:int,minHeight:int,maxWith:int,maxHeight:int} $sizes - * - * @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundBeforeLastUsed - */ - private function validatePicture(string $_attribute, string $value, callable $fail, object $sizes): void - { - unset($_attribute); - if (! ($useStorage = Storage::exists($value)) && ! File::exists($value)) { - $fail(trans('validation.custom.has_picture.file_does_not_exist')); - - return; - } - /** @var string */ - $fileFullPath = $this->getUploadedFileFullPath($value, $useStorage); - if ( - ! \in_array($this->getUploadedFileMimeType($value, $useStorage), [ - 'image/jpeg', - 'image/jpg', - 'image/png', - 'image/gif', - ]) - ) { - $fail(trans('validation.mimetypes', [ - 'values' => 'image/jpeg, image/jpg, image/png, image/gif', - ])); - } - if (! is_readable($fileFullPath)) { - $fail(trans('validation.custom.has_picture.file_not_readable')); - - return; - } - - if (! ($dimensions = \getimagesize($fileFullPath))) { - $fail(trans('validation.dimensions')); - - return; - } - $width = intval($dimensions[0]); - $height = intval($dimensions[1]); - - $xMessage = trans('validation.custom.has_picture.width_between', [ - 'min' => "{$sizes->minWith}px", - 'max' => "{$sizes->maxWith}px", - ]); - if ($sizes->minWith === $sizes->maxWith) { - $xMessage = trans('validation.custom.has_picture.width_equal', [ - 'value' => "{$sizes->minWith}px", - ]); - } - $yMessage = trans( - 'validation.custom.has_picture.height_between', - [ - 'min' => "{$sizes->minHeight}px", - 'max' => "{$sizes->maxHeight}px", - ] - ); - if ($sizes->minHeight === $sizes->maxHeight) { - $yMessage = trans('validation.custom.has_picture.height_equal', [ - 'value' => "{$sizes->minHeight}px", - ]); - } - - if (($width < $sizes->minWith) || ($width > $sizes->maxWith)) { - $fail($xMessage); - } - if (($height < $sizes->minHeight) || ($height > $sizes->maxHeight)) { - $fail($yMessage); - } - if (\filesize($fileFullPath) > ($this->maxWeight * 1024)) { - $fail(trans('validation.custom.has_picture.weight_max', [ - 'value' => $this->maxWeight, - ])); - } - } - - /** - * Merges products pictures fields with request data - */ - protected function mergePicture(string $name = 'picture'): void - { - /** @var UploadedFile|string|null */ - $picturePath = $this->{$name}; - if (is_string($picturePath) || $picturePath instanceof UploadedFile) { - $this->merge(["{$name}Validate" => []]); - // ! Empty picture. - if ($picturePath === 'false') { - // * Empty picture and exit - $this->merge([$name => []]); - - return; - } - $decodedPath = \urldecode(is_string($picturePath) ? $picturePath : $picturePath->getPathname()); - - $this->merge([ - "{$name}Validate" => array_merge( - $this->{"{$name}Validate"}, - [\public_path(ltrim($decodedPath, '/'))] - ), - ]); - $changedPicture = ltrim($decodedPath, '/'); - $this->merge([ - $name => $changedPicture, - ]); - } // End if. - } - - /** - * Merges products pictures fields with request data - */ - protected function mergePictures(string $name = 'pictures'): void - { - // Allows to empty pictures. - $pictures = $this->array($name); - $this->merge([ - $name => $pictures, - ]); - $this->merge(["{$name}Validate" => []]); - foreach ($pictures as $key => $picturePath) { - // ! Empty picture. - if ($picturePath === 'false') { - // * Empty picture and exit - $this->merge([$name => []]); - - return; - } - $decodedPath = \urldecode((! is_string($picturePath) && $picturePath) ? $picturePath->getPathname() : $picturePath); - $this->merge([ - "{$name}Validate" => array_merge( - $this->{"{$name}Validate"}, - [is_string($picturePath) ? \public_path(ltrim($decodedPath, '/')) : $picturePath] - ), - ]); - $changedPictures = $this->{$name}; - if (is_string($picturePath)) { - $changedPictures[$key] = ltrim($decodedPath, '/'); - } - $this->merge([ - $name => $changedPictures, - ]); - } // End foreach. - } - - /** - * Get the file full path - */ - private static function getUploadedFileFullPath(string $value, bool $useStorage): string - { - /** @var FilesystemAdapter */ - $disk = Storage::disk(); - - if (! $useStorage) { - return realpath($value) ?: $value; - } - - return $disk->path($value); - } - - /** - * Get the file mimetype - * - * @return string|false - */ - private function getUploadedFileMimeType(string $value, bool $useStorage) - { - return ! $useStorage ? File::mimeType($value) : Storage::mimeType($value); - } -} diff --git a/app/helpers.php b/app/helpers.php new file mode 100644 index 00000000..f1123ac1 --- /dev/null +++ b/app/helpers.php @@ -0,0 +1,27 @@ +value + : $path; + + if (str_starts_with($pathValue, 'http://') || str_starts_with($pathValue, 'https://')) { + return $pathValue; + } + + $s3Disk = app()->make(PublicS3Disk::class); + + return $s3Disk->publicUrlOf($pathValue); + } +} diff --git a/composer.json b/composer.json index 359fed4b..a888e3d7 100644 --- a/composer.json +++ b/composer.json @@ -11,6 +11,7 @@ "php": "^8.5", "axlon/laravel-postal-code-validation": "^3.9", "diglactic/laravel-breadcrumbs": "^10.1", + "intervention/image": "^4.0", "kwaadpepper/serial-int-caster": "^2.0", "laravel/framework": "^13.0", "laravel/tinker": "^3.0", @@ -29,6 +30,7 @@ "uwil/laravel-admin-secure": "^6.0", "uwil/laravel-redirections": "^3.0", "uwil/sitemap-generator": "^7.0", + "uwil/storage-laravel": "*", "webmozart/assert": "^2.4" }, "require-dev": { @@ -78,6 +80,9 @@ } }, "autoload": { + "files": [ + "app/helpers.php" + ], "psr-4": { "App\\": "app/", "Domain\\": "domain/", diff --git a/composer.lock b/composer.lock index faabd587..db280ac1 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "f01f8102e7b6581b3ec94ade3b273714", + "content-hash": "4153b2dd831c9e7586484890903f713e", "packages": [ { "name": "aws/aws-crt-php", @@ -62,16 +62,16 @@ }, { "name": "aws/aws-sdk-php", - "version": "3.403.4", + "version": "3.403.5", "source": { "type": "git", "url": "https://github.com/aws/aws-sdk-php.git", - "reference": "2d01207539928fe943a3f8d8981952b3655e2fc1" + "reference": "6e52905dabd868c1bc7fd491e0deec6f78a0f7d1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/2d01207539928fe943a3f8d8981952b3655e2fc1", - "reference": "2d01207539928fe943a3f8d8981952b3655e2fc1", + "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/6e52905dabd868c1bc7fd491e0deec6f78a0f7d1", + "reference": "6e52905dabd868c1bc7fd491e0deec6f78a0f7d1", "shasum": "" }, "require": { @@ -153,9 +153,9 @@ "support": { "forum": "https://github.com/aws/aws-sdk-php/discussions", "issues": "https://github.com/aws/aws-sdk-php/issues", - "source": "https://github.com/aws/aws-sdk-php/tree/3.403.4" + "source": "https://github.com/aws/aws-sdk-php/tree/3.403.5" }, - "time": "2026-11-11T19:03:26+00:00" + "time": "2026-11-12T19:40:30+00:00" }, { "name": "axlon/laravel-postal-code-validation", @@ -1586,16 +1586,16 @@ }, { "name": "guzzlehttp/psr7", - "version": "2.13.2", + "version": "2.13.3", "source": { "type": "git", "url": "https://github.com/guzzle/psr7.git", - "reference": "adee536f95101929f262b8c59e8a61472f347d58" + "reference": "6d3cd8285a97eaa352956a4ada92fa03ecce1c4e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/psr7/zipball/adee536f95101929f262b8c59e8a61472f347d58", - "reference": "adee536f95101929f262b8c59e8a61472f347d58", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/6d3cd8285a97eaa352956a4ada92fa03ecce1c4e", + "reference": "6d3cd8285a97eaa352956a4ada92fa03ecce1c4e", "shasum": "" }, "require": { @@ -1685,7 +1685,7 @@ ], "support": { "issues": "https://github.com/guzzle/psr7/issues", - "source": "https://github.com/guzzle/psr7/tree/2.13.2" + "source": "https://github.com/guzzle/psr7/tree/2.13.3" }, "funding": [ { @@ -1701,7 +1701,7 @@ "type": "tidelift" } ], - "time": "2026-10-17T23:49:46+00:00" + "time": "2026-11-12T15:57:42+00:00" }, { "name": "guzzlehttp/uri-template", @@ -1789,6 +1789,150 @@ ], "time": "2026-08-24T17:13:02+00:00" }, + { + "name": "intervention/gif", + "version": "5.0.1", + "source": { + "type": "git", + "url": "https://github.com/Intervention/gif.git", + "reference": "bb395af960deffe64d70c976b4df9283f68e762d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Intervention/gif/zipball/bb395af960deffe64d70c976b4df9283f68e762d", + "reference": "bb395af960deffe64d70c976b4df9283f68e762d", + "shasum": "" + }, + "require": { + "php": "^8.3" + }, + "require-dev": { + "phpstan/phpstan": "^2.1", + "phpunit/phpunit": "^12.0", + "slevomat/coding-standard": "~8.0", + "squizlabs/php_codesniffer": "^4" + }, + "type": "library", + "autoload": { + "psr-4": { + "Intervention\\Gif\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Oliver Vogel", + "email": "oliver@intervention.io", + "homepage": "https://intervention.io/" + } + ], + "description": "PHP GIF Encoder/Decoder", + "homepage": "https://github.com/intervention/gif", + "keywords": [ + "animation", + "gd", + "gif", + "image" + ], + "support": { + "issues": "https://github.com/Intervention/gif/issues", + "source": "https://github.com/Intervention/gif/tree/5.0.1" + }, + "funding": [ + { + "url": "https://paypal.me/interventionio", + "type": "custom" + }, + { + "url": "https://github.com/Intervention", + "type": "github" + }, + { + "url": "https://ko-fi.com/interventionphp", + "type": "ko_fi" + } + ], + "time": "2026-05-03T06:04:47+00:00" + }, + { + "name": "intervention/image", + "version": "4.4.1", + "source": { + "type": "git", + "url": "https://github.com/Intervention/image.git", + "reference": "3a47838f2e0f4ec6c8c9b43a5d73ac985b975830" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Intervention/image/zipball/3a47838f2e0f4ec6c8c9b43a5d73ac985b975830", + "reference": "3a47838f2e0f4ec6c8c9b43a5d73ac985b975830", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "intervention/gif": "^5", + "php": "^8.3" + }, + "require-dev": { + "intervention/coding-standard": "^1", + "mockery/mockery": "^1.6", + "phpstan/phpstan": "^2.1", + "phpunit/phpunit": "^12.0", + "psr/http-message": "^2" + }, + "suggest": { + "ext-exif": "Recommended to be able to read EXIF data properly." + }, + "type": "library", + "autoload": { + "psr-4": { + "Intervention\\Image\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Oliver Vogel", + "email": "oliver@intervention.io", + "homepage": "https://intervention.io" + } + ], + "description": "PHP Image Processing", + "homepage": "https://image.intervention.io", + "keywords": [ + "gd", + "image", + "imagick", + "resize", + "thumbnail", + "watermark" + ], + "support": { + "issues": "https://github.com/Intervention/image/issues", + "source": "https://github.com/Intervention/image/tree/4.4.1" + }, + "funding": [ + { + "url": "https://paypal.me/interventionio", + "type": "custom" + }, + { + "url": "https://github.com/Intervention", + "type": "github" + }, + { + "url": "https://ko-fi.com/interventionphp", + "type": "ko_fi" + } + ], + "time": "2026-10-30T13:38:01+00:00" + }, { "name": "jean85/pretty-package-versions", "version": "2.1.1", @@ -10400,6 +10544,96 @@ }, "description": "Create sitemap.xml" }, + { + "name": "uwil/storage-laravel", + "version": "1.0.3", + "source": { + "type": "git", + "url": "git@lab.s-web.fr:ldc-web/projets/file-storage-service.git", + "reference": "516350ecf66e80d0ac8a7ef3198cce07e52d515a" + }, + "dist": { + "type": "zip", + "url": "https://lab.s-web.fr/api/v4/projects/284/packages/composer/archives/uwil/storage-laravel.zip?sha=516350ecf66e80d0ac8a7ef3198cce07e52d515a", + "reference": "516350ecf66e80d0ac8a7ef3198cce07e52d515a", + "shasum": "" + }, + "require": { + "illuminate/support": "~13", + "laravel/framework": "~13", + "php": "^8.5" + }, + "require-dev": { + "larastan/larastan": "^3.4", + "laravel/pint": "^1.29", + "orchestra/testbench": "^11.3", + "pestphp/pest": "^5.3", + "php-parallel-lint/php-parallel-lint": "^1.4", + "phpstan/phpstan-mockery": "^2.0", + "slevomat/coding-standard": "^8.22" + }, + "type": "library", + "extra": { + "laravel": { + "aliases": { + "StorageService": "Uwil\\Storage\\Facades\\StorageService" + }, + "providers": [ + "Uwil\\Storage\\StorageServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "Uwil\\Storage\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Uwil\\Storage\\Tests\\": "tests/" + } + }, + "scripts": { + "lint": [ + "./vendor/bin/phpcs && ./vendor/bin/pint --test" + ], + "test": [ + "./vendor/bin/pest" + ], + "format": [ + "./vendor/bin/pint" + ], + "analyze": [ + "./vendor/bin/phpstan analyse" + ], + "lint:fix": [ + "./vendor/bin/phpcbf && ./vendor/bin/pint" + ], + "lint:php": [ + "./vendor/bin/parallel-lint --exclude vendor ." + ], + "lint:pint": [ + "./vendor/bin/pint --test" + ], + "lint:phpcs": [ + "./vendor/bin/phpcs" + ], + "lint:phpstan": [ + "./vendor/bin/phpstan analyse" + ], + "test:coverage": [ + "./vendor/bin/pest --log-junit=junit.xml --coverage --coverage-html=tests/coverage --coverage-clover=coverage.xml" + ] + }, + "license": [ + "MIT" + ], + "description": "Handles file storage", + "support": { + "email": "digital@ldc.fr", + "issues": "https://lab.s-web.fr/ldc-web/projets/storage-laravel/-/issues" + } + }, { "name": "vlucas/phpdotenv", "version": "v5.8.0", diff --git a/config/filesystems.php b/config/filesystems.php index 72e4cb81..c25b0fd5 100644 --- a/config/filesystems.php +++ b/config/filesystems.php @@ -40,15 +40,6 @@ return [ 'report' => false, ], - 'public' => [ - 'driver' => 'local', - 'root' => storage_path('app/public'), - 'url' => rtrim((string) env('APP_URL'), '/') . '/storage', - 'visibility' => 'public', - 'throw' => false, - 'report' => false, - ], - 's3' => [ 'driver' => 's3', 'key' => env('AWS_ACCESS_KEY_ID'), @@ -80,19 +71,4 @@ return [ ], - /* - |-------------------------------------------------------------------------- - | Symbolic Links - |-------------------------------------------------------------------------- - | - | Here you may configure the symbolic links that will be created when the - | `storage:link` Artisan command is executed. The array keys should be - | the locations of the links and the values should be their targets. - | - */ - - 'links' => [ - public_path('storage') => storage_path('app/public'), - ], - ]; diff --git a/config/storage-service.php b/config/storage-service.php new file mode 100644 index 00000000..41e4ff0b --- /dev/null +++ b/config/storage-service.php @@ -0,0 +1,18 @@ + 's3-private', + + 'eligibleDisks' => [ + 's3-public', + 's3-private', + ], + + // NOTE: empty in order to allow transparent file migration. + // 'prefix' => env('STORAGE_SERVICE_PREFIX', 'media'), + 'prefix' => '', + + 'allowedExtensions' => ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'txt', 'doc', 'docx', 'csv', 'mp4', 'webm'], +]; diff --git a/lang/fr/validation.php b/lang/fr/validation.php index 86416c17..88160ff3 100644 --- a/lang/fr/validation.php +++ b/lang/fr/validation.php @@ -402,15 +402,6 @@ return [ 'max' => 'La taille du fichier ne peut pas dépasser :max kilo-octets.', 'mimes' => 'Le fichier doit être de type : :values.', ], - 'has_picture' => [ - 'file_does_not_exist' => ':attribute n\'existe pas dans le système de fichier', - 'file_not_readable' => ':attribute n\'est pas lisible ou a expiré', - 'height_between' => ':attribute la hauteur doit être comprise entre :min et :max', - 'height_equal' => ':attribute la hauteur doit être de :value', - 'weight_max' => ':attribute le poids doit être de max :value Kb', - 'width_between' => ':attribute la largeur doit être comprise entre :min et :max', - 'width_equal' => ':attribute la largeur doit être de :value', - ], 'of_the' => [ 'female' => 'de la ', 'male' => 'du ', diff --git a/shared/Filesystem/TemporaryFileException.php b/shared/Filesystem/TemporaryFileException.php new file mode 100644 index 00000000..c4412a5f --- /dev/null +++ b/shared/Filesystem/TemporaryFileException.php @@ -0,0 +1,9 @@ +rewind(); + $tempFile = $this->openNewTempFile($sourceFile->getFilename()); + + while (! $sourceFile->eof()) { + $chunk = $sourceFile->fread(self::CHUNK_SIZE); + if ($chunk === false) { + throw new TemporaryFileException('Could not read the contents of the source file.'); + } + $this->writeChunk($tempFile, $chunk); + } + + $tempFile->rewind(); + + return $tempFile; + } + + /** + * @param resource $stream + * + * @throws TemporaryFileException if the stream is not valid or readable. + */ + public function newWithStream($stream, string $originalFileName = ''): \SplFileObject + { + if (! is_resource($stream) || get_resource_type($stream) !== 'stream') { + throw new TemporaryFileException('Provided stream is not a valid stream resource.'); + } + + $metadata = stream_get_meta_data($stream); + + if (! str_contains($metadata['mode'], 'r') && ! str_contains($metadata['mode'], '+')) { + throw new TemporaryFileException(sprintf('Stream with mode "%s" is not readable.', $metadata['mode'])); + } + + if ($metadata['seekable'] && ftell($stream) !== 0) { + rewind($stream); + } + + $tempFile = $this->openNewTempFile($originalFileName); + + while (! feof($stream)) { + $chunk = fread($stream, self::CHUNK_SIZE); + if ($chunk === false) { + throw new TemporaryFileException('Could not read from the provided stream.'); + } + $this->writeChunk($tempFile, $chunk); + } + + $tempFile->rewind(); + + return $tempFile; + } + + /** + * @throws TemporaryFileException if the bytes cannot be persisted. + */ + public function newWithBytes(string $contents, string $originalFileName = ''): \SplFileObject + { + $tempFile = $this->openNewTempFile($originalFileName); + $this->writeChunk($tempFile, $contents); + $tempFile->rewind(); + + return $tempFile; + } + + private function openNewTempFile(string $originalFileName): \SplFileObject + { + $path = $this->createTempFilePath($originalFileName); + + try { + return new \SplFileObject($path, 'w+b'); + } catch (\RuntimeException $e) { + throw new TemporaryFileException('Could not open temporary file.', 0, $e); + } + } + + private function writeChunk(\SplFileObject $file, string $chunk): void + { + if ($chunk === '') { + return; + } + + $written = $file->fwrite($chunk); + if ($written === false || $written < strlen($chunk)) { + throw new TemporaryFileException('Could not persist temporary file contents.'); + } + } + + private function createTempFilePath(string $originalName): string + { + $baseTempPath = tempnam(sys_get_temp_dir(), 'tmp_'); + if ($baseTempPath === false) { + throw new TemporaryFileException('Could not create a temporary file path.'); + } + + $rawExtension = pathinfo($originalName, PATHINFO_EXTENSION); + $extension = preg_replace('/[^a-zA-Z0-9_-]/', '', $rawExtension) ?? ''; + + if ($extension !== '') { + $targetPath = $baseTempPath . '.' . $extension; + if (! rename($baseTempPath, $targetPath)) { + @unlink($baseTempPath); + throw new TemporaryFileException('Could not rename temporary file with extension.'); + } + $baseTempPath = $targetPath; + } + + $this->temporaryFilePaths[] = $baseTempPath; + + return $baseTempPath; + } + + public function __destruct() + { + foreach ($this->temporaryFilePaths as $path) { + if (is_file($path)) { + @unlink($path); + } + } + + $this->temporaryFilePaths = []; + } +} diff --git a/tests/Integration/WithApp/Helpers/FileStorageHelperTest.php b/tests/Integration/WithApp/Helpers/FileStorageHelperTest.php deleted file mode 100644 index 5245c216..00000000 --- a/tests/Integration/WithApp/Helpers/FileStorageHelperTest.php +++ /dev/null @@ -1,139 +0,0 @@ -toBe('my-fancy-file.PNG') - ->and($sanitized)->toBe('inv-lid-name.jpg'); -}); - -it('extracts href/src/url files from html', function (): void { - // GIVEN - $html = <<<'HTML' -
- A - - -
-HTML; - - // WHEN - $files = FileStorageHelper::findFilesInHtml($html); - - // THEN - expect($files)->toHaveCount(3) - ->and($files[0])->toContain('file-a.pdf') - ->and($files[1])->toContain('file-b.png') - ->and($files[2])->toContain('file-c.jpg'); -}); - -it('filters uploaded files that exist on public disk', function (): void { - // GIVEN - Storage::fake('public'); - Storage::disk('public')->put('modelfiles/orders/26/03/04/aa/file-1.png', 'ok'); - - $urls = [ - '/storage/modelfiles/orders/26/03/04/aa/file-1.png', - '/storage/modelfiles/orders/26/03/04/aa/file-missing.png', - 'https://other.test/storage/modelfiles/orders/26/03/04/aa/file-1.png', - '/uploads/file.jpg', - ]; - - // WHEN - $filtered = FileStorageHelper::onlyUploadedFilesWithFileStorageHelper($urls); - - // THEN - expect($filtered)->toHaveCount(2) - ->and($filtered)->toContain('/storage/modelfiles/orders/26/03/04/aa/file-1.png') - ->and($filtered)->toContain('https://other.test/storage/modelfiles/orders/26/03/04/aa/file-1.png'); -}); - -it('removes old files that are no longer referenced', function (): void { - // GIVEN - Storage::fake('public'); - - $keptPath = 'modelfiles/orders/26/03/04/aa/keep.png'; - $removedPath = 'modelfiles/orders/26/03/04/aa/remove.png'; - - Storage::disk('public')->put($keptPath, 'keep'); - Storage::disk('public')->put($removedPath, 'remove'); - - $oldFiles = [ - '/storage/' . $keptPath, - '/storage/' . $removedPath, - ]; - $newFiles = [ - '/storage/' . $keptPath, - ]; - - // WHEN - FileStorageHelper::removeOldFiles($oldFiles, $newFiles); - - // THEN - expect(Storage::disk('public')->exists($keptPath))->toBeTrue() - ->and(Storage::disk('public')->exists($removedPath))->toBeFalse(); -}); - -it('returns string input as-is when storing file with string path', function (): void { - // GIVEN - /** @var Model $model */ - $model = new Product(); - $existingPath = '/storage/modelfiles/orders/26/03/04/ab/existing.pdf'; - - // WHEN - $stored = FileStorageHelper::storeFile($model, $existingPath); - - // THEN - expect($stored)->toBe($existingPath); -}); - -it('removes file from model attribute when prefixed by storage', function (): void { - // GIVEN - Storage::fake('public'); - $path = 'modelfiles/orders/26/03/04/aa/model-file.png'; - Storage::disk('public')->put($path, 'file-content'); - - $product = new Product(); - $product->picture = '/storage/' . $path; - - // WHEN - FileStorageHelper::removeFile($product, 'picture'); - - // THEN - expect(Storage::disk('public')->exists($path))->toBeFalse(); -}); - -it('removes old model file only when attribute changed', function (): void { - // GIVEN - Storage::fake('public'); - $oldPath = 'modelfiles/orders/26/03/04/aa/old.png'; - $newPath = 'modelfiles/orders/26/03/04/aa/new.png'; - - Storage::disk('public')->put($oldPath, 'old-content'); - - $product = new Product(); - $product->setRawAttributes([ - 'picture' => '/storage/' . $oldPath, - ], true); - $product->picture = '/storage/' . $newPath; - - // WHEN - FileStorageHelper::removeOldFile($product, 'picture'); - - // THEN - expect(Storage::disk('public')->exists($oldPath))->toBeFalse(); -}); diff --git a/tests/Integration/WithApp/Helpers/ToolboxHelperCoreHarness.php b/tests/Integration/WithApp/Helpers/ToolboxHelperCoreHarness.php deleted file mode 100644 index 81841045..00000000 --- a/tests/Integration/WithApp/Helpers/ToolboxHelperCoreHarness.php +++ /dev/null @@ -1,20 +0,0 @@ -toBeFalse(); @@ -22,7 +21,7 @@ it('replaces recursively in nested array subject', function (): void { $subject = ['a.b', ['a.b', 'z']]; // WHEN - $result = ToolboxHelperCoreHarness::mbReplace('.', '-', $subject, $count); + $result = ToolboxHelperCore::mbReplace('.', '-', $subject, $count); // THEN expect($result)->toBe(['a-b', ['a-b', 'z']]) @@ -34,7 +33,7 @@ it('replaces with search array and scalar replacement', function (): void { $count = 0; // WHEN - $result = ToolboxHelperCoreHarness::mbReplace(['ab', 'cd'], '_', 'ab-cd', $count); + $result = ToolboxHelperCore::mbReplace(['ab', 'cd'], '_', 'ab-cd', $count); // THEN expect($result)->toBe('_-_'); @@ -45,42 +44,8 @@ it('replaces with paired search and replace arrays', function (): void { $count = 0; // WHEN - $result = ToolboxHelperCoreHarness::mbReplace(['ab', 'cd'], ['X', 'Y'], 'ab-cd', $count); + $result = ToolboxHelperCore::mbReplace(['ab', 'cd'], ['X', 'Y'], 'ab-cd', $count); // THEN expect($result)->toBe('X-Y'); }); - -it('resolves full path and mime type without storage disk', function (): void { - // GIVEN - $tmpFile = tempnam(sys_get_temp_dir(), 'tbx-'); - expect($tmpFile)->toBeString(); - file_put_contents((string) $tmpFile, 'hello'); - - // WHEN - $fullPath = ToolboxHelperCoreHarness::exposeGetUploadedFileFullPath((string) $tmpFile, false); - $mimeType = ToolboxHelperCoreHarness::exposeGetUploadedFileMimeType((string) $tmpFile, false); - - // THEN - expect($fullPath)->toBe(realpath((string) $tmpFile) ?: (string) $tmpFile) - ->and($mimeType)->toBeString(); - - unlink((string) $tmpFile); -}); - -it('resolves full path and mime type through storage disk', function (): void { - // GIVEN - $path = 'tests/toolbox-core/demo.txt'; - Storage::disk()->put($path, 'hello world'); - - // WHEN - $fullPath = ToolboxHelperCoreHarness::exposeGetUploadedFileFullPath($path, true); - $mimeType = ToolboxHelperCoreHarness::exposeGetUploadedFileMimeType($path, true); - - // THEN - expect($fullPath)->toBeString() - ->and($fullPath)->toContain('demo.txt') - ->and($mimeType)->toBeString(); - - Storage::disk()->delete($path); -}); diff --git a/tests/Unit/Services/ImageOptimizerServiceTest.php b/tests/Unit/Services/ImageOptimizerServiceTest.php new file mode 100644 index 00000000..e2ef6751 --- /dev/null +++ b/tests/Unit/Services/ImageOptimizerServiceTest.php @@ -0,0 +1,57 @@ +image('picture.jpg', 800, 600); + + // WHEN + $optimized = $service->optimize($file, quality: 70); + $path = $optimized->getRealPath(); + $optimized->rewind(); + $content = $optimized->fread(16); + + // THEN + expect($optimized)->toBeInstanceOf(\SplFileObject::class) + ->and($path)->not->toBeFalse() + ->and(file_exists($path))->toBeTrue() + ->and(pathinfo($path, PATHINFO_EXTENSION))->toBe('jpg') + ->and($content)->toBeString(); + }); + + it('creates a real temp file for non-image uploads with a readable path', function () use (&$service): void { + // GIVEN + $pdf = UploadedFile::fake()->create('document.pdf', 250, 'application/pdf'); + + // WHEN + $result = $service->optimize($pdf); + $path = $result->getRealPath(); + $result->rewind(); + $content = $result->fread(16); + + // THEN + expect($result)->toBeInstanceOf(\SplFileObject::class) + ->and($path)->not->toBeFalse() + ->and(file_exists($path))->toBeTrue() + ->and(pathinfo($path, PATHINFO_EXTENSION))->toBe('pdf') + ->and($content)->toBeString(); + }); +}); From cfba7f47568d9ca41db67e99201e202e8a9f0b10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Sat, 14 Nov 2026 16:06:12 +0100 Subject: [PATCH 011/183] refactor(storage): migrate media models, basket value objects and CQS actions to S3 --- app/Casts/OrderLineProductCast.php | 5 +- app/Cqs/Actions/Contact/SubmitContactForm.php | 59 +++++ .../Contact/SubmitContactFormInput.php | 32 +++ app/Cqs/Actions/Products/CreateProduct.php | 27 ++- .../Actions/Products/CreateProductInput.php | 5 +- app/Cqs/Actions/Products/DeleteProduct.php | 33 ++- .../Actions/Products/DeleteProductInput.php | 4 +- app/Cqs/Actions/Products/UpdateProduct.php | 31 ++- .../Actions/Products/UpdateProductInput.php | 10 +- app/Cqs/Actions/Ranges/CreateRange.php | 23 +- app/Cqs/Actions/Ranges/CreateRangeInput.php | 2 +- app/Cqs/Actions/Ranges/DeleteRange.php | 19 +- app/Cqs/Actions/Ranges/UpdateRange.php | 23 +- app/Cqs/Actions/Ranges/UpdateRangeInput.php | 3 +- app/Cqs/Actions/Slides/CreateSlide.php | 23 +- app/Cqs/Actions/Slides/CreateSlideInput.php | 2 +- app/Cqs/Actions/Slides/DeleteSlide.php | 15 ++ app/Cqs/Actions/Slides/UpdateSlide.php | 23 +- app/Cqs/Actions/Slides/UpdateSlideInput.php | 3 +- app/Dto/DiscountProductDto.php | 6 +- app/Dto/RangeDto.php | 2 +- app/Dto/SlideDto.php | 2 +- .../Fo/Pages/ContactController.php | 8 +- .../Fo/Ajax/BasketProductResource.php | 2 +- app/Mail/SendContactMail.php | 5 +- app/Models/Product.php | 17 +- app/Models/Range.php | 11 +- app/Models/Slide.php | 10 +- database/factories/SlideFactory.php | 2 +- domain/Models/ValueObjects/BasketProduct.php | 3 +- .../Models/ValueObjects/OrderLineProduct.php | 3 +- .../Adapters/Serializers/BasketSerializer.php | 8 +- .../views/bo/products/index-list.blade.php | 4 +- .../views/bo/ranges/index-list.blade.php | 3 +- .../views/bo/slides/index-list.blade.php | 2 +- resources/views/bo/tags/index-list.blade.php | 1 + .../views/fo/home-parts/ranges.blade.php | 2 +- .../fo/home-parts/sliders/main.blade.php | 2 +- .../Fo/Pages/ContactControllerTest.php | 42 ++++ .../Actions/Contact/SubmitContactFormTest.php | 94 ++++++++ .../App/Actions/Ranges/CreateRangeTest.php | 25 +- .../App/Actions/Ranges/DeleteRangeTest.php | 36 ++- .../App/Actions/Ranges/UpdateRangeTest.php | 25 +- .../App/Actions/Slides/CreateSlideTest.php | 22 +- .../App/Actions/Slides/DeleteSlideTest.php | 52 ++++- .../App/Actions/Slides/UpdateSlideTest.php | 81 ++++++- .../WithApp/App/Dto/SlideDtoTest.php | 32 ++- .../Casts/OrderLineProductCastTest.php | 6 +- .../SessionBasketRepositoryTest.php | 7 +- .../Actions/Slides/CreateSlideInputTest.php | 9 +- .../App/Casts/OrderLineProductCastTest.php | 219 +++++++++--------- .../Domain/Models/Entities/BasketTest.php | 9 +- .../Unit/Domain/Models/Entities/OrderTest.php | 3 +- .../ValueObjects/OrderLineProductTest.php | 5 +- .../Domain/Services/BasketServiceTest.php | 3 +- .../Unit/Domain/Services/OrderServiceTest.php | 6 +- .../SessionBasketRepositoryTest.php | 217 ++++++++--------- .../Serializers/BasketSerializerTest.php | 3 +- 58 files changed, 1002 insertions(+), 329 deletions(-) create mode 100644 app/Cqs/Actions/Contact/SubmitContactForm.php create mode 100644 app/Cqs/Actions/Contact/SubmitContactFormInput.php create mode 100644 tests/Integration/WithApp/App/Actions/Contact/SubmitContactFormTest.php diff --git a/app/Casts/OrderLineProductCast.php b/app/Casts/OrderLineProductCast.php index 916c5e2f..f1958d37 100644 --- a/app/Casts/OrderLineProductCast.php +++ b/app/Casts/OrderLineProductCast.php @@ -16,6 +16,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Arr; use Ramsey\Uuid\Uuid; use Symfony\Component\Uid\Uuid as SymfonyUuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; /** * @implements CastsAttributes @@ -58,7 +59,7 @@ class OrderLineProductCast implements CastsAttributes discountedPrice: new MoneyCast()->get($model, 'discounted_price', Arr::get($data, 'discounted_price'), []), priceKgTtc: new MoneyCast()->get($model, 'price_kg_ttc', Arr::get($data, 'price_kg_ttc'), []), taxRate: TaxRate::fromPercent($taxRate), - picture: is_string($picture = Arr::get($data, 'picture')) ? $picture : null, + picture: is_string($picture = Arr::get($data, 'picture')) ? new StorageFilePath($picture) : null, ); } @@ -99,7 +100,7 @@ class OrderLineProductCast implements CastsAttributes [] ), 'tax_rate' => $value->taxRate->percent(), - 'picture' => $value->picture, + 'picture' => $value->picture?->value, ], \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES); } } diff --git a/app/Cqs/Actions/Contact/SubmitContactForm.php b/app/Cqs/Actions/Contact/SubmitContactForm.php new file mode 100644 index 00000000..3414fc79 --- /dev/null +++ b/app/Cqs/Actions/Contact/SubmitContactForm.php @@ -0,0 +1,59 @@ + + */ +final class SubmitContactForm implements Action +{ + public function __construct( + private readonly StorageService $storageService, + private readonly PrivateS3Disk $privateS3Disk, + ) { + } + + /** + * @param \App\Cqs\Actions\Contact\SubmitContactFormInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): ContactFormData + { + Assert::isInstanceOf($input, SubmitContactFormInput::class); + + $attachedFile = null; + + if ($input->file instanceof UploadedFile && $input->file->isValid()) { + $storedPath = $this->storageService->storeUploadedOntoDisk($input->file, $this->privateS3Disk->disk); + $attachedFile = new AttachedFile( + path: $storedPath->value, + originalName: $input->file->getClientOriginalName(), + mimeType: $input->file->getMimeType() ?? 'application/octet-stream', + ); + } + + return new ContactFormData( + lastName: $input->lastName, + firstName: $input->firstName, + email: $input->email, + subject: $input->subject, + message: $input->message, + orderRef: $input->orderRef, + file: $attachedFile, + ); + } +} diff --git a/app/Cqs/Actions/Contact/SubmitContactFormInput.php b/app/Cqs/Actions/Contact/SubmitContactFormInput.php new file mode 100644 index 00000000..55aaad78 --- /dev/null +++ b/app/Cqs/Actions/Contact/SubmitContactFormInput.php @@ -0,0 +1,32 @@ +lastName)); + Assert::stringNotEmpty(trim($this->firstName)); + Assert::stringNotEmpty(trim($this->email)); + Assert::stringNotEmpty(trim($this->subject)); + Assert::stringNotEmpty(trim($this->message)); + + if ($this->orderRef !== null) { + Assert::stringNotEmpty(trim($this->orderRef)); + } + } +} diff --git a/app/Cqs/Actions/Products/CreateProduct.php b/app/Cqs/Actions/Products/CreateProduct.php index 8cdf4f30..5eaaeff4 100644 --- a/app/Cqs/Actions/Products/CreateProduct.php +++ b/app/Cqs/Actions/Products/CreateProduct.php @@ -6,10 +6,15 @@ namespace App\Cqs\Actions\Products; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; use App\Models\Product; use App\Models\Tag; +use App\Services\ImageOptimizerService; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Date; use Illuminate\Support\Str; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; /** @@ -17,6 +22,13 @@ use Webmozart\Assert\Assert; */ final class CreateProduct implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Products\CreateProductInput $input */ @@ -44,14 +56,14 @@ final class CreateProduct implements Action $product->star = $input->star; $product->status = $input->status; - if ($input->picture !== null) { - $product->setAttribute('picture', $input->picture); + if ($input->picture instanceof UploadedFile) { + $product->picture = $this->storeFile($input->picture); } $product->picture_alt = (string) $input->pictureAlt; $product->picture_title = (string) $input->pictureTitle; - if ($input->pictureLarge !== null) { - $product->setAttribute('picture_large', $input->pictureLarge); + if ($input->pictureLarge instanceof UploadedFile) { + $product->picture_large = $this->storeFile($input->pictureLarge); } $product->picture_large_alt = (string) $input->pictureLargeAlt; $product->picture_large_title = (string) $input->pictureLargeTitle; @@ -106,4 +118,11 @@ final class CreateProduct implements Action $product->products()->sync($syncData); } + + protected function storeFile(UploadedFile $file): StorageFilePath + { + $optimized = $this->imageOptimizerService->optimize($file); + + return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk); + } } diff --git a/app/Cqs/Actions/Products/CreateProductInput.php b/app/Cqs/Actions/Products/CreateProductInput.php index f2d4748c..79109ae1 100644 --- a/app/Cqs/Actions/Products/CreateProductInput.php +++ b/app/Cqs/Actions/Products/CreateProductInput.php @@ -11,6 +11,7 @@ use Domain\Enums\SellUnit; use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; +use Illuminate\Http\UploadedFile; use Money\Money; use Webmozart\Assert\Assert; @@ -38,10 +39,10 @@ final readonly class CreateProductInput implements ActionInput public ?CarbonInterface $orderableEnd = null, public bool $star = false, public bool $status = false, - public mixed $picture = null, + public ?UploadedFile $picture = null, public ?string $pictureAlt = null, public ?string $pictureTitle = null, - public mixed $pictureLarge = null, + public ?UploadedFile $pictureLarge = null, public ?string $pictureLargeAlt = null, public ?string $pictureLargeTitle = null, public array $tags = [], diff --git a/app/Cqs/Actions/Products/DeleteProduct.php b/app/Cqs/Actions/Products/DeleteProduct.php index 8af950c1..290fc501 100644 --- a/app/Cqs/Actions/Products/DeleteProduct.php +++ b/app/Cqs/Actions/Products/DeleteProduct.php @@ -6,6 +6,9 @@ namespace App\Cqs\Actions\Products; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; +use App\Models\Product; +use Uwil\Storage\Contracts\StorageService; use Webmozart\Assert\Assert; /** @@ -13,6 +16,12 @@ use Webmozart\Assert\Assert; */ final class DeleteProduct implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + ) { + } + /** * @param \App\Cqs\Actions\Products\DeleteProductInput $input */ @@ -21,6 +30,28 @@ final class DeleteProduct implements Action { Assert::isInstanceOf($input, DeleteProductInput::class); - return (bool) $input->product->deleteOrFail(); + $product = Product::query() + ->where('id', $input->productId->value->toString()) + ->first(); + + if (! $product) { + return false; + } + + if ( + $product->picture && $this->storageService + ->fileExistsOnDisk($product->picture, $this->s3Disk->disk) + ) { + $this->storageService->removeFromDisk($product->picture, $this->s3Disk->disk); + } + + if ( + $product->picture_large && $this->storageService + ->fileExistsOnDisk($product->picture_large, $this->s3Disk->disk) + ) { + $this->storageService->removeFromDisk($product->picture_large, $this->s3Disk->disk); + } + + return (bool) $product->deleteOrFail(); } } diff --git a/app/Cqs/Actions/Products/DeleteProductInput.php b/app/Cqs/Actions/Products/DeleteProductInput.php index 43a1f2cf..bd878552 100644 --- a/app/Cqs/Actions/Products/DeleteProductInput.php +++ b/app/Cqs/Actions/Products/DeleteProductInput.php @@ -5,12 +5,12 @@ declare(strict_types=1); namespace App\Cqs\Actions\Products; use App\Contracts\ActionInput; -use App\Models\Product; +use Domain\Models\ValueObjects\Entities\ProductId; final readonly class DeleteProductInput implements ActionInput { public function __construct( - public Product $product, + public ProductId $productId, ) { } } diff --git a/app/Cqs/Actions/Products/UpdateProduct.php b/app/Cqs/Actions/Products/UpdateProduct.php index a4acab0b..dc6e5060 100644 --- a/app/Cqs/Actions/Products/UpdateProduct.php +++ b/app/Cqs/Actions/Products/UpdateProduct.php @@ -6,10 +6,15 @@ namespace App\Cqs\Actions\Products; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; use App\Models\Product; use App\Models\Tag; +use App\Services\ImageOptimizerService; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Date; use Illuminate\Support\Str; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; /** @@ -17,6 +22,13 @@ use Webmozart\Assert\Assert; */ final class UpdateProduct implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Products\UpdateProductInput $input */ @@ -25,7 +37,9 @@ final class UpdateProduct implements Action { Assert::isInstanceOf($input, UpdateProductInput::class); - $product = $input->product; + $product = Product::query() + ->where('id', $input->productId->value->toString()) + ->firstOrFail(); $product->name = $input->name; $product->short_description = $input->shortDescription; $product->description = $input->description; @@ -44,14 +58,14 @@ final class UpdateProduct implements Action $product->star = $input->star; $product->status = $input->status; - if ($input->picture !== null) { - $product->setAttribute('picture', $input->picture); + if ($input->picture instanceof UploadedFile) { + $product->setAttribute('picture', $this->storeFile($input->picture)); } $product->picture_alt = (string) $input->pictureAlt; $product->picture_title = (string) $input->pictureTitle; - if ($input->pictureLarge !== null) { - $product->setAttribute('picture_large', $input->pictureLarge); + if ($input->pictureLarge instanceof UploadedFile) { + $product->setAttribute('picture_large', $this->storeFile($input->pictureLarge)); } $product->picture_large_alt = (string) $input->pictureLargeAlt; $product->picture_large_title = (string) $input->pictureLargeTitle; @@ -106,4 +120,11 @@ final class UpdateProduct implements Action $product->products()->sync($syncData); } + + protected function storeFile(UploadedFile $file): StorageFilePath + { + $optimized = $this->imageOptimizerService->optimize($file); + + return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk); + } } diff --git a/app/Cqs/Actions/Products/UpdateProductInput.php b/app/Cqs/Actions/Products/UpdateProductInput.php index b3f75990..79163d45 100644 --- a/app/Cqs/Actions/Products/UpdateProductInput.php +++ b/app/Cqs/Actions/Products/UpdateProductInput.php @@ -5,14 +5,16 @@ declare(strict_types=1); namespace App\Cqs\Actions\Products; use App\Contracts\ActionInput; -use App\Models\Product; use Carbon\CarbonInterface; use Domain\Enums\ProductBrand; use Domain\Enums\SellUnit; use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; +use Domain\Models\ValueObjects\Entities\ProductId; +use Illuminate\Http\UploadedFile; use Money\Money; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; final readonly class UpdateProductInput implements ActionInput @@ -22,7 +24,7 @@ final readonly class UpdateProductInput implements ActionInput * @param list $associatedProductsIds */ public function __construct( - public Product $product, + public ProductId $productId, public string $name, public string $shortDescription, public string $description, @@ -40,10 +42,10 @@ final readonly class UpdateProductInput implements ActionInput public ?CarbonInterface $orderableEnd = null, public bool $star = false, public bool $status = false, - public mixed $picture = null, + public UploadedFile | StorageFilePath | null $picture = null, public ?string $pictureAlt = null, public ?string $pictureTitle = null, - public mixed $pictureLarge = null, + public UploadedFile | StorageFilePath | null $pictureLarge = null, public ?string $pictureLargeAlt = null, public ?string $pictureLargeTitle = null, public array $tags = [], diff --git a/app/Cqs/Actions/Ranges/CreateRange.php b/app/Cqs/Actions/Ranges/CreateRange.php index 634d6ad1..ddaeaf05 100644 --- a/app/Cqs/Actions/Ranges/CreateRange.php +++ b/app/Cqs/Actions/Ranges/CreateRange.php @@ -6,7 +6,12 @@ namespace App\Cqs\Actions\Ranges; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; use App\Models\Range; +use App\Services\ImageOptimizerService; +use Illuminate\Http\UploadedFile; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; /** @@ -14,6 +19,13 @@ use Webmozart\Assert\Assert; */ final class CreateRange implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Ranges\CreateRangeInput $input */ @@ -30,8 +42,8 @@ final class CreateRange implements Action 'status' => $input->status, ]; - if ($input->picture !== null) { - $attributes['picture'] = $input->picture; + if ($input->picture instanceof UploadedFile) { + $attributes['picture'] = $this->storeFile($input->picture); } $range = new Range(); @@ -40,4 +52,11 @@ final class CreateRange implements Action return $range; } + + protected function storeFile(UploadedFile $file): StorageFilePath + { + $optimized = $this->imageOptimizerService->optimize($file); + + return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk); + } } diff --git a/app/Cqs/Actions/Ranges/CreateRangeInput.php b/app/Cqs/Actions/Ranges/CreateRangeInput.php index 6031b01e..9e015949 100644 --- a/app/Cqs/Actions/Ranges/CreateRangeInput.php +++ b/app/Cqs/Actions/Ranges/CreateRangeInput.php @@ -14,7 +14,7 @@ final readonly class CreateRangeInput implements ActionInput public function __construct( public string $name, public ?string $description, - public UploadedFile | string | null $picture, + public ?UploadedFile $picture, public PictureMetadata $pictureMetadata, public bool $status, ) { diff --git a/app/Cqs/Actions/Ranges/DeleteRange.php b/app/Cqs/Actions/Ranges/DeleteRange.php index 228248fb..3c2a84f4 100644 --- a/app/Cqs/Actions/Ranges/DeleteRange.php +++ b/app/Cqs/Actions/Ranges/DeleteRange.php @@ -6,6 +6,8 @@ namespace App\Cqs\Actions\Ranges; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; +use Uwil\Storage\Contracts\StorageService; use Webmozart\Assert\Assert; /** @@ -13,6 +15,12 @@ use Webmozart\Assert\Assert; */ final class DeleteRange implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + ) { + } + /** * @param \App\Cqs\Actions\Ranges\DeleteRangeInput $input */ @@ -21,6 +29,15 @@ final class DeleteRange implements Action { Assert::isInstanceOf($input, DeleteRangeInput::class); - return (bool) $input->range->deleteOrFail(); + $deletion = (bool) $input->range->deleteOrFail(); + + if ( + $deletion && $input->range->picture && $this->storageService + ->fileExistsOnDisk($input->range->picture, $this->s3Disk->disk) + ) { + $this->storageService->removeFromDisk($input->range->picture, $this->s3Disk->disk); + } + + return $deletion; } } diff --git a/app/Cqs/Actions/Ranges/UpdateRange.php b/app/Cqs/Actions/Ranges/UpdateRange.php index 5e37f58a..ccb9574b 100644 --- a/app/Cqs/Actions/Ranges/UpdateRange.php +++ b/app/Cqs/Actions/Ranges/UpdateRange.php @@ -6,7 +6,12 @@ namespace App\Cqs\Actions\Ranges; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; use App\Models\Range; +use App\Services\ImageOptimizerService; +use Illuminate\Http\UploadedFile; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; /** @@ -14,6 +19,13 @@ use Webmozart\Assert\Assert; */ final class UpdateRange implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Ranges\UpdateRangeInput $input */ @@ -30,8 +42,8 @@ final class UpdateRange implements Action 'status' => $input->status, ]; - if ($input->picture !== null) { - $attributes['picture'] = $input->picture; + if ($input->picture instanceof UploadedFile) { + $attributes['picture'] = $this->storeFile($input->picture); } $range = $input->range; @@ -40,4 +52,11 @@ final class UpdateRange implements Action return $range; } + + protected function storeFile(UploadedFile $file): StorageFilePath + { + $optimized = $this->imageOptimizerService->optimize($file); + + return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk); + } } diff --git a/app/Cqs/Actions/Ranges/UpdateRangeInput.php b/app/Cqs/Actions/Ranges/UpdateRangeInput.php index 496dc782..0acbc1f4 100644 --- a/app/Cqs/Actions/Ranges/UpdateRangeInput.php +++ b/app/Cqs/Actions/Ranges/UpdateRangeInput.php @@ -8,6 +8,7 @@ use App\Contracts\ActionInput; use App\Models\Range; use Domain\Models\ValueObjects\PictureMetadata; use Illuminate\Http\UploadedFile; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; final readonly class UpdateRangeInput implements ActionInput @@ -16,7 +17,7 @@ final readonly class UpdateRangeInput implements ActionInput public Range $range, public string $name, public ?string $description, - public UploadedFile | string | null $picture, + public UploadedFile | StorageFilePath | null $picture, public PictureMetadata $pictureMetadata, public bool $status, ) { diff --git a/app/Cqs/Actions/Slides/CreateSlide.php b/app/Cqs/Actions/Slides/CreateSlide.php index 92823dc1..850fd2a8 100644 --- a/app/Cqs/Actions/Slides/CreateSlide.php +++ b/app/Cqs/Actions/Slides/CreateSlide.php @@ -6,8 +6,13 @@ namespace App\Cqs\Actions\Slides; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; use App\Models\Slide; +use App\Services\ImageOptimizerService; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Carbon; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; /** @@ -15,6 +20,13 @@ use Webmozart\Assert\Assert; */ final class CreateSlide implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Slides\CreateSlideInput $input */ @@ -36,8 +48,8 @@ final class CreateSlide implements Action 'date_end' => $input->period->end !== null ? Carbon::instance($input->period->end) : null, ]; - if ($input->picture !== null) { - $attributes['picture'] = $input->picture; + if ($input->picture instanceof UploadedFile) { + $attributes['picture'] = $this->storeFile($input->picture); } $slide = new Slide(); @@ -46,4 +58,11 @@ final class CreateSlide implements Action return $slide; } + + protected function storeFile(UploadedFile $file): StorageFilePath + { + $optimized = $this->imageOptimizerService->optimize($file); + + return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk); + } } diff --git a/app/Cqs/Actions/Slides/CreateSlideInput.php b/app/Cqs/Actions/Slides/CreateSlideInput.php index 9cf21571..17212755 100644 --- a/app/Cqs/Actions/Slides/CreateSlideInput.php +++ b/app/Cqs/Actions/Slides/CreateSlideInput.php @@ -14,7 +14,7 @@ final readonly class CreateSlideInput implements ActionInput public function __construct( public string $title, public ?string $text = null, - public UploadedFile | string | null $picture = null, + public ?UploadedFile $picture = null, public ?string $pictureAlt = null, public ?string $pictureTitle = null, public ?string $link = null, diff --git a/app/Cqs/Actions/Slides/DeleteSlide.php b/app/Cqs/Actions/Slides/DeleteSlide.php index dc9f8e96..03bbb39c 100644 --- a/app/Cqs/Actions/Slides/DeleteSlide.php +++ b/app/Cqs/Actions/Slides/DeleteSlide.php @@ -6,6 +6,8 @@ namespace App\Cqs\Actions\Slides; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; +use Uwil\Storage\Contracts\StorageService; use Webmozart\Assert\Assert; /** @@ -13,6 +15,12 @@ use Webmozart\Assert\Assert; */ final class DeleteSlide implements Action { + public function __construct( + private readonly StorageService $storageService, + private readonly PublicS3Disk $s3Disk, + ) { + } + /** * @param \App\Cqs\Actions\Slides\DeleteSlideInput $input */ @@ -21,6 +29,13 @@ final class DeleteSlide implements Action { Assert::isInstanceOf($input, DeleteSlideInput::class); + if ( + $input->slide->picture && $this->storageService + ->fileExistsOnDisk($input->slide->picture, $this->s3Disk->disk) + ) { + $this->storageService->removeFromDisk($input->slide->picture, $this->s3Disk->disk); + } + return (bool) $input->slide->deleteOrFail(); } } diff --git a/app/Cqs/Actions/Slides/UpdateSlide.php b/app/Cqs/Actions/Slides/UpdateSlide.php index 075af4e7..16f83cf3 100644 --- a/app/Cqs/Actions/Slides/UpdateSlide.php +++ b/app/Cqs/Actions/Slides/UpdateSlide.php @@ -6,8 +6,13 @@ namespace App\Cqs\Actions\Slides; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Lib\PublicS3Disk; use App\Models\Slide; +use App\Services\ImageOptimizerService; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Carbon; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; /** @@ -15,6 +20,13 @@ use Webmozart\Assert\Assert; */ final class UpdateSlide implements Action { + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Slides\UpdateSlideInput $input */ @@ -36,8 +48,8 @@ final class UpdateSlide implements Action 'date_end' => $input->period->end !== null ? Carbon::instance($input->period->end) : null, ]; - if ($input->picture !== null) { - $attributes['picture'] = $input->picture; + if ($input->picture instanceof UploadedFile) { + $attributes['picture'] = $this->storeFile($input->picture); } $slide = $input->slide; @@ -46,4 +58,11 @@ final class UpdateSlide implements Action return $slide; } + + protected function storeFile(UploadedFile $file): StorageFilePath + { + $optimized = $this->imageOptimizerService->optimize($file); + + return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk); + } } diff --git a/app/Cqs/Actions/Slides/UpdateSlideInput.php b/app/Cqs/Actions/Slides/UpdateSlideInput.php index d2c71a53..b0f879a4 100644 --- a/app/Cqs/Actions/Slides/UpdateSlideInput.php +++ b/app/Cqs/Actions/Slides/UpdateSlideInput.php @@ -8,6 +8,7 @@ use App\Contracts\ActionInput; use App\Models\Slide; use Domain\Models\ValueObjects\DatePeriod; use Illuminate\Http\UploadedFile; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; final readonly class UpdateSlideInput implements ActionInput @@ -16,7 +17,7 @@ final readonly class UpdateSlideInput implements ActionInput public Slide $slide, public string $title, public ?string $text = null, - public UploadedFile | string | null $picture = null, + public UploadedFile | StorageFilePath | null $picture = null, public ?string $pictureAlt = null, public ?string $pictureTitle = null, public ?string $link = null, diff --git a/app/Dto/DiscountProductDto.php b/app/Dto/DiscountProductDto.php index 432866d7..54c80c98 100644 --- a/app/Dto/DiscountProductDto.php +++ b/app/Dto/DiscountProductDto.php @@ -24,12 +24,12 @@ final readonly class DiscountProductDto implements \JsonSerializable, Arrayable return new self( id: (string) $product->id, name: (string) $product->name, - picture: $product->picture, + picture: publicS3Asset($product->picture), ); } /** - * @return array{id: string, name: string} + * @return array{id: string, name: string, picture: ?string} */ #[\Override] public function toArray(): array @@ -42,7 +42,7 @@ final readonly class DiscountProductDto implements \JsonSerializable, Arrayable } /** - * @return array{id: string, name: string} + * @return array{id: string, name: string, picture: ?string} */ #[\Override] public function jsonSerialize(): array diff --git a/app/Dto/RangeDto.php b/app/Dto/RangeDto.php index 3254013c..a25f4125 100644 --- a/app/Dto/RangeDto.php +++ b/app/Dto/RangeDto.php @@ -33,7 +33,7 @@ final readonly class RangeDto implements Arrayable, UrlRoutable name: $range->name, slug: $range->slug, description: $range->description, - picture: is_string($range->picture) ? $range->picture : null, + picture: publicS3Asset($range->picture), picture_alt: $range->picture_alt, picture_title: $range->picture_title, order: $range->order, diff --git a/app/Dto/SlideDto.php b/app/Dto/SlideDto.php index 83827884..a4b781e6 100644 --- a/app/Dto/SlideDto.php +++ b/app/Dto/SlideDto.php @@ -39,7 +39,7 @@ final readonly class SlideDto implements Arrayable, UrlRoutable id: $slide->id, title: $slide->title, text: $slide->text, - picture: is_string($slide->picture) ? $slide->picture : null, + picture: publicS3Asset($slide->picture), picture_alt: $slide->picture_alt, picture_title: $slide->picture_title, link: $slide->link, diff --git a/app/Http/Controllers/Fo/Pages/ContactController.php b/app/Http/Controllers/Fo/Pages/ContactController.php index 28a4982b..7425cad2 100644 --- a/app/Http/Controllers/Fo/Pages/ContactController.php +++ b/app/Http/Controllers/Fo/Pages/ContactController.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Http\Controllers\Fo\Pages; use App\Contracts\Executor; +use App\Cqs\Actions\Contact\SubmitContactForm; use App\Cqs\Queries\Pages\GetPageQuery; use App\Cqs\Queries\Pages\GetPageQueryInput; use App\Cqs\Queries\Shops\GetShopQuery; @@ -61,9 +62,12 @@ class ContactController extends Controller )); } - public function submitForm(ContactFormRequest $request): RedirectResponse + public function submitForm(ContactFormRequest $request, SubmitContactForm $action): RedirectResponse { - $contactData = $request->toValueObject(); + $contactData = $this->executor->execute( + $action, + $request->toSubmitContactFormInput(), + ); Mail::to($this->mailToContact) ->send(new SendContactMail($contactData)); diff --git a/app/Http/Resources/Fo/Ajax/BasketProductResource.php b/app/Http/Resources/Fo/Ajax/BasketProductResource.php index 21ae3f89..9212dc43 100644 --- a/app/Http/Resources/Fo/Ajax/BasketProductResource.php +++ b/app/Http/Resources/Fo/Ajax/BasketProductResource.php @@ -43,7 +43,7 @@ class BasketProductResource extends JsonResource 'slug' => $this->basketProduct->slug, 'picture' => $this->basketProduct->picture ? - url($this->basketProduct->picture) : null, + publicS3Asset($this->basketProduct->picture) : null, 'description' => $this->basketProduct->description, 'weight_variable' => $this->basketProduct->weightVariable, 'discountRate' => $this->basketProduct->discountRate->ratio(), diff --git a/app/Mail/SendContactMail.php b/app/Mail/SendContactMail.php index 3c992e0c..20fc6e6b 100644 --- a/app/Mail/SendContactMail.php +++ b/app/Mail/SendContactMail.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Mail; +use App\Lib\PrivateS3Disk; use Domain\Models\ValueObjects\ContactFormData; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; @@ -88,8 +89,10 @@ class SendContactMail extends Mailable implements ShouldQueue $extension ); + $disk = app()->make(PrivateS3Disk::class)->disk->value; + return [ - Attachment::fromPath($this->data->file->path) + Attachment::fromStorageDisk($disk, $this->data->file->path) ->as($joinedFileName) ->withMime($this->data->file->mimeType), ]; diff --git a/app/Models/Product.php b/app/Models/Product.php index 1921efa3..a2b8a354 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -4,11 +4,11 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\FilePathCast; use App\Casts\MoneyCast; use App\Interfaces\ModelWithOrder; use App\Interfaces\ModelWithStar; use App\Interfaces\ModelWithStatus; -use App\Lib\Helpers\FileStorageHelper; use App\Lib\Helpers\ToolboxHelper; use App\Traits\Models\HasOrder; use App\Traits\Models\HasStar; @@ -42,10 +42,10 @@ use Uwil\Laravel\Redirections\Traits\IsRedirectable; * @property ProductBrand $brand * @property string $description * @property string|null $short_description - * @property string|null $picture + * @property \Uwil\Storage\Lib\ValueObjects\StorageFilePath|null $picture * @property string $picture_alt * @property string $picture_title - * @property string|null $picture_large + * @property \Uwil\Storage\Lib\ValueObjects\StorageFilePath|null $picture_large * @property string $picture_large_alt * @property string $picture_large_title * @property \Money\Money $price @@ -133,20 +133,13 @@ class Product extends Model implements ModelWithOrder, ModelWithStar, ModelWithS self::makeStatusSense($model); self::makeStarSense($model); }); - - static::deleting(function (self $model): void { - FileStorageHelper::removeFile($model, 'picture'); - FileStorageHelper::removeFile($model, 'picture_large'); - }); } private static function manageFields(self $model): void { self::assertNameIsUnique($model->name, $model->id); - $model->slug = Str::slug($model->name); - $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); - $model->picture_large = FileStorageHelper::storeFile($model, $model->picture_large, true); + $model->slug = Str::slug($model->name); if ($model->order === null) { $max = self::query()->max('order'); @@ -165,6 +158,8 @@ class Product extends Model implements ModelWithOrder, ModelWithStar, ModelWithS protected function casts(): array { return [ + 'picture' => FilePathCast::class, + 'picture_large' => FilePathCast::class, 'orderable_start' => 'datetime', 'orderable_end' => 'datetime', 'price' => MoneyCast::class, diff --git a/app/Models/Range.php b/app/Models/Range.php index ec72dd69..b586eae6 100644 --- a/app/Models/Range.php +++ b/app/Models/Range.php @@ -4,9 +4,9 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\FilePathCast; use App\Interfaces\ModelWithOrder; use App\Interfaces\ModelWithStatus; -use App\Lib\Helpers\FileStorageHelper; use App\Lib\Helpers\ToolboxHelper; use App\Traits\Models\HasOrder; use App\Traits\Models\HasStatus; @@ -22,7 +22,7 @@ use Uwil\Laravel\Redirections\Traits\IsRedirectable; * @property string $name * @property string $slug * @property string|null $description - * @property string|null $picture + * @property \Uwil\Storage\Lib\ValueObjects\StorageFilePath|null $picture * @property string $picture_alt * @property string $picture_title * @property bool $status @@ -56,9 +56,6 @@ class Range extends Model implements ModelWithOrder, ModelWithStatus, Redirectab static::updating(function (self $model): void { self::manageFields($model); }); - static::deleting(function (self $model): void { - FileStorageHelper::removeFile($model, 'picture'); - }); } #[\Override] @@ -81,7 +78,6 @@ class Range extends Model implements ModelWithOrder, ModelWithStatus, Redirectab self::assertNameIsUnique($model->name, $model->id); $model->slug = Str::slug($model->name); - $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); if (is_null($model->order)) { $maxOrder = self::query()->max('order'); $model->order = is_numeric($maxOrder) ? (int) $maxOrder + 1 : 0; @@ -105,7 +101,8 @@ class Range extends Model implements ModelWithOrder, ModelWithStatus, Redirectab protected function casts(): array { return [ - 'status' => 'bool', + 'picture' => FilePathCast::class, + 'status' => 'bool', ]; } } diff --git a/app/Models/Slide.php b/app/Models/Slide.php index bef0dd62..b2e7156d 100644 --- a/app/Models/Slide.php +++ b/app/Models/Slide.php @@ -4,9 +4,9 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\FilePathCast; use App\Interfaces\ModelWithOrder; use App\Interfaces\ModelWithStatus; -use App\Lib\Helpers\FileStorageHelper; use App\Traits\Models\HasOrder; use App\Traits\Models\HasStatus; use Illuminate\Contracts\Session\Session; @@ -21,7 +21,7 @@ use Shared\Helpers\DatesHelper; * @property int $id * @property string $title * @property string|null $text - * @property string|null $picture + * @property \Uwil\Storage\Lib\ValueObjects\StorageFilePath|null $picture * @property string|null $picture_alt * @property string|null $picture_title * @property string|null $link_label @@ -77,9 +77,6 @@ class Slide extends Model implements ModelWithOrder, ModelWithStatus self::manageFields($model); self::makeStatusSense($model); }); - static::deleting(function (self $model): void { - FileStorageHelper::removeFile($model, 'picture'); - }); } public function isVisible(): bool @@ -95,8 +92,6 @@ class Slide extends Model implements ModelWithOrder, ModelWithStatus private static function manageFields(self $model): void { - $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); - if ($model->order === null) { $max = self::query()->max('order'); $model->order = is_scalar($max) ? intval($max) + 1 : 1; @@ -120,6 +115,7 @@ class Slide extends Model implements ModelWithOrder, ModelWithStatus protected function casts(): array { return [ + 'picture' => FilePathCast::class, 'link_new_tab' => 'bool', 'connected' => 'bool', 'status' => 'bool', diff --git a/database/factories/SlideFactory.php b/database/factories/SlideFactory.php index a42b0cd6..5c1a68e5 100644 --- a/database/factories/SlideFactory.php +++ b/database/factories/SlideFactory.php @@ -37,7 +37,7 @@ class SlideFactory extends Factory 'link_label' => fake()->words(2, true), 'link_new_tab' => fake()->boolean(), 'connected' => fake()->boolean(20), - 'picture' => fake()->imageUrl(1920, 1080, 'nature'), + 'picture' => 'slides/' . fake()->slug() . '.jpg', 'picture_alt' => fake()->sentence(3), 'picture_title' => fake()->sentence(3), 'status' => true, diff --git a/domain/Models/ValueObjects/BasketProduct.php b/domain/Models/ValueObjects/BasketProduct.php index 390b6e6b..23f33999 100644 --- a/domain/Models/ValueObjects/BasketProduct.php +++ b/domain/Models/ValueObjects/BasketProduct.php @@ -10,6 +10,7 @@ use Domain\Enums\Units\OrderUnit; use Domain\Models\Entities\Product; use Domain\Models\ValueObjects\Entities\ProductId; use Money\Money; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; final readonly class BasketProduct { @@ -25,7 +26,7 @@ final readonly class BasketProduct public ?IncoId $incoId, public OrderUnit $orderUnit, public string $slug, - public ?string $picture, + public ?StorageFilePath $picture, public ?string $description, public bool $weightVariable, public DiscountRate $discountRate, diff --git a/domain/Models/ValueObjects/OrderLineProduct.php b/domain/Models/ValueObjects/OrderLineProduct.php index a8ab97fc..6abf59ea 100644 --- a/domain/Models/ValueObjects/OrderLineProduct.php +++ b/domain/Models/ValueObjects/OrderLineProduct.php @@ -9,6 +9,7 @@ use Domain\Enums\TaxRate; use Domain\Enums\Units\OrderUnit; use Domain\Models\ValueObjects\Entities\ProductId; use Money\Money; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; final readonly class OrderLineProduct { @@ -23,7 +24,7 @@ final readonly class OrderLineProduct public Money $discountedPrice, public Money $priceKgTtc, public TaxRate $taxRate, - public ?string $picture = null + public ?StorageFilePath $picture = null ) { if (trim($name) === '') { throw new \DomainException('Product name cannot be empty'); diff --git a/infra/Adapters/Serializers/BasketSerializer.php b/infra/Adapters/Serializers/BasketSerializer.php index 5d8f3fa4..cc7465c1 100644 --- a/infra/Adapters/Serializers/BasketSerializer.php +++ b/infra/Adapters/Serializers/BasketSerializer.php @@ -17,6 +17,8 @@ use Illuminate\Support\Arr; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; +use Webmozart\Assert\Assert; class BasketSerializer { @@ -81,6 +83,10 @@ class BasketSerializer $priceKgTtcCurrency = Arr::string($priceKgTtc, 'currency'); $options = Arr::array($itemData, 'options', []); + foreach ($options as $key => $option) { + Assert::string($key); + } + if (empty($unitPriceHtCurrency)) { throw new \DomainException("Currency is required for unitPriceHt of item with id $id"); } @@ -109,7 +115,7 @@ class BasketSerializer incoId: is_scalar($incoId) && $incoId !== 0 ? new IncoId((int) $incoId) : null, orderUnit: OrderUnit::from($orderUnit), slug: $slug, - picture: is_string($picture) && $picture !== '' ? $picture : null, + picture: is_string($picture) && $picture !== '' ? new StorageFilePath($picture) : null, description: is_string($description) && $description !== '' ? $description : null, weightVariable: $weightVariable, discountRate: $discountRate, diff --git a/resources/views/bo/products/index-list.blade.php b/resources/views/bo/products/index-list.blade.php index a486f1a4..8b1dad60 100644 --- a/resources/views/bo/products/index-list.blade.php +++ b/resources/views/bo/products/index-list.blade.php @@ -46,7 +46,7 @@ {{ Str::limit($product->name, 45) }} @if (!empty($product->picture)) - {{ $product->picture_alt }} @else {{ __('No Content') }} @@ -54,7 +54,7 @@ @if (!empty($product->picture_large)) - {{ $product->picture_large_alt }} @else {{ __('No Content') }} diff --git a/resources/views/bo/ranges/index-list.blade.php b/resources/views/bo/ranges/index-list.blade.php index 2b350213..34e25f5e 100644 --- a/resources/views/bo/ranges/index-list.blade.php +++ b/resources/views/bo/ranges/index-list.blade.php @@ -9,6 +9,7 @@ 'name' => Str::ucfirst(__('validation.attributes.title')), 'picture' => Str::ucfirst(__('validation.attributes.image')), 'order' => Str::ucfirst(__('validation.custom.attributes.order')), + 'status' => Str::ucfirst(__('validation.custom.attributes.status')) ]; @endphp @include('bo.modules.tableColSorter', ['cols' => $cols, 'mobileHide' => ['picture']]) @@ -18,7 +19,7 @@ {{ $range->name }} - {{ $range->picture_alt }} + {{ $range->picture_alt }} @include('bo.modules.change-order', [ 'route' => 'bo.ranges.change-order', diff --git a/resources/views/bo/slides/index-list.blade.php b/resources/views/bo/slides/index-list.blade.php index c82a07da..3cbdbe11 100644 --- a/resources/views/bo/slides/index-list.blade.php +++ b/resources/views/bo/slides/index-list.blade.php @@ -26,7 +26,7 @@ {{ $slide->title }} - {{ $slide->title }} + {{ $slide->title }} {{ $slide->link_label }} diff --git a/resources/views/bo/tags/index-list.blade.php b/resources/views/bo/tags/index-list.blade.php index 07f9eba6..c16a3659 100644 --- a/resources/views/bo/tags/index-list.blade.php +++ b/resources/views/bo/tags/index-list.blade.php @@ -8,6 +8,7 @@ $cols = [ 'label' => Str::ucfirst(__('validation.custom.attributes.label')), 'order' => Str::ucfirst(__('validation.custom.attributes.order')), + 'status' => Str::ucfirst(__('validation.custom.attributes.status')) ]; @endphp @include('bo.modules.tableColSorter', ['cols' => $cols, 'mobileHide' => ['description']]) diff --git a/resources/views/fo/home-parts/ranges.blade.php b/resources/views/fo/home-parts/ranges.blade.php index 5da9b252..246f8ee4 100644 --- a/resources/views/fo/home-parts/ranges.blade.php +++ b/resources/views/fo/home-parts/ranges.blade.php @@ -4,7 +4,7 @@
- {{ $range->picture_alt }}
diff --git a/resources/views/fo/home-parts/sliders/main.blade.php b/resources/views/fo/home-parts/sliders/main.blade.php index fc727aaa..2dd05557 100644 --- a/resources/views/fo/home-parts/sliders/main.blade.php +++ b/resources/views/fo/home-parts/sliders/main.blade.php @@ -26,7 +26,7 @@ @if (!empty($slide->picture))
- {{ $slide->picture_alt ?: $slide->title }}
@endif diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php index dce49c08..5a80ab2d 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php @@ -5,14 +5,19 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Controllers\Fo\Pages; use App\Dto\ShopDto; +use App\Lib\PrivateS3Disk; use App\Mail\SendContactMail; use App\Models\Page; use App\Models\Shop; use Database\Seeders\ContentSeeder; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\View; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\DiskName; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('ContactController', function (): void { beforeEach(function (): void { @@ -87,6 +92,43 @@ describe('ContactController', function (): void { Mail::assertQueued(SendContactMail::class); }); + it('submits contact form with an attachment uploaded via StorageService', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + Mail::fake(); + $file = UploadedFile::fake()->create('piece.pdf', 100, 'application/pdf'); + $this->mock(StorageService::class, function ($mock): void { + $mock->shouldReceive('storeUploadedOntoDisk') + ->once() + ->with( + \Mockery::type(UploadedFile::class), + \Mockery::on(fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), + ) + ->andReturn(new StorageFilePath('contact-attachments/piece.pdf')); + }); + + $data = [ + 'first_name' => 'Jean', + 'last_name' => 'Dupont', + 'email' => 'jean.dupont@gmail.com', + 'subject' => 'Question avec PJ', + 'message' => 'Bonjour, ceci est un message de test qui contient au moins vingt caractères.', + 'file' => $file, + 'ok_cgv' => '1', + ]; + + // WHEN + $response = $this->from('/contactez-nous')->post('/contactez-nous', $data); + + // THEN + $response->assertRedirect('/contactez-nous'); + $response->assertSessionHas('status', true); + Mail::assertQueued( + SendContactMail::class, + fn (SendContactMail $mail): bool => $mail->data->file?->path === 'contact-attachments/piece.pdf' + ); + }); + it('redirects with validation errors when form data is invalid', function (): void { /** @var \Tests\TestCase $this */ // GIVEN diff --git a/tests/Integration/WithApp/App/Actions/Contact/SubmitContactFormTest.php b/tests/Integration/WithApp/App/Actions/Contact/SubmitContactFormTest.php new file mode 100644 index 00000000..2753cd86 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Contact/SubmitContactFormTest.php @@ -0,0 +1,94 @@ +shouldNotReceive('storeUploadedOntoDisk'); + $action = new SubmitContactForm($storage, new PrivateS3Disk()); + $input = new SubmitContactFormInput( + lastName: 'Doe', + firstName: 'John', + email: 'john.doe@example.com', + subject: 'Question', + message: 'Bonjour, ceci est un message de test valide.', + orderRef: '12345', + ); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeInstanceOf(ContactFormData::class) + ->and($result->lastName)->toBe('Doe') + ->and($result->firstName)->toBe('John') + ->and($result->email)->toBe('john.doe@example.com') + ->and($result->subject)->toBe('Question') + ->and($result->orderRef)->toBe('12345') + ->and($result->file)->toBeNull(); + }); + + it('uploads attachment to private S3 disk and attaches metadata', function (): void { + // GIVEN + $file = UploadedFile::fake()->create('document.pdf', 100, 'application/pdf'); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeUploadedOntoDisk') + ->once() + ->with( + $file, + \Mockery::on(fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), + ) + ->andReturn(new StorageFilePath('contact-attachments/document.pdf')); + + $action = new SubmitContactForm($storage, new PrivateS3Disk()); + $input = new SubmitContactFormInput( + lastName: 'Doe', + firstName: 'John', + email: 'john.doe@example.com', + subject: 'Question', + message: 'Bonjour, ceci est un message de test valide.', + file: $file, + ); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeInstanceOf(ContactFormData::class) + ->and($result->file)->toBeInstanceOf(AttachedFile::class) + ->and($result->file?->path)->toBe('contact-attachments/document.pdf') + ->and($result->file?->originalName)->toBe('document.pdf') + ->and($result->file?->mimeType)->toBe('application/pdf'); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeUploadedOntoDisk'); + $action = new SubmitContactForm($storage, new PrivateS3Disk()); + $invalidInput = new class () implements ActionInput + { + }; + + // WHEN + expect( + /** @phpstan-ignore argument.type */ + fn () => $action($invalidInput) + ) + // THEN + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Ranges/CreateRangeTest.php b/tests/Integration/WithApp/App/Actions/Ranges/CreateRangeTest.php index 31aadc91..98a4adfd 100644 --- a/tests/Integration/WithApp/App/Actions/Ranges/CreateRangeTest.php +++ b/tests/Integration/WithApp/App/Actions/Ranges/CreateRangeTest.php @@ -5,11 +5,16 @@ declare(strict_types=1); use App\Contracts\ActionInput; use App\Cqs\Actions\Ranges\CreateRange; use App\Cqs\Actions\Ranges\CreateRangeInput; +use App\Lib\PublicS3Disk; use App\Models\Range; +use App\Services\ImageOptimizerService; use Domain\Models\ValueObjects\PictureMetadata; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\UploadedFile; -use Illuminate\Support\Facades\Storage; +use Psr\Log\NullLogger; +use Shared\Filesystem\TemporaryFileFactory; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; uses(RefreshDatabase::class); @@ -17,8 +22,14 @@ describe('CreateRange action', function () { test('it creates and persists a range in database', function () { /** @var \Tests\TestCase $this */ // GIVEN - Storage::fake('public'); - $action = new CreateRange(); + // Strict double: no S3 side effect, upload asserted. + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeFileOntoDisk')->once()->andReturn(new StorageFilePath('media/range.jpg')); + $action = new CreateRange( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $input = new CreateRangeInput( name: 'Gamme Décoration', description: '

Une superbe gamme

', @@ -49,7 +60,13 @@ describe('CreateRange action', function () { test('it throws when an invalid input is passed', function () { // GIVEN - $action = new CreateRange(); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new CreateRange( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $invalidInput = new class () implements ActionInput { }; diff --git a/tests/Integration/WithApp/App/Actions/Ranges/DeleteRangeTest.php b/tests/Integration/WithApp/App/Actions/Ranges/DeleteRangeTest.php index 19ae58dd..b8e391f9 100644 --- a/tests/Integration/WithApp/App/Actions/Ranges/DeleteRangeTest.php +++ b/tests/Integration/WithApp/App/Actions/Ranges/DeleteRangeTest.php @@ -5,8 +5,11 @@ declare(strict_types=1); use App\Contracts\ActionInput; use App\Cqs\Actions\Ranges\DeleteRange; use App\Cqs\Actions\Ranges\DeleteRangeInput; +use App\Lib\PublicS3Disk; use App\Models\Range; use Illuminate\Foundation\Testing\RefreshDatabase; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; uses(RefreshDatabase::class); @@ -21,7 +24,11 @@ describe('DeleteRange action', function () { $range->status = true; $range->save(); - $action = new DeleteRange(); + // Range has no picture: storage must stay untouched. + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('fileExistsOnDisk'); + $storage->shouldNotReceive('removeFromDisk'); + $action = new DeleteRange($storage, new PublicS3Disk('https://cdn.test')); $input = new DeleteRangeInput(range: $range); // WHEN @@ -34,9 +41,34 @@ describe('DeleteRange action', function () { ]); }); + test('it removes the picture from storage when the range has one', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + $range = new Range(); + $range->name = 'Gamme Avec Image'; + $range->picture_alt = 'Alt'; + $range->picture_title = 'Title'; + $range->status = true; + $range->picture = new StorageFilePath('media/range.jpg'); + $range->save(); + + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('fileExistsOnDisk')->once()->andReturnTrue(); + $storage->shouldReceive('removeFromDisk')->once()->andReturnTrue(); + $action = new DeleteRange($storage, new PublicS3Disk('https://cdn.test')); + + // WHEN + $result = $action(new DeleteRangeInput(range: $range)); + + // THEN + expect($result)->toBeTrue(); + $this->assertDatabaseMissing('ranges', ['id' => $range->id]); + }); + test('it throws when an invalid input is passed', function () { // GIVEN - $action = new DeleteRange(); + $storage = \Mockery::mock(StorageService::class); + $action = new DeleteRange($storage, new PublicS3Disk('https://cdn.test')); $invalidInput = new class () implements ActionInput { }; diff --git a/tests/Integration/WithApp/App/Actions/Ranges/UpdateRangeTest.php b/tests/Integration/WithApp/App/Actions/Ranges/UpdateRangeTest.php index 326ef02c..bbff5731 100644 --- a/tests/Integration/WithApp/App/Actions/Ranges/UpdateRangeTest.php +++ b/tests/Integration/WithApp/App/Actions/Ranges/UpdateRangeTest.php @@ -5,11 +5,16 @@ declare(strict_types=1); use App\Contracts\ActionInput; use App\Cqs\Actions\Ranges\UpdateRange; use App\Cqs\Actions\Ranges\UpdateRangeInput; +use App\Lib\PublicS3Disk; use App\Models\Range; +use App\Services\ImageOptimizerService; use Domain\Models\ValueObjects\PictureMetadata; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\UploadedFile; -use Illuminate\Support\Facades\Storage; +use Psr\Log\NullLogger; +use Shared\Filesystem\TemporaryFileFactory; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; uses(RefreshDatabase::class); @@ -17,7 +22,6 @@ describe('UpdateRange action', function () { test('it updates an existing range in database', function () { /** @var \Tests\TestCase $this */ // GIVEN - Storage::fake('public'); $range = new Range(); $range->name = 'Gamme Initiale'; $range->description = 'Ancien contenu'; @@ -26,7 +30,14 @@ describe('UpdateRange action', function () { $range->status = true; $range->save(); - $action = new UpdateRange(); + // Storage is a strict double: no network/S3 side effect, and the upload is asserted. + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeFileOntoDisk')->once()->andReturn(new StorageFilePath('media/range.jpg')); + $action = new UpdateRange( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $input = new UpdateRangeInput( range: $range, name: 'Gamme Renommée', @@ -57,7 +68,13 @@ describe('UpdateRange action', function () { test('it throws when an invalid input is passed', function () { // GIVEN - $action = new UpdateRange(); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new UpdateRange( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $invalidInput = new class () implements ActionInput { }; diff --git a/tests/Integration/WithApp/App/Actions/Slides/CreateSlideTest.php b/tests/Integration/WithApp/App/Actions/Slides/CreateSlideTest.php index 0ae8ff06..0c4d841b 100644 --- a/tests/Integration/WithApp/App/Actions/Slides/CreateSlideTest.php +++ b/tests/Integration/WithApp/App/Actions/Slides/CreateSlideTest.php @@ -5,13 +5,25 @@ declare(strict_types=1); use App\Contracts\ActionInput; use App\Cqs\Actions\Slides\CreateSlide; use App\Cqs\Actions\Slides\CreateSlideInput; +use App\Lib\PublicS3Disk; use App\Models\Slide; +use App\Services\ImageOptimizerService; use Domain\Models\ValueObjects\DatePeriod; +use Psr\Log\NullLogger; +use Shared\Filesystem\TemporaryFileFactory; +use Uwil\Storage\Contracts\StorageService; describe('CreateSlide action', function (): void { it('creates and persists a slide in database', function (): void { // GIVEN - $action = new CreateSlide(); + // Strict double: no picture in this input, so storage must never be touched. + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new CreateSlide( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $start = new \DateTimeImmutable('2026-06-01 10:00:00'); $end = new \DateTimeImmutable('2026-06-30 20:00:00'); $period = new DatePeriod($start, $end); @@ -46,7 +58,13 @@ describe('CreateSlide action', function (): void { it('throws when an invalid input is passed', function (): void { // GIVEN - $action = new CreateSlide(); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new CreateSlide( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $invalidInput = new class () implements ActionInput { }; diff --git a/tests/Integration/WithApp/App/Actions/Slides/DeleteSlideTest.php b/tests/Integration/WithApp/App/Actions/Slides/DeleteSlideTest.php index a9e22ebc..cdc1ce7a 100644 --- a/tests/Integration/WithApp/App/Actions/Slides/DeleteSlideTest.php +++ b/tests/Integration/WithApp/App/Actions/Slides/DeleteSlideTest.php @@ -5,17 +5,25 @@ declare(strict_types=1); use App\Contracts\ActionInput; use App\Cqs\Actions\Slides\DeleteSlide; use App\Cqs\Actions\Slides\DeleteSlideInput; +use App\Lib\PublicS3Disk; use App\Models\Slide; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('DeleteSlide action', function (): void { - it('deletes an existing slide from database', function (): void { + it('deletes an existing slide from database without picture', function (): void { + /** @var \Tests\TestCase $this */ // GIVEN $slide = new Slide(); $slide->title = 'Slide à supprimer'; $slide->text = '

Contenu

'; $slide->saveOrFail(); - $action = new DeleteSlide(); + // Slide has no picture: storage must stay untouched. + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('fileExistsOnDisk'); + $storage->shouldNotReceive('removeFromDisk'); + $action = new DeleteSlide($storage, new PublicS3Disk('https://cdn.test')); $input = new DeleteSlideInput(slide: $slide); // WHEN @@ -23,22 +31,52 @@ describe('DeleteSlide action', function (): void { // THEN expect($result)->toBeTrue(); + $this->assertDatabaseMissing('slides', [ + 'id' => $slide->id, + ]); + expect(Slide::query()->find($slide->id))->toBeNull(); + }); + + it('removes the picture from storage when the slide has one', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $slide = new Slide(); + $slide->title = 'Slide avec image'; + $slide->text = '

Contenu

'; + $slide->picture = new StorageFilePath('slides/slide.jpg'); + $slide->saveOrFail(); + + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('fileExistsOnDisk')->once()->andReturnTrue(); + $storage->shouldReceive('removeFromDisk')->once()->andReturnTrue(); + $action = new DeleteSlide($storage, new PublicS3Disk('https://cdn.test')); + $input = new DeleteSlideInput(slide: $slide); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeTrue(); + $this->assertDatabaseMissing('slides', [ + 'id' => $slide->id, + ]); expect(Slide::query()->find($slide->id))->toBeNull(); }); it('throws when an invalid input is passed', function (): void { // GIVEN - $action = new DeleteSlide(); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('fileExistsOnDisk'); + $storage->shouldNotReceive('removeFromDisk'); + $action = new DeleteSlide($storage, new PublicS3Disk('https://cdn.test')); $invalidInput = new class () implements ActionInput { }; - // WHEN + // WHEN & THEN expect( /** @phpstan-ignore argument.type */ fn () => $action($invalidInput) - ) - // THEN - ->toThrow(\InvalidArgumentException::class); + )->toThrow(\InvalidArgumentException::class); }); }); diff --git a/tests/Integration/WithApp/App/Actions/Slides/UpdateSlideTest.php b/tests/Integration/WithApp/App/Actions/Slides/UpdateSlideTest.php index cd8e3676..0588fa73 100644 --- a/tests/Integration/WithApp/App/Actions/Slides/UpdateSlideTest.php +++ b/tests/Integration/WithApp/App/Actions/Slides/UpdateSlideTest.php @@ -5,18 +5,33 @@ declare(strict_types=1); use App\Contracts\ActionInput; use App\Cqs\Actions\Slides\UpdateSlide; use App\Cqs\Actions\Slides\UpdateSlideInput; +use App\Lib\PublicS3Disk; use App\Models\Slide; +use App\Services\ImageOptimizerService; use Domain\Models\ValueObjects\DatePeriod; +use Illuminate\Http\UploadedFile; +use Psr\Log\NullLogger; +use Shared\Filesystem\TemporaryFileFactory; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('UpdateSlide action', function (): void { - it('updates an existing slide in database', function (): void { + it('updates an existing slide without new picture', function (): void { + /** @var \Tests\TestCase $this */ // GIVEN $slide = new Slide(); $slide->title = 'Ancien Titre'; $slide->text = '

Ancien texte

'; $slide->saveOrFail(); - $action = new UpdateSlide(); + // Strict double: no picture in this input, so storeFileOntoDisk must never be touched. + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new UpdateSlide( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $start = new \DateTimeImmutable('2026-07-01 10:00:00'); $end = new \DateTimeImmutable('2026-07-31 20:00:00'); $period = new DatePeriod($start, $end); @@ -48,11 +63,71 @@ describe('UpdateSlide action', function (): void { expect($fresh)->not->toBeNull() ->and($fresh?->title)->toBe('Titre Mis à Jour') ->and($fresh?->text)->toBe('

Texte mis à jour

'); + + $this->assertDatabaseHas('slides', [ + 'id' => $slide->id, + 'title' => 'Titre Mis à Jour', + ]); + }); + + it('updates an existing slide with a new uploaded picture', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $slide = new Slide(); + $slide->title = 'Ancien Titre'; + $slide->text = '

Ancien texte

'; + $slide->saveOrFail(); + + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeFileOntoDisk')->once()->andReturn(new StorageFilePath('slides/new-slide.jpg')); + $action = new UpdateSlide( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); + + $input = new UpdateSlideInput( + slide: $slide, + title: 'Titre Avec Image', + text: '

Texte avec image

', + picture: UploadedFile::fake()->image('new-slide.jpg', 600, 400), + pictureAlt: 'Nouvel alt', + pictureTitle: 'Nouveau titre', + ); + + // WHEN + $updatedSlide = $action($input); + + // THEN + expect($updatedSlide->id)->toBe($slide->id) + ->and($updatedSlide->title)->toBe('Titre Avec Image') + ->and($updatedSlide->picture_alt)->toBe('Nouvel alt') + ->and($updatedSlide->picture_title)->toBe('Nouveau titre') + ->and($updatedSlide->picture)->toBeInstanceOf(StorageFilePath::class) + ->and($updatedSlide->picture?->value)->toBe('slides/new-slide.jpg'); + + $fresh = Slide::query()->find($slide->id); + expect($fresh)->not->toBeNull() + ->and($fresh?->title)->toBe('Titre Avec Image') + ->and($fresh?->picture?->value)->toBe('slides/new-slide.jpg'); + + $this->assertDatabaseHas('slides', [ + 'id' => $slide->id, + 'title' => 'Titre Avec Image', + 'picture_alt' => 'Nouvel alt', + 'picture_title' => 'Nouveau titre', + ]); }); it('throws when an invalid input is passed', function (): void { // GIVEN - $action = new UpdateSlide(); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new UpdateSlide( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); $invalidInput = new class () implements ActionInput { }; diff --git a/tests/Integration/WithApp/App/Dto/SlideDtoTest.php b/tests/Integration/WithApp/App/Dto/SlideDtoTest.php index ef6291ef..6f6a7eb5 100644 --- a/tests/Integration/WithApp/App/Dto/SlideDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/SlideDtoTest.php @@ -3,11 +3,19 @@ declare(strict_types=1); use App\Dto\SlideDto; +use App\Lib\PublicS3Disk; use App\Models\Slide; use Illuminate\Support\Carbon; +use Illuminate\Support\Facades\Storage; describe('SlideDto integration', function (): void { - it('creates a DTO from Slide model with booted application', function (): void { + beforeEach(function (): void { + config(['filesystems.disks.s3.url' => 'https://cdn.test']); + Storage::forgetDisk(['s3', 's3-public']); + app()->forgetInstance(PublicS3Disk::class); + }); + + it('creates a DTO from Slide model with booted application and resolves public S3 URL', function (): void { // GIVEN $dateStart = Carbon::parse('2026-06-01 10:00:00'); $dateEnd = Carbon::parse('2026-06-30 20:00:00'); @@ -35,7 +43,7 @@ describe('SlideDto integration', function (): void { expect($dto->id)->toBe(42) ->and($dto->title)->toBe('Bannière Été') ->and($dto->text)->toBe('

Découvrez notre nouvelle collection

') - ->and($dto->picture)->toBe('storage/modelfiles/slides/26/06/01/ab/summer.jpg') + ->and($dto->picture)->toBe('https://cdn.test/public/storage/modelfiles/slides/26/06/01/ab/summer.jpg') ->and($dto->picture_alt)->toBe('Collection Été') ->and($dto->picture_title)->toBe('Bannière promotionnelle été') ->and($dto->link)->toBe('https://example.com/ete') @@ -48,4 +56,24 @@ describe('SlideDto integration', function (): void { ->and($dto->status)->toBeTrue() ->and($dto->isVisible())->toBeFalse(); }); + + it('creates a DTO from Slide model when picture is null', function (): void { + // GIVEN + $slide = new Slide(); + $slide->id = 43; + $slide->title = 'Slide sans image'; + $slide->text = '

Texte uniquement

'; + $slide->picture = null; + $slide->link_new_tab = false; + $slide->connected = false; + $slide->order = 1; + $slide->status = true; + + // WHEN + $dto = SlideDto::fromModel($slide); + + // THEN + expect($dto->picture)->toBeNull() + ->and($dto->title)->toBe('Slide sans image'); + }); }); diff --git a/tests/Integration/WithApp/Casts/OrderLineProductCastTest.php b/tests/Integration/WithApp/Casts/OrderLineProductCastTest.php index baafe54e..1a5a3eb1 100644 --- a/tests/Integration/WithApp/Casts/OrderLineProductCastTest.php +++ b/tests/Integration/WithApp/Casts/OrderLineProductCastTest.php @@ -16,6 +16,7 @@ use Illuminate\Database\Eloquent\Model; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('OrderLineProductCast', function () { @@ -53,7 +54,8 @@ describe('OrderLineProductCast', function () { ->and($vo->brand)->toBe(ProductBrand::loue) ->and($vo->orderUnit)->toBe(OrderUnit::PCE) ->and($vo->taxRate)->toBe(TaxRate::TVA_5_5) - ->and($vo->picture)->toBe('poulet.jpg'); + ->and($vo->picture)->toBeInstanceOf(StorageFilePath::class) + ->and($vo->picture->value)->toBe('poulet.jpg'); }); it('can cast JSON to OrderLineProduct with TVA 20% and null picture correctly', function () { @@ -105,7 +107,7 @@ describe('OrderLineProductCast', function () { discountedPrice: new Money(950, new Currency('EUR')), priceKgTtc: new Money(700, new Currency('EUR')), taxRate: TaxRate::TVA_5_5, - picture: 'poulet.jpg' + picture: new StorageFilePath('poulet.jpg') ); // WHEN diff --git a/tests/Integration/WithApp/Infra/Repositories/SessionBasketRepositoryTest.php b/tests/Integration/WithApp/Infra/Repositories/SessionBasketRepositoryTest.php index 93e3914b..b012fe71 100644 --- a/tests/Integration/WithApp/Infra/Repositories/SessionBasketRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Repositories/SessionBasketRepositoryTest.php @@ -17,6 +17,9 @@ use Domain\Ports\Repositories\BasketRepository; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; + +covers(BasketRepository::class); describe('SessionBasketRepository', function () { @@ -64,7 +67,7 @@ describe('SessionBasketRepository', function () { ->and($retrievedProduct->incoId?->value)->toBe($product->incoId?->value) ->and($retrievedProduct->orderUnit->value)->toBe($product->orderUnit->value) ->and($retrievedProduct->slug)->toBe($product->slug) - ->and($retrievedProduct->picture)->toBe($product->picture) + ->and($retrievedProduct->picture?->value)->toBe($product->picture?->value) ->and($retrievedProduct->description)->toBe($product->description) ->and($retrievedProduct->weightVariable)->toBe($product->weightVariable) ->and($retrievedProduct->discountRate->basisPoints())->toBe($product->discountRate->basisPoints()) @@ -83,7 +86,7 @@ describe('SessionBasketRepository', function () { incoId: new IncoId(456789), orderUnit: OrderUnit::from('KGM'), slug: 'poulet-roti', - picture: 'poulet.jpg', + picture: new StorageFilePath('poulet.jpg'), description: 'Un bon poulet', weightVariable: true, discountRate: DiscountRate::fromRatio(0.05), diff --git a/tests/Unit/App/Actions/Slides/CreateSlideInputTest.php b/tests/Unit/App/Actions/Slides/CreateSlideInputTest.php index b52ad42d..67694eb0 100644 --- a/tests/Unit/App/Actions/Slides/CreateSlideInputTest.php +++ b/tests/Unit/App/Actions/Slides/CreateSlideInputTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); use App\Cqs\Actions\Slides\CreateSlideInput; use Domain\Models\ValueObjects\DatePeriod; +use Illuminate\Http\UploadedFile; describe('CreateSlideInput', function (): void { it('creates a valid CreateSlideInput instance with text', function (): void { @@ -29,7 +30,7 @@ describe('CreateSlideInput', function (): void { it('creates a valid CreateSlideInput instance with picture', function (): void { // GIVEN $title = 'Nouveau Slide Photo'; - $picture = 'storage/modelfiles/slides/picture.jpg'; + $picture = \Mockery::mock(UploadedFile::class); // WHEN $input = new CreateSlideInput( @@ -81,7 +82,11 @@ describe('CreateSlideInput', function (): void { $tooLongAlt = str_repeat('a', 76); // WHEN - expect(fn () => new CreateSlideInput(title: 'Slide', picture: 'pic.jpg', pictureAlt: $tooLongAlt)) + expect(fn () => new CreateSlideInput( + title: 'Slide', + picture: \Mockery::mock(UploadedFile::class), + pictureAlt: $tooLongAlt + )) // THEN ->toThrow(\InvalidArgumentException::class); }); diff --git a/tests/Unit/App/Casts/OrderLineProductCastTest.php b/tests/Unit/App/Casts/OrderLineProductCastTest.php index 104d71a7..2f4eece1 100644 --- a/tests/Unit/App/Casts/OrderLineProductCastTest.php +++ b/tests/Unit/App/Casts/OrderLineProductCastTest.php @@ -14,131 +14,140 @@ use Illuminate\Database\Eloquent\Model; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; -it('throws exception when getting null', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); +covers(OrderLineProductCast::class); - // WHEN - $cast->get($model, 'product', null, []); +describe('OrderLineProductCast', function () { - // THEN -})->throws(\InvalidArgumentException::class, 'The value cannot be null.'); + it('throws exception when getting null', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); -it('throws exception when getting non-string', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); + // WHEN + $cast->get($model, 'product', null, []); - // WHEN - $cast->get($model, 'product', 123, []); + // THEN + })->throws(\InvalidArgumentException::class, 'The value cannot be null.'); - // THEN -})->throws(\InvalidArgumentException::class, 'The value must be a string.'); + it('throws exception when getting non-string', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); -it('gets an order line product', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); - $uuid = Uuid::uuid7()->toString(); + // WHEN + $cast->get($model, 'product', 123, []); - $json = json_encode([ - 'inco_id' => 123, - 'original_id' => $uuid, - 'name' => 'Product Name', - 'weight' => 1000, - 'weight_variable' => false, - 'brand' => ProductBrand::loue->value, - 'order_unit' => OrderUnit::PCE->value, - 'price' => '1000', - 'discounted_price' => '800', - 'price_kg_ttc' => '1000', - 'tax_rate' => TaxRate::TVA_5_5->percent(), - 'picture' => 'pic.jpg', - ]); + // THEN + })->throws(\InvalidArgumentException::class, 'The value must be a string.'); - // WHEN - $product = $cast->get($model, 'product', $json, []); + it('gets an order line product', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); + $uuid = Uuid::uuid7()->toString(); - // THEN - expect($product)->toBeInstanceOf(OrderLineProduct::class) - ->and($product->incoId->value)->toBe(123) - ->and($product->originalId->value->toString())->toBe($uuid) - ->and($product->name)->toBe('Product Name') - ->and($product->weight->value)->toBe(1000) - ->and($product->weight->isVariable)->toBeFalse() - ->and($product->taxRate)->toBe(TaxRate::TVA_5_5) - ->and($product->picture)->toBe('pic.jpg'); -}); + $json = json_encode([ + 'inco_id' => 123, + 'original_id' => $uuid, + 'name' => 'Product Name', + 'weight' => 1000, + 'weight_variable' => false, + 'brand' => ProductBrand::loue->value, + 'order_unit' => OrderUnit::PCE->value, + 'price' => '1000', + 'discounted_price' => '800', + 'price_kg_ttc' => '1000', + 'tax_rate' => TaxRate::TVA_5_5->percent(), + 'picture' => 'pic.jpg', + ]); -it('gets an order line product with integer tax rate and null picture', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); - $uuid = Uuid::uuid7()->toString(); + // WHEN + $product = $cast->get($model, 'product', $json, []); - $json = json_encode([ - 'inco_id' => 123, - 'original_id' => $uuid, - 'name' => 'Product Name', - 'weight' => 1000, - 'weight_variable' => false, - 'brand' => ProductBrand::loue->value, - 'order_unit' => OrderUnit::PCE->value, - 'price' => '1000', - 'discounted_price' => '800', - 'price_kg_ttc' => '1000', - 'tax_rate' => 20, // integer from json_decode for 20% - 'picture' => null, - ]); + // THEN + expect($product)->toBeInstanceOf(OrderLineProduct::class) + ->and($product->incoId->value)->toBe(123) + ->and($product->originalId->value->toString())->toBe($uuid) + ->and($product->name)->toBe('Product Name') + ->and($product->weight->value)->toBe(1000) + ->and($product->weight->isVariable)->toBeFalse() + ->and($product->taxRate)->toBe(TaxRate::TVA_5_5) + ->and($product->picture)->toBeInstanceOf(StorageFilePath::class) + ->and($product->picture->value)->toBe('pic.jpg'); + }); - // WHEN - $product = $cast->get($model, 'product', $json, []); + it('gets an order line product with integer tax rate and null picture', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); + $uuid = Uuid::uuid7()->toString(); - // THEN - expect($product)->toBeInstanceOf(OrderLineProduct::class) - ->and($product->taxRate)->toBe(TaxRate::TVA_20) - ->and($product->picture)->toBeNull(); -}); + $json = json_encode([ + 'inco_id' => 123, + 'original_id' => $uuid, + 'name' => 'Product Name', + 'weight' => 1000, + 'weight_variable' => false, + 'brand' => ProductBrand::loue->value, + 'order_unit' => OrderUnit::PCE->value, + 'price' => '1000', + 'discounted_price' => '800', + 'price_kg_ttc' => '1000', + 'tax_rate' => 20, // integer from json_decode for 20% + 'picture' => null, + ]); -it('throws exception when setting invalid type', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); + // WHEN + $product = $cast->get($model, 'product', $json, []); - // WHEN - $cast->set($model, 'product', 'invalid', []); + // THEN + expect($product)->toBeInstanceOf(OrderLineProduct::class) + ->and($product->taxRate)->toBe(TaxRate::TVA_20) + ->and($product->picture)->toBeNull(); + }); - // THEN -})->throws( - \InvalidArgumentException::class, - 'The given value is not an instance of OrderLineProduct.' -); + it('throws exception when setting invalid type', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); -it('sets an order line product', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); - $currency = resolve(Currency::class); + // WHEN + $cast->set($model, 'product', 'invalid', []); - $product = new OrderLineProduct( - incoId: new IncoId(123), - originalId: new ProductId(Uuid::uuid7()), - name: 'Product Name', - weight: new ProductWeight(1000, false), - brand: ProductBrand::cases()[0], // Pick first enum case - orderUnit: OrderUnit::cases()[0], // Pick first enum case - price: new Money(1000, $currency), - discountedPrice: new Money(800, $currency), - priceKgTtc: new Money(1000, $currency), - taxRate: TaxRate::TVA_20, - picture: 'pic.jpg' + // THEN + })->throws( + \InvalidArgumentException::class, + 'The given value is not an instance of OrderLineProduct.' ); - // WHEN - $value = $cast->set($model, 'product', $product, []); + it('sets an order line product', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); + $currency = new Currency('EUR'); - // THEN - expect($value)->toBeJson(); + $product = new OrderLineProduct( + incoId: new IncoId(123), + originalId: new ProductId(Uuid::uuid7()), + name: 'Product Name', + weight: new ProductWeight(1000, false), + brand: ProductBrand::cases()[0], // Pick first enum case + orderUnit: OrderUnit::cases()[0], // Pick first enum case + price: new Money(1000, $currency), + discountedPrice: new Money(800, $currency), + priceKgTtc: new Money(1000, $currency), + taxRate: TaxRate::TVA_20, + picture: new StorageFilePath('pic.jpg') + ); + + // WHEN + $value = $cast->set($model, 'product', $product, []); + $data = json_decode($value, true); + + // THEN + expect($value)->toBeJson() + ->and($data['picture'])->toBe('pic.jpg'); + }); }); diff --git a/tests/Unit/Domain/Models/Entities/BasketTest.php b/tests/Unit/Domain/Models/Entities/BasketTest.php index 2535812b..94f6f135 100644 --- a/tests/Unit/Domain/Models/Entities/BasketTest.php +++ b/tests/Unit/Domain/Models/Entities/BasketTest.php @@ -15,6 +15,7 @@ use Domain\Models\ValueObjects\Entities\ProductId; use Domain\Models\ValueObjects\IncoId; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('Basket and BasketProduct', function (): void { @@ -32,7 +33,7 @@ describe('Basket and BasketProduct', function (): void { 'incoId' => new IncoId(45), 'orderUnit' => OrderUnit::PCE, 'slug' => 'poulet-roti', - 'picture' => 'images/poulet.jpg', + 'picture' => new StorageFilePath('images/poulet.jpg'), 'description' => 'Un bon poulet rôti', 'weightVariable' => true, 'discountRate' => DiscountRate::fromRatio(0.2), @@ -65,7 +66,7 @@ describe('Basket and BasketProduct', function (): void { incoId: new IncoId(45), orderUnit: $orderUnit, slug: 'poulet-roti', - picture: 'images/poulet.jpg', + picture: new StorageFilePath('images/poulet.jpg'), description: 'Un bon poulet rôti', weightVariable: true, discountRate: DiscountRate::fromRatio(0.2), @@ -85,7 +86,7 @@ describe('Basket and BasketProduct', function (): void { expect($item->incoId->value)->toBe(45); expect($item->orderUnit)->toBe(OrderUnit::PCE); expect($item->slug)->toBe('poulet-roti'); - expect($item->picture)->toBe('images/poulet.jpg'); + expect((string) $item->picture)->toBe('images/poulet.jpg'); expect($item->description)->toBe('Un bon poulet rôti'); expect($item->weightVariable)->toBeTrue(); expect($item->discountRate->basisPoints())->toBe(2000); @@ -116,7 +117,7 @@ describe('Basket and BasketProduct', function (): void { expect($updatedItem->incoId->value)->toBe(45); expect($updatedItem->orderUnit)->toBe(OrderUnit::PCE); expect($updatedItem->slug)->toBe('poulet-roti'); - expect($updatedItem->picture)->toBe('images/poulet.jpg'); + expect((string) $updatedItem->picture)->toBe('images/poulet.jpg'); expect($updatedItem->description)->toBe('Un bon poulet rôti'); expect($updatedItem->weightVariable)->toBeTrue(); expect($updatedItem->discountRate->basisPoints())->toBe(2000); diff --git a/tests/Unit/Domain/Models/Entities/OrderTest.php b/tests/Unit/Domain/Models/Entities/OrderTest.php index c258cc93..9e63be35 100644 --- a/tests/Unit/Domain/Models/Entities/OrderTest.php +++ b/tests/Unit/Domain/Models/Entities/OrderTest.php @@ -36,6 +36,7 @@ use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; function makeOrderLine(array $overrides = []): OrderLine { @@ -228,7 +229,7 @@ describe('Order - fromBasket factory', function (): void { incoId: new IncoId(45), orderUnit: OrderUnit::PCE, slug: 'poulet-roti', - picture: 'images/poulet.jpg', + picture: new StorageFilePath('images/poulet.jpg'), description: 'Un bon poulet', weightVariable: false, discountRate: DiscountRate::fromRatio(0.1), diff --git a/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php b/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php index 97800f57..35cc5a57 100644 --- a/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php @@ -13,6 +13,7 @@ use Domain\Models\ValueObjects\OrderLineProduct; use Domain\Models\ValueObjects\ProductWeight; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('OrderLineProduct', function (): void { it('can instantiate correctly', function (): void { @@ -32,7 +33,7 @@ describe('OrderLineProduct', function (): void { Money::EUR(900), Money::EUR(2000), TaxRate::TVA_5_5, - 'pic.jpg' + new StorageFilePath('pic.jpg') // WHEN ); // THEN @@ -47,7 +48,7 @@ describe('OrderLineProduct', function (): void { ->and($product->discountedPrice->getAmount())->toBe('900') ->and($product->priceKgTtc->getAmount())->toBe('2000') ->and($product->taxRate)->toBe(TaxRate::TVA_5_5) - ->and($product->picture)->toBe('pic.jpg'); + ->and($product->picture)->toEqual(new StorageFilePath('pic.jpg')); }); it('throws exception if name is empty', function (): void { diff --git a/tests/Unit/Domain/Services/BasketServiceTest.php b/tests/Unit/Domain/Services/BasketServiceTest.php index dbaa524a..a55f7659 100644 --- a/tests/Unit/Domain/Services/BasketServiceTest.php +++ b/tests/Unit/Domain/Services/BasketServiceTest.php @@ -21,6 +21,7 @@ use Domain\Services\BasketService; use Mockery; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; function makeBasketProduct(array $overrides = []): BasketProduct { @@ -36,7 +37,7 @@ function makeBasketProduct(array $overrides = []): BasketProduct 'incoId' => new IncoId(45), 'orderUnit' => OrderUnit::PCE, 'slug' => 'poulet-roti', - 'picture' => 'images/poulet.jpg', + 'picture' => new StorageFilePath('images/poulet.jpg'), 'description' => 'Un bon poulet', 'weightVariable' => false, 'discountRate' => DiscountRate::fromRatio(0.0), diff --git a/tests/Unit/Domain/Services/OrderServiceTest.php b/tests/Unit/Domain/Services/OrderServiceTest.php index d9e63424..6d211e60 100644 --- a/tests/Unit/Domain/Services/OrderServiceTest.php +++ b/tests/Unit/Domain/Services/OrderServiceTest.php @@ -39,6 +39,7 @@ use Mockery; use Money\Money; use Ramsey\Uuid\Uuid; use Shared\Helpers\UuidHelper; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('Order Cancellation', function () { it('cancels a validated order successfully', function () { @@ -146,7 +147,7 @@ describe('Order Creation', function () { incoId: new IncoId(45), orderUnit: OrderUnit::PCE, slug: 'poulet-roti', - picture: 'images/poulet.jpg', + picture: new StorageFilePath('images/poulet.jpg'), description: 'Un bon poulet', weightVariable: false, discountRate: DiscountRate::fromRatio(0.1), @@ -234,7 +235,8 @@ describe('Order Creation', function () { expect($product->brand)->toBe(ProductBrand::marie); expect($product->incoId->value)->toBe(45); expect($product->orderUnit)->toBe(OrderUnit::PCE); - expect($product->picture)->toBe('images/poulet.jpg'); + expect($product->picture)->toBeInstanceOf(StorageFilePath::class); + expect($product->picture->value)->toBe('images/poulet.jpg'); }); it('throws exception if basket product has no incoId', function () { diff --git a/tests/Unit/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php b/tests/Unit/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php index 6710ce64..538d8640 100644 --- a/tests/Unit/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php +++ b/tests/Unit/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php @@ -9,114 +9,119 @@ use Infrastructure\Adapters\Repositories\SessionBasketRepository; use Infrastructure\Adapters\Serializers\BasketSerializer; use Ramsey\Uuid\Uuid; -it('returns null if session is empty', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(false); +covers(SessionBasketRepository::class); - $serializer = \Mockery::mock(BasketSerializer::class); +describe('SessionBasketRepository', function () { - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + it('returns null if session is empty', function () { + // GIVEN + $basketId = new BasketId(Uuid::uuid7()); + $session = \Mockery::mock(Session::class); + $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(false); - // WHEN - $basket = $repo->find($basketId); + $serializer = \Mockery::mock(BasketSerializer::class); - // THEN - expect($basket)->toBeNull(); -}); - -it('returns deserialized basket if session has data', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); - $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('{"id":"123"}'); - - $serializer = \Mockery::mock(BasketSerializer::class); - $basket = new Basket($basketId, []); - $serializer->shouldReceive('fromArray')->with(['id' => '123'])->andReturn($basket); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); - - // WHEN - $result = $repo->find($basketId); - - // THEN - expect($result)->toBe($basket); -}); - -it('returns null if session data is invalid json', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); - $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('invalid-json'); - - $serializer = \Mockery::mock(BasketSerializer::class); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); - - // WHEN - $basket = $repo->find($basketId); - - // THEN - expect($basket)->toBeNull(); -}); - -it('returns null if deserialization throws exception', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); - $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('{"id":"123"}'); - - $serializer = \Mockery::mock(BasketSerializer::class); - $serializer->shouldReceive('fromArray')->andThrow(new \Exception('error')); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); - - // WHEN - $basket = $repo->find($basketId); - - // THEN - expect($basket)->toBeNull(); -}); - -it('persists basket to session', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - - $serializer = \Mockery::mock(BasketSerializer::class); - $basket = new Basket($basketId, []); - $serializer->shouldReceive('toArray')->with($basket)->andReturn(['id' => '123']); - - $session->shouldReceive('put')->with('basket_key' . $basketId->value->toString(), '{"id":"123"}')->once(); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); - - // WHEN - $repo->persist($basket); - - // THEN - // Expectations handled by Mockery counts automatically (the `once()` call above) -}); - -it('deletes basket from session', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('forget')->with('basket_key' . $basketId->value->toString())->once(); - - $serializer = \Mockery::mock(BasketSerializer::class); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); - $basket = new Basket($basketId, []); - - // WHEN - $repo->delete($basket); - - // THEN - // Expectations handled by Mockery automatically + $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + + // WHEN + $basket = $repo->find($basketId); + + // THEN + expect($basket)->toBeNull(); + }); + + it('returns deserialized basket if session has data', function () { + // GIVEN + $basketId = new BasketId(Uuid::uuid7()); + $session = \Mockery::mock(Session::class); + $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); + $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('{"id":"123"}'); + + $serializer = \Mockery::mock(BasketSerializer::class); + $basket = new Basket($basketId, []); + $serializer->shouldReceive('fromArray')->with(['id' => '123'])->andReturn($basket); + + $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + + // WHEN + $result = $repo->find($basketId); + + // THEN + expect($result)->toBe($basket); + }); + + it('returns null if session data is invalid json', function () { + // GIVEN + $basketId = new BasketId(Uuid::uuid7()); + $session = \Mockery::mock(Session::class); + $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); + $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('invalid-json'); + + $serializer = \Mockery::mock(BasketSerializer::class); + + $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + + // WHEN + $basket = $repo->find($basketId); + + // THEN + expect($basket)->toBeNull(); + }); + + it('returns null if deserialization throws exception', function () { + // GIVEN + $basketId = new BasketId(Uuid::uuid7()); + $session = \Mockery::mock(Session::class); + $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); + $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('{"id":"123"}'); + + $serializer = \Mockery::mock(BasketSerializer::class); + $serializer->shouldReceive('fromArray')->andThrow(new \Exception('error')); + + $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + + // WHEN + $basket = $repo->find($basketId); + + // THEN + expect($basket)->toBeNull(); + }); + + it('persists basket to session', function () { + // GIVEN + $basketId = new BasketId(Uuid::uuid7()); + $session = \Mockery::mock(Session::class); + + $serializer = \Mockery::mock(BasketSerializer::class); + $basket = new Basket($basketId, []); + $serializer->shouldReceive('toArray')->with($basket)->andReturn(['id' => '123']); + + $session->shouldReceive('put')->with('basket_key' . $basketId->value->toString(), '{"id":"123"}')->once(); + + $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + + // WHEN + $repo->persist($basket); + + // THEN + // Expectations handled by Mockery counts automatically (the `once()` call above) + }); + + it('deletes basket from session', function () { + // GIVEN + $basketId = new BasketId(Uuid::uuid7()); + $session = \Mockery::mock(Session::class); + $session->shouldReceive('forget')->with('basket_key' . $basketId->value->toString())->once(); + + $serializer = \Mockery::mock(BasketSerializer::class); + + $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + $basket = new Basket($basketId, []); + + // WHEN + $repo->delete($basket); + + // THEN + // Expectations handled by Mockery automatically + }); }); diff --git a/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php b/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php index ca9eb2b2..65aadb0d 100644 --- a/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php +++ b/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php @@ -15,6 +15,7 @@ use Infrastructure\Adapters\Serializers\BasketSerializer; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; it('serializes and deserializes basket correctly', function () { describe('BasketSerializer', function () { @@ -36,7 +37,7 @@ it('serializes and deserializes basket correctly', function () { incoId: new IncoId(12345), orderUnit: OrderUnit::PCE, slug: 'product-1', - picture: 'pic.png', + picture: new StorageFilePath('pic.png'), description: 'desc', weightVariable: true, discountRate: DiscountRate::fromRatio(0.1), From 9808ef9769dba5e4aafab981db52520f432f48a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Sat, 14 Nov 2026 16:06:21 +0100 Subject: [PATCH 012/183] refactor(products): decouple views, policies and queries from Eloquent model via ProductDtoAssemblerService --- .../ProductIncos/AssociateProductInco.php | 6 +- .../AssociateProductIncoInput.php | 4 +- .../Actions/ProductIncos/SyncProductInco.php | 5 +- .../ProductIncos/SyncProductIncoInput.php | 4 +- .../Products/GetBoPaginatedProductsQuery.php | 6 +- .../Products/GetFoFilteredProductsQuery.php | 15 +- .../Products/GetFoProductIndexPageQuery.php | 14 +- .../GetFoProductIndexPageQueryOutput.php | 4 +- .../Products/GetPaginatedProductsQuery.php | 27 +- .../Products/GetProductFormDataQuery.php | 50 ++-- .../Products/GetProductFormDataQueryInput.php | 4 +- app/Cqs/Queries/Products/GetProductQuery.php | 38 +++ .../Queries/Products/GetProductQueryInput.php | 17 ++ .../Products/GetProductWithPricingQuery.php | 38 +++ .../GetPublishedProductWithPricingQuery.php | 39 +++ ...tPublishedProductWithPricingQueryInput.php | 16 ++ app/Dto/FaqDto.php | 17 +- app/Dto/ProductDto.php | 26 +- app/Dto/ProductPricingDto.php | 38 +++ app/Dto/ProductWithPricingDto.php | 7 +- app/Dto/TagDto.php | 18 +- app/Http/Controllers/Bo/FaqsController.php | 3 +- .../Bo/PickupExceptionsController.php | 6 +- .../Controllers/Bo/ProductIncosController.php | 14 +- .../Controllers/Bo/ProductsController.php | 10 +- app/Http/Controllers/Bo/RangesController.php | 4 +- app/Http/Controllers/Bo/ShopsController.php | 6 +- app/Http/Controllers/Bo/TagsController.php | 3 +- .../Fo/Pages/ProductsController.php | 13 +- app/Http/Requests/Basket/AddBasketRequest.php | 15 +- .../AssociateProductIncoRequest.php | 6 +- .../ProductIncos/SyncProductIncoRequest.php | 6 +- .../Fo/Ajax/FilteredProductResource.php | 51 ++-- app/Policies/Backend/ProductPolicy.php | 12 +- app/Policies/Frontend/ProductPolicy.php | 35 +-- app/Providers/AuthServiceProvider.php | 8 +- app/Providers/RouteServiceProvider.php | 67 +++-- app/Providers/ViewServiceProvider.php | 18 +- app/Services/ProductDtoAssemblerService.php | 145 +++++++++++ .../Ports/Repositories/ProductRepository.php | 11 + .../EloquentProductRepository.php | 32 +++ .../components/ProductsViewer/ProductCard.vue | 8 +- .../ts/fo/repositories/product.repository.ts | 2 +- .../schemas/models/product-model.zod.test.ts | 2 +- .../ts/fo/schemas/models/product-model.zod.ts | 2 +- .../fo/schemas/requests/product-filter.zod.ts | 2 +- .../ts/fo/services/filter-product.service.ts | 2 +- .../ts/fo/stores/product-viewer.store.ts | 2 +- resources/views/bo/faqs/edit.blade.php | 2 +- .../fo/home-parts/sliders/discounts.blade.php | 32 +-- .../fo/modules/guarded-currency.blade.php | 5 +- .../fo/pages/products/show-info.blade.php | 2 +- .../fo/pages/products/show-picture.blade.php | 10 +- .../pages/products/show-price-info.blade.php | 10 +- .../views/fo/pages/products/show.blade.php | 4 +- routes/breadcrumbs-bo.php | 35 +-- routes/breadcrumbs-fo.php | 6 +- .../Fo/Ajax/ProductsControllerTest.php | 2 +- .../Fo/ProductCharacterizationTest.php | 233 +++++++++++++++++ .../Requests/Basket/AddBasketRequestTest.php | 14 +- .../ProductIncos/AssociateProductIncoTest.php | 6 +- .../GetBoPaginatedProductsQueryTest.php | 18 +- .../Products/GetProductFormDataQueryTest.php | 10 +- .../App/Services/ProductDtoAssemblerTest.php | 136 ++++++++++ .../AssociateProductIncoInputTest.php | 17 +- tests/Unit/App/Dto/ProductDtoTest.php | 2 + .../Policies/Frontend/ProductPolicyTest.php | 244 ++++-------------- 67 files changed, 1167 insertions(+), 499 deletions(-) create mode 100644 app/Cqs/Queries/Products/GetProductQuery.php create mode 100644 app/Cqs/Queries/Products/GetProductQueryInput.php create mode 100644 app/Cqs/Queries/Products/GetProductWithPricingQuery.php create mode 100644 app/Cqs/Queries/Products/GetPublishedProductWithPricingQuery.php create mode 100644 app/Cqs/Queries/Products/GetPublishedProductWithPricingQueryInput.php create mode 100644 app/Dto/ProductPricingDto.php create mode 100644 app/Services/ProductDtoAssemblerService.php create mode 100644 tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php create mode 100644 tests/Integration/WithApp/App/Services/ProductDtoAssemblerTest.php diff --git a/app/Cqs/Actions/ProductIncos/AssociateProductInco.php b/app/Cqs/Actions/ProductIncos/AssociateProductInco.php index 4a31d27d..902f3de2 100644 --- a/app/Cqs/Actions/ProductIncos/AssociateProductInco.php +++ b/app/Cqs/Actions/ProductIncos/AssociateProductInco.php @@ -34,14 +34,16 @@ final class AssociateProductInco implements Action throw new \RuntimeException(sprintf('INCO sheet #%d was not found on Arcadia API.', $input->no_art)); } + $productId = $input->productId->value->toString(); + // * Remove existing product_inco for this product if present - $existing = ProductInco::query()->where('product_id', $input->product->id)->first(); + $existing = ProductInco::query()->where('product_id', $productId)->first(); if ($existing !== null) { $existing->delete(); } $inco = new ProductInco(); - $inco->product_id = (string) $input->product->id; + $inco->product_id = $productId; $inco->no_art = $incoData->noArt; $inco->ingredients = $incoData->ingredients; $inco->preparation = $incoData->preparation; diff --git a/app/Cqs/Actions/ProductIncos/AssociateProductIncoInput.php b/app/Cqs/Actions/ProductIncos/AssociateProductIncoInput.php index 673ffbfc..b39fde19 100644 --- a/app/Cqs/Actions/ProductIncos/AssociateProductIncoInput.php +++ b/app/Cqs/Actions/ProductIncos/AssociateProductIncoInput.php @@ -5,13 +5,13 @@ declare(strict_types=1); namespace App\Cqs\Actions\ProductIncos; use App\Contracts\ActionInput; -use App\Models\Product; +use Domain\Models\ValueObjects\Entities\ProductId; use Webmozart\Assert\Assert; final readonly class AssociateProductIncoInput implements ActionInput { public function __construct( - public Product $product, + public ProductId $productId, public int $no_art, ) { Assert::greaterThanEq($this->no_art, 1, 'The INCO article number must be greater than or equal to 1.'); diff --git a/app/Cqs/Actions/ProductIncos/SyncProductInco.php b/app/Cqs/Actions/ProductIncos/SyncProductInco.php index fd92e08d..03b6b887 100644 --- a/app/Cqs/Actions/ProductIncos/SyncProductInco.php +++ b/app/Cqs/Actions/ProductIncos/SyncProductInco.php @@ -28,7 +28,10 @@ final class SyncProductInco implements Action { Assert::isInstanceOf($input, SyncProductIncoInput::class); - $inco = $input->product->inco; + $inco = ProductInco::query() + ->where('product_id', $input->productId->value->toString()) + ->first(); + if ($inco === null) { throw new \RuntimeException('Product does not have an associated INCO sheet to sync.'); } diff --git a/app/Cqs/Actions/ProductIncos/SyncProductIncoInput.php b/app/Cqs/Actions/ProductIncos/SyncProductIncoInput.php index dede8ae3..1ee5e018 100644 --- a/app/Cqs/Actions/ProductIncos/SyncProductIncoInput.php +++ b/app/Cqs/Actions/ProductIncos/SyncProductIncoInput.php @@ -5,12 +5,12 @@ declare(strict_types=1); namespace App\Cqs\Actions\ProductIncos; use App\Contracts\ActionInput; -use App\Models\Product; +use Domain\Models\ValueObjects\Entities\ProductId; final readonly class SyncProductIncoInput implements ActionInput { public function __construct( - public Product $product, + public ProductId $productId, ) { } } diff --git a/app/Cqs/Queries/Products/GetBoPaginatedProductsQuery.php b/app/Cqs/Queries/Products/GetBoPaginatedProductsQuery.php index c8d66e11..b9d02644 100644 --- a/app/Cqs/Queries/Products/GetBoPaginatedProductsQuery.php +++ b/app/Cqs/Queries/Products/GetBoPaginatedProductsQuery.php @@ -6,12 +6,12 @@ namespace App\Cqs\Queries\Products; use App\Contracts\Query; use App\Contracts\QueryInput; -use App\Dto\ProductDto; use App\Models\Discount; use App\Models\Product; use App\Models\Range; use App\Models\Tag; use App\Services\DataTableService; +use App\Services\ProductDtoAssemblerService; use Domain\Enums\ProductBrand; use Illuminate\Contracts\Database\Query\Builder; use Money\Formatter\IntlMoneyFormatter; @@ -28,6 +28,7 @@ final readonly class GetBoPaginatedProductsQuery implements Query public function __construct( private DataTableService $dataTable, private IntlMoneyFormatter $moneyFormatter, + private ProductDtoAssemblerService $assembler, ) { } @@ -78,8 +79,7 @@ final readonly class GetBoPaginatedProductsQuery implements Query $this->dataTable->sortQuery(Product::class, $query, ['inco']); $paginator = $this->dataTable->paginateQuery($query, $input->pagination); - /** @var \Illuminate\Contracts\Pagination\LengthAwarePaginator $productsDtoPaginator */ - $productsDtoPaginator = $paginator->through(fn (Product $product): ProductDto => ProductDto::fromModel($product)); + $productsDtoPaginator = $this->assembler->paginateDtos($paginator); $brands = ProductBrand::cases(); $ranges = Range::query()->pluck('name', 'id'); diff --git a/app/Cqs/Queries/Products/GetFoFilteredProductsQuery.php b/app/Cqs/Queries/Products/GetFoFilteredProductsQuery.php index 7b05f9ef..16fc7023 100644 --- a/app/Cqs/Queries/Products/GetFoFilteredProductsQuery.php +++ b/app/Cqs/Queries/Products/GetFoFilteredProductsQuery.php @@ -7,18 +7,23 @@ namespace App\Cqs\Queries\Products; use App\Contracts\Query; use App\Contracts\QueryInput; use App\Models\Product; +use App\Services\ProductDtoAssemblerService; use Illuminate\Contracts\Pagination\LengthAwarePaginator; -use SortDirection; use Webmozart\Assert\Assert; /** * @implements \App\Contracts\Query< * \App\Cqs\Queries\Products\GetFoFilteredProductsQueryInput, - * \Illuminate\Contracts\Pagination\LengthAwarePaginator + * \Illuminate\Contracts\Pagination\LengthAwarePaginator * > */ final readonly class GetFoFilteredProductsQuery implements Query { + public function __construct( + private ProductDtoAssemblerService $assembler, + ) { + } + #[\Override] public function __invoke(QueryInput $input): LengthAwarePaginator { @@ -27,7 +32,7 @@ final readonly class GetFoFilteredProductsQuery implements Query /** @var \Illuminate\Database\Eloquent\Builder $query */ $query = Product::query() ->with(['inco', 'validDiscount']) - ->orderBy('order', SortDirection::Ascending) + ->orderBy('order', \SortDirection::Ascending) ->published(); if (! empty($input->search)) { @@ -59,9 +64,11 @@ final readonly class GetFoFilteredProductsQuery implements Query ); } - return $query->paginate( + $paginated = $query->with('range')->paginate( perPage: $input->pagination->pageSize()->value(), page: $input->pagination->pageNumber()->value() ); + + return $this->assembler->paginateDtosWithPricing($paginated); } } diff --git a/app/Cqs/Queries/Products/GetFoProductIndexPageQuery.php b/app/Cqs/Queries/Products/GetFoProductIndexPageQuery.php index 3fa74e09..6d5cb6b1 100644 --- a/app/Cqs/Queries/Products/GetFoProductIndexPageQuery.php +++ b/app/Cqs/Queries/Products/GetFoProductIndexPageQuery.php @@ -13,9 +13,9 @@ use App\Models\Discount; use App\Models\Product; use App\Models\Range; use App\Models\Tag; +use App\Services\ProductDtoAssemblerService; use Domain\Enums\ProductBrand; use Illuminate\Support\Collection; -use SortDirection; use Webmozart\Assert\Assert; /** @@ -26,6 +26,11 @@ use Webmozart\Assert\Assert; */ final readonly class GetFoProductIndexPageQuery implements Query { + public function __construct( + private ProductDtoAssemblerService $assembler, + ) { + } + #[\Override] public function __invoke(QueryInput $input): GetFoProductIndexPageQueryOutput { @@ -34,13 +39,12 @@ final readonly class GetFoProductIndexPageQuery implements Query /** @var \Illuminate\Database\Eloquent\Builder $query */ $query = Product::query() ->with(['inco', 'validDiscount']) - ->orderBy('order', SortDirection::Ascending) + ->orderBy('order', \SortDirection::Ascending) ->published(); - - $paginatedProducts = $query->paginate( + $paginatedProducts = $this->assembler->paginateDtosWithPricing($query->with('range')->paginate( perPage: $input->pagination->pageSize()->value(), page: $input->pagination->pageNumber()->value() - ); + )); /** @var \Illuminate\Support\Collection $publishedBrandStringList */ $publishedBrandStringList = Product::query() diff --git a/app/Cqs/Queries/Products/GetFoProductIndexPageQueryOutput.php b/app/Cqs/Queries/Products/GetFoProductIndexPageQueryOutput.php index dc2992f8..2773a808 100644 --- a/app/Cqs/Queries/Products/GetFoProductIndexPageQueryOutput.php +++ b/app/Cqs/Queries/Products/GetFoProductIndexPageQueryOutput.php @@ -5,9 +5,9 @@ declare(strict_types=1); namespace App\Cqs\Queries\Products; use App\Dto\DiscountDto; +use App\Dto\ProductWithPricingDto; use App\Dto\RangeDto; use App\Dto\TagDto; -use App\Models\Product; use Domain\Enums\ProductBrand; use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; @@ -15,7 +15,7 @@ use Illuminate\Support\Collection; final readonly class GetFoProductIndexPageQueryOutput { /** - * @param LengthAwarePaginator $paginatedProducts + * @param LengthAwarePaginator $paginatedProducts * @param Collection $brandList * @param Collection $rangeList * @param Collection $tagList diff --git a/app/Cqs/Queries/Products/GetPaginatedProductsQuery.php b/app/Cqs/Queries/Products/GetPaginatedProductsQuery.php index 6ae3deee..6b52b6b5 100644 --- a/app/Cqs/Queries/Products/GetPaginatedProductsQuery.php +++ b/app/Cqs/Queries/Products/GetPaginatedProductsQuery.php @@ -6,25 +6,23 @@ namespace App\Cqs\Queries\Products; use App\Contracts\Query; use App\Contracts\QueryInput; -use App\Dto\ProductDto; -use App\Dto\ProductWithPricingDto; use App\Models\Product; use App\Services\DataTableService; -use Domain\Ports\Repositories\ProductRepository; +use App\Services\ProductDtoAssemblerService; use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Webmozart\Assert\Assert; /** * @implements \App\Contracts\Query< * \App\Cqs\Queries\Products\GetPaginatedProductsQueryInput, - * \Illuminate\Contracts\Pagination\LengthAwarePaginator + * LengthAwarePaginator | LengthAwarePaginator * > */ final readonly class GetPaginatedProductsQuery implements Query { public function __construct( private DataTableService $dataTable, - private ProductRepository $domainProductRepository, + private ProductDtoAssemblerService $assembler, ) { } @@ -55,24 +53,9 @@ final readonly class GetPaginatedProductsQuery implements Query $paginator = $this->dataTable->paginateQuery($query, $input->pagination); if ($input->withPricing) { - /** @var \Illuminate\Contracts\Pagination\LengthAwarePaginator $result */ - $result = $paginator->through(function (Product $product): ProductWithPricingDto { - $domainProduct = $this->domainProductRepository->find($product->getId()); - Assert::notNull($domainProduct, "Domain product not found for ID {$product->id}"); - $pricing = $domainProduct->pricing(); - - return new ProductWithPricingDto( - product: $product, - pricing: $pricing, - ); - }); - - return $result; + return $this->assembler->paginateDtosWithPricing($paginator); } - /** @var \Illuminate\Contracts\Pagination\LengthAwarePaginator $result */ - $result = $paginator->through(fn (Product $product): ProductDto => ProductDto::fromModel($product)); - - return $result; + return $this->assembler->paginateDtos($paginator); } } diff --git a/app/Cqs/Queries/Products/GetProductFormDataQuery.php b/app/Cqs/Queries/Products/GetProductFormDataQuery.php index c39ffecd..89e65f96 100644 --- a/app/Cqs/Queries/Products/GetProductFormDataQuery.php +++ b/app/Cqs/Queries/Products/GetProductFormDataQuery.php @@ -12,6 +12,7 @@ use App\Dto\TagDto; use App\Models\Product; use App\Models\Range; use App\Models\Tag; +use App\Services\ProductDtoAssemblerService; use Domain\Enums\ProductBrand; use Domain\Enums\SellUnit; use Domain\Enums\TaxRate; @@ -25,6 +26,11 @@ use Webmozart\Assert\Assert; */ final readonly class GetProductFormDataQuery implements Query { + public function __construct( + private ProductDtoAssemblerService $assembler, + ) { + } + #[\Override] public function __invoke(QueryInput $input): ProductFormDataDto { @@ -41,26 +47,38 @@ final readonly class GetProductFormDataQuery implements Query ->get() ->map(fn (Tag $tag): TagDto => TagDto::fromModel($tag)); - if ($input->product !== null) { - $input->product->loadMissing(['tags', 'inco']); - $selectedProds = $input->product->products() - ->select(['products.*']) - ->get() - ->map(fn (Product $p): ProductDto => ProductDto::fromModel($p)); + $product = $input->productId !== null + ? Product::query() + ->with(['tags', 'inco']) + ->where('id', $input->productId->value->toString()) + ->first() + : null; - $existingProds = Product::query() - ->where('id', '!=', $input->product->id) - ->whereNotIn('id', $selectedProds->pluck('id')) - ->orderBy('name') - ->get() - ->map(fn (Product $p): ProductDto => ProductDto::fromModel($p)); + if ($product !== null) { + $selectedProds = collect($this->assembler->toDtos( + $product->products() + ->select(['products.*']) + ->with(['inco', 'validDiscount', 'range']) + ->get() + )); + + $existingProds = collect($this->assembler->toDtos( + Product::query() + ->with(['inco', 'validDiscount', 'range']) + ->where('id', '!=', $product->id) + ->whereNotIn('id', $selectedProds->pluck('id')) + ->orderBy('name') + ->get() + )); } else { /** @var Collection $selectedProds */ $selectedProds = Collection::empty(); - $existingProds = Product::query() - ->orderBy('name') - ->get() - ->map(fn (Product $p): ProductDto => ProductDto::fromModel($p)); + $existingProds = collect($this->assembler->toDtos( + Product::query() + ->with(['inco', 'validDiscount', 'range']) + ->orderBy('name') + ->get() + )); } return new ProductFormDataDto( diff --git a/app/Cqs/Queries/Products/GetProductFormDataQueryInput.php b/app/Cqs/Queries/Products/GetProductFormDataQueryInput.php index b6c76de8..6cfc5e2b 100644 --- a/app/Cqs/Queries/Products/GetProductFormDataQueryInput.php +++ b/app/Cqs/Queries/Products/GetProductFormDataQueryInput.php @@ -5,12 +5,12 @@ declare(strict_types=1); namespace App\Cqs\Queries\Products; use App\Contracts\QueryInput; -use App\Models\Product; +use Domain\Models\ValueObjects\Entities\ProductId; final readonly class GetProductFormDataQueryInput implements QueryInput { public function __construct( - public ?Product $product = null, + public ?ProductId $productId = null, ) { } } diff --git a/app/Cqs/Queries/Products/GetProductQuery.php b/app/Cqs/Queries/Products/GetProductQuery.php new file mode 100644 index 00000000..7727f7c8 --- /dev/null +++ b/app/Cqs/Queries/Products/GetProductQuery.php @@ -0,0 +1,38 @@ + + */ +final readonly class GetProductQuery implements Query +{ + public function __construct( + private ProductDtoAssemblerService $assembler, + ) { + } + + #[\Override] + public function __invoke(QueryInput $input): ?ProductDto + { + Assert::isAOf($input, GetProductQueryInput::class); + + $builder = Product::query()->with(['inco', 'validDiscount', 'range']); + + $product = $input->identifier instanceof Slug + ? $builder->where('slug', $input->identifier->value)->first() + : $builder->where('id', $input->identifier->value->toString())->first(); + + return $product === null ? null : $this->assembler->toDto($product); + } +} diff --git a/app/Cqs/Queries/Products/GetProductQueryInput.php b/app/Cqs/Queries/Products/GetProductQueryInput.php new file mode 100644 index 00000000..1fadcb6a --- /dev/null +++ b/app/Cqs/Queries/Products/GetProductQueryInput.php @@ -0,0 +1,17 @@ + + */ +final readonly class GetProductWithPricingQuery implements Query +{ + public function __construct( + private ProductDtoAssemblerService $assembler, + ) { + } + + #[\Override] + public function __invoke(QueryInput $input): ?ProductWithPricingDto + { + Assert::isAOf($input, GetProductQueryInput::class); + + $builder = Product::query()->with(['inco', 'validDiscount', 'range']); + + $product = $input->identifier instanceof Slug + ? $builder->where('slug', $input->identifier->value)->first() + : $builder->where('id', $input->identifier->value->toString())->first(); + + return $product === null ? null : $this->assembler->toDtoWithPricing($product); + } +} diff --git a/app/Cqs/Queries/Products/GetPublishedProductWithPricingQuery.php b/app/Cqs/Queries/Products/GetPublishedProductWithPricingQuery.php new file mode 100644 index 00000000..a7fa03ae --- /dev/null +++ b/app/Cqs/Queries/Products/GetPublishedProductWithPricingQuery.php @@ -0,0 +1,39 @@ + + */ +final readonly class GetPublishedProductWithPricingQuery implements Query +{ + public function __construct( + private ProductDtoAssemblerService $assembler, + ) { + } + + #[\Override] + public function __invoke(QueryInput $input): ?ProductWithPricingDto + { + Assert::isAOf($input, GetPublishedProductWithPricingQueryInput::class); + + $product = Product::query() + ->with(['inco', 'validDiscount', 'range', 'products']) + ->where('slug', $input->slug->value) + ->published() + ->first(); + + return $product === null ? null : $this->assembler->toDtoWithPricing($product); + } +} diff --git a/app/Cqs/Queries/Products/GetPublishedProductWithPricingQueryInput.php b/app/Cqs/Queries/Products/GetPublishedProductWithPricingQueryInput.php new file mode 100644 index 00000000..d463d40e --- /dev/null +++ b/app/Cqs/Queries/Products/GetPublishedProductWithPricingQueryInput.php @@ -0,0 +1,16 @@ + + */ +final readonly class FaqDto implements Arrayable, UrlRoutable { public function __construct( public int $id, @@ -50,4 +54,15 @@ final readonly class FaqDto implements UrlRoutable { return null; } + + #[\Override] + public function toArray(): array + { + return [ + 'id' => $this->id, + 'question' => $this->question, + 'answer' => $this->answer, + 'order' => $this->order, + ]; + } } diff --git a/app/Dto/ProductDto.php b/app/Dto/ProductDto.php index 2aa359e9..2ae59719 100644 --- a/app/Dto/ProductDto.php +++ b/app/Dto/ProductDto.php @@ -7,6 +7,7 @@ namespace App\Dto; use App\Models\Product; use Domain\Enums\ProductBrand; use Domain\Enums\SellUnit; +use Domain\Models\ValueObjects\ProductWeight; use Illuminate\Contracts\Routing\UrlRoutable; use Illuminate\Contracts\Support\Arrayable; use Money\Money; @@ -36,33 +37,46 @@ final readonly class ProductDto implements Arrayable, UrlRoutable public int $order = 0, public bool $status = false, public bool $star = false, + public ?ProductWeight $product_weight = null, + public bool $weight_variable = false, + public bool $is_orderable = false, public ?string $short_description = null, public ?string $description = null, ) { } - public static function fromModel(Product $product): self - { + public static function fromModel( + Product $product, + bool $isOrderable, + bool $validDiscountOnly = false, + ): self { + $discountModel = $validDiscountOnly + ? ($product->relationLoaded('validDiscount') ? $product->validDiscount : null) + : ($product->relationLoaded('discount') ? $product->discount : null); + return new self( id: (string) $product->id, name: $product->name, slug: (string) $product->slug, brand: $product->brand, inco: $product->relationLoaded('inco') && $product->inco ? ProductIncoDto::fromModel($product->inco) : null, - picture: is_string($product->picture) ? $product->picture : null, + picture: publicS3Asset($product->picture), picture_alt: $product->picture_alt, picture_title: $product->picture_title, - picture_large: is_string($product->picture_large) ? $product->picture_large : null, + picture_large: publicS3Asset($product->picture_large), picture_large_alt: $product->picture_large_alt, picture_large_title: $product->picture_large_title, price: $product->price instanceof Money ? $product->price : null, - discount: $product->relationLoaded('discount') && $product->discount ? DiscountDto::fromModel($product->discount) : null, + discount: $discountModel ? DiscountDto::fromModel($discountModel) : null, stock: (int) $product->stock, sell_unit: $product->sell_unit, range: $product->relationLoaded('range') && $product->range ? RangeDto::fromModel($product->range) : null, order: (int) $product->order, status: (bool) $product->status, star: (bool) $product->star, + product_weight: $product->product_weight, + weight_variable: (bool) $product->weight_variable, + is_orderable: $isOrderable, short_description: $product->short_description, description: $product->description, ); @@ -116,6 +130,8 @@ final readonly class ProductDto implements Arrayable, UrlRoutable 'sell_unit' => $this->sell_unit?->value, 'range' => $this->range?->toArray(), 'order' => $this->order, + 'product_weight' => $this->product_weight?->value, + 'weight_variable' => $this->weight_variable, 'status' => $this->status, 'star' => $this->star, 'short_description' => $this->short_description, diff --git a/app/Dto/ProductPricingDto.php b/app/Dto/ProductPricingDto.php new file mode 100644 index 00000000..585f9193 --- /dev/null +++ b/app/Dto/ProductPricingDto.php @@ -0,0 +1,38 @@ +basePriceHt(), + basePriceTtc: $pricing->basePriceTtc(), + discountAmountHt: $pricing->discountAmountHt(), + discountedPriceHt: $pricing->discountedPriceHt(), + discountedPriceTtc: $pricing->discountedPriceTtc(), + priceKgTtc: $pricing->priceKgTtc(), + discountRate: $pricing->discountRate, + hasDiscount: $pricing->hasDiscount, + ); + } +} diff --git a/app/Dto/ProductWithPricingDto.php b/app/Dto/ProductWithPricingDto.php index 2dfc199a..7acc8996 100644 --- a/app/Dto/ProductWithPricingDto.php +++ b/app/Dto/ProductWithPricingDto.php @@ -4,14 +4,11 @@ declare(strict_types=1); namespace App\Dto; -use App\Models\Product; -use Domain\Models\ValueObjects\ProductPricing; - final readonly class ProductWithPricingDto { public function __construct( - public Product $product, - public ProductPricing $pricing, + public ProductDto $product, + public ProductPricingDto $pricing, ) { } } diff --git a/app/Dto/TagDto.php b/app/Dto/TagDto.php index 556714f1..c9d709d5 100644 --- a/app/Dto/TagDto.php +++ b/app/Dto/TagDto.php @@ -6,8 +6,12 @@ namespace App\Dto; use App\Models\Tag; use Illuminate\Contracts\Routing\UrlRoutable; +use Illuminate\Contracts\Support\Arrayable; -final readonly class TagDto implements UrlRoutable +/** + * @implements Arrayable + */ +final readonly class TagDto implements Arrayable, UrlRoutable { public function __construct( public int $id, @@ -52,4 +56,16 @@ final readonly class TagDto implements UrlRoutable { return null; } + + #[\Override] + public function toArray(): array + { + return [ + 'id' => $this->id, + 'label' => $this->label, + 'slug' => $this->slug, + 'order' => $this->order, + 'status' => $this->status, + ]; + } } diff --git a/app/Http/Controllers/Bo/FaqsController.php b/app/Http/Controllers/Bo/FaqsController.php index bf928f6c..3dc22977 100644 --- a/app/Http/Controllers/Bo/FaqsController.php +++ b/app/Http/Controllers/Bo/FaqsController.php @@ -11,6 +11,7 @@ use App\Cqs\Actions\Faqs\DeleteFaqInput; use App\Cqs\Actions\Faqs\UpdateFaq; use App\Cqs\Queries\Faqs\GetPaginatedFaqsQuery; use App\Cqs\Queries\Faqs\GetPaginatedFaqsQueryInput; +use App\Dto\FaqDto; use App\Http\Controllers\Controller; use App\Http\Requests\Bo\Faqs\StoreFaqRequest; use App\Http\Requests\Bo\Faqs\UpdateFaqRequest; @@ -72,7 +73,7 @@ class FaqsController extends Controller { $this->authorize('update', $faq); - return view('bo.faqs.edit', compact('faq')); + return view('bo.faqs.edit', ['faq' => FaqDto::fromModel($faq)]); } public function update(UpdateFaqRequest $request, Faq $faq, UpdateFaq $action): RedirectResponse diff --git a/app/Http/Controllers/Bo/PickupExceptionsController.php b/app/Http/Controllers/Bo/PickupExceptionsController.php index 2f88dc5f..cf4a3e47 100644 --- a/app/Http/Controllers/Bo/PickupExceptionsController.php +++ b/app/Http/Controllers/Bo/PickupExceptionsController.php @@ -69,9 +69,9 @@ class PickupExceptionsController extends Controller { $this->authorize('update', $pickupException); - $pickupException = PickupExceptionDto::fromModel($pickupException); - - return view('bo.pickup-exceptions.edit', compact('pickupException')); + return view('bo.pickup-exceptions.edit', [ + 'pickupException' => PickupExceptionDto::fromModel($pickupException), + ]); } public function update(UpdatePickupExceptionRequest $request, PickupException $pickupException, UpdatePickupException $action): RedirectResponse diff --git a/app/Http/Controllers/Bo/ProductIncosController.php b/app/Http/Controllers/Bo/ProductIncosController.php index b4800031..69522963 100644 --- a/app/Http/Controllers/Bo/ProductIncosController.php +++ b/app/Http/Controllers/Bo/ProductIncosController.php @@ -8,7 +8,6 @@ use App\Contracts\Executor; use App\Cqs\Actions\ProductIncos\AssociateProductInco; use App\Cqs\Actions\ProductIncos\SyncProductInco; use App\Cqs\Queries\ProductIncos\GetArcadiaIncoPreviewQuery; -use App\Dto\ProductDto; use App\Dto\ProductIncoDto; use App\Http\Controllers\Controller; use App\Http\Requests\Bo\ProductIncos\AssociateProductIncoRequest; @@ -16,6 +15,7 @@ use App\Http\Requests\Bo\ProductIncos\PreviewArcadiaIncoRequest; use App\Http\Requests\Bo\ProductIncos\SyncProductIncoRequest; use App\Models\Product; use App\Models\ProductInco; +use App\Services\ProductDtoAssemblerService; use Illuminate\Contracts\View\View; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; @@ -58,7 +58,7 @@ class ProductIncosController extends Controller try { $inco = $this->executor->execute( $action, - $request->toAssociateProductIncoInput($product), + $request->toAssociateProductIncoInput($product->getId()), ); } catch (\RuntimeException $e) { return back()->with('danger', __('Arcadia API error: :error', ['error' => $e->getMessage()])); @@ -75,7 +75,7 @@ class ProductIncosController extends Controller try { $inco = $this->executor->execute( $action, - $request->toSyncProductIncoInput($product), + $request->toSyncProductIncoInput($product->getId()), ); } catch (\RuntimeException $e) { return back()->with('danger', __('Arcadia API error: :error', ['error' => $e->getMessage()])); @@ -85,16 +85,16 @@ class ProductIncosController extends Controller ->with('success', __('The INCO sheet has been successfully synchronized from Arcadia.')); } - public function create(Product $product): View + public function create(Product $product, ProductDtoAssemblerService $assembler): View { - return $this->edit($product); + return $this->edit($product, $assembler); } - public function edit(Product $product, ?ProductInco $inco = null): View + public function edit(Product $product, ProductDtoAssemblerService $assembler, ?ProductInco $inco = null): View { $this->authorize('associateInco', $product); - $productDto = ProductDto::fromModel($product); + $productDto = $assembler->toDto($product); $incoModel = $inco ?? $product->inco; $incoDto = $incoModel instanceof ProductInco ? ProductIncoDto::fromModel($incoModel) : null; diff --git a/app/Http/Controllers/Bo/ProductsController.php b/app/Http/Controllers/Bo/ProductsController.php index 9cee5f75..5fa0af4e 100644 --- a/app/Http/Controllers/Bo/ProductsController.php +++ b/app/Http/Controllers/Bo/ProductsController.php @@ -18,6 +18,7 @@ use App\Http\Requests\Bo\Products\StoreProductRequest; use App\Http\Requests\Bo\Products\UpdateProductRequest; use App\Interfaces\MassActions; use App\Models\Product; +use App\Services\ProductDtoAssemblerService; use App\Traits\Controllers\ChangesModelOrder; use App\Traits\Controllers\HasMassActions; use App\Traits\Controllers\TogglesModelStar; @@ -35,6 +36,7 @@ class ProductsController extends Controller implements MassActions public function __construct( private readonly Executor $executor, + private readonly ProductDtoAssemblerService $productDtoAssemblerService ) { } @@ -110,10 +112,10 @@ class ProductsController extends Controller implements MassActions { $this->authorize('update', $product); - $formData = $this->executor->execute($query, new GetProductFormDataQueryInput(product: $product)); + $formData = $this->executor->execute($query, new GetProductFormDataQueryInput(productId: $product->getId())); return view('bo.products.edit', [ - 'product' => $product, + 'product' => $this->productDtoAssemblerService->toDto($product), 'brands' => $formData->brands, 'taxes' => $formData->taxes, 'invoicingUnits' => $formData->invoicingUnits, @@ -132,7 +134,7 @@ class ProductsController extends Controller implements MassActions $this->executor->execute( $action, - $request->toUpdateProductInput($product) + $request->toUpdateProductInput($product->getId()) ); return to_route('bo.products.edit', $product) @@ -147,7 +149,7 @@ class ProductsController extends Controller implements MassActions $this->executor->execute( $action, - new DeleteProductInput($product) + new DeleteProductInput($product->getId()) ); return to_route('bo.products.index') diff --git a/app/Http/Controllers/Bo/RangesController.php b/app/Http/Controllers/Bo/RangesController.php index fc24a059..a3237c27 100644 --- a/app/Http/Controllers/Bo/RangesController.php +++ b/app/Http/Controllers/Bo/RangesController.php @@ -76,9 +76,7 @@ class RangesController extends Controller { $this->authorize('update', $range); - $range = RangeDto::fromModel($range); - - return view('bo.ranges.edit', compact('range')); + return view('bo.ranges.edit', ['range' => RangeDto::fromModel($range)]); } public function update(UpdateRangeRequest $request, Range $range, UpdateRange $action): RedirectResponse diff --git a/app/Http/Controllers/Bo/ShopsController.php b/app/Http/Controllers/Bo/ShopsController.php index 368f33b5..d6d078b1 100644 --- a/app/Http/Controllers/Bo/ShopsController.php +++ b/app/Http/Controllers/Bo/ShopsController.php @@ -77,9 +77,9 @@ class ShopsController extends Controller { $this->authorize('update', $shop); - $shop = ShopDto::fromModel($shop); - - return view('bo.shops.edit', compact('shop')); + return view('bo.shops.edit', [ + 'shop' => ShopDto::fromModel($shop), + ]); } public function update(UpdateShopRequest $request, Shop $shop, UpdateShop $action): RedirectResponse diff --git a/app/Http/Controllers/Bo/TagsController.php b/app/Http/Controllers/Bo/TagsController.php index cdae956a..e9dd6f43 100644 --- a/app/Http/Controllers/Bo/TagsController.php +++ b/app/Http/Controllers/Bo/TagsController.php @@ -11,6 +11,7 @@ use App\Cqs\Actions\Tags\DeleteTagInput; use App\Cqs\Actions\Tags\UpdateTag; use App\Cqs\Queries\Tags\GetPaginatedTagsQuery; use App\Cqs\Queries\Tags\GetPaginatedTagsQueryInput; +use App\Dto\TagDto; use App\Http\Controllers\Controller; use App\Http\Requests\Bo\Tags\StoreTagRequest; use App\Http\Requests\Bo\Tags\UpdateTagRequest; @@ -75,7 +76,7 @@ class TagsController extends Controller { $this->authorize('update', $tag); - return view('bo.tags.edit', compact('tag')); + return view('bo.tags.edit', ['tag' => TagDto::fromModel($tag)]); } public function update(UpdateTagRequest $request, Tag $tag, UpdateTag $action): RedirectResponse diff --git a/app/Http/Controllers/Fo/Pages/ProductsController.php b/app/Http/Controllers/Fo/Pages/ProductsController.php index e185efff..24105bb4 100644 --- a/app/Http/Controllers/Fo/Pages/ProductsController.php +++ b/app/Http/Controllers/Fo/Pages/ProductsController.php @@ -7,6 +7,8 @@ namespace App\Http\Controllers\Fo\Pages; use App\Contracts\Executor; use App\Cqs\Queries\Products\GetFoProductIndexPageQuery; use App\Cqs\Queries\Products\GetFoProductIndexPageQueryInput; +use App\Cqs\Queries\Products\GetPaginatedProductsQuery; +use App\Cqs\Queries\Products\GetPaginatedProductsQueryInput; use App\Dto\ProductWithPricingDto; use App\Http\Controllers\Controller; use App\Http\Resources\Fo\Ajax\FilteredProductResource; @@ -46,12 +48,17 @@ class ProductsController extends Controller ]); } - public function view(Request $request, ProductWithPricingDto $productWithPricing): View + public function view(Request $request, ProductWithPricingDto $productWithPricing, GetPaginatedProductsQuery $query): View { $this->authorize('viewPublished', $productWithPricing->product); - $associated = $productWithPricing->product->products; - $associated->loadMissing(['inco', 'validDiscount']); + $associated = $this->executor->execute( + $query, + new GetPaginatedProductsQueryInput( + pagination: Pagination::firstPage(new PageSize(self::PER_PAGE_PRODUCTS)), + withPricing: true + ), + ); $associatedProducts = FilteredProductResource::collection( $associated diff --git a/app/Http/Requests/Basket/AddBasketRequest.php b/app/Http/Requests/Basket/AddBasketRequest.php index f6712ab7..ec47e713 100644 --- a/app/Http/Requests/Basket/AddBasketRequest.php +++ b/app/Http/Requests/Basket/AddBasketRequest.php @@ -5,7 +5,8 @@ declare(strict_types=1); namespace App\Http\Requests\Basket; use App\Cqs\Actions\Basket\AddToBasketInput; -use App\Models\Product; +use App\Cqs\Queries\Products\GetProductQueryInput; +use App\Cqs\Queries\Products\GetProductWithPricingQuery; use Domain\Models\ValueObjects\Entities\ProductId; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Gate; @@ -15,9 +16,15 @@ class AddBasketRequest extends FormRequest { public function authorize(): bool { - $product = Product::query() - ->where('id', $this->input('rowId')) - ->first(); + $rowId = $this->input('rowId'); + + if (! is_string($rowId) || ! Uuid::isValid($rowId)) { + return false; + } + + $product = resolve(GetProductWithPricingQuery::class)( + new GetProductQueryInput($this->getProductId()) + ); return $product !== null && Gate::allows('addToBasket', $product); } diff --git a/app/Http/Requests/Bo/ProductIncos/AssociateProductIncoRequest.php b/app/Http/Requests/Bo/ProductIncos/AssociateProductIncoRequest.php index 892222e0..da22e8ae 100644 --- a/app/Http/Requests/Bo/ProductIncos/AssociateProductIncoRequest.php +++ b/app/Http/Requests/Bo/ProductIncos/AssociateProductIncoRequest.php @@ -5,7 +5,7 @@ declare(strict_types=1); namespace App\Http\Requests\Bo\ProductIncos; use App\Cqs\Actions\ProductIncos\AssociateProductIncoInput; -use App\Models\Product; +use Domain\Models\ValueObjects\Entities\ProductId; use Illuminate\Foundation\Http\FormRequest; use Infrastructure\Adapters\Services\AppAdminAuthService; @@ -29,10 +29,10 @@ class AssociateProductIncoRequest extends FormRequest ]; } - public function toAssociateProductIncoInput(Product $product): AssociateProductIncoInput + public function toAssociateProductIncoInput(ProductId $productId): AssociateProductIncoInput { return new AssociateProductIncoInput( - product: $product, + productId: $productId, no_art: $this->integer('no_art') ); } diff --git a/app/Http/Requests/Bo/ProductIncos/SyncProductIncoRequest.php b/app/Http/Requests/Bo/ProductIncos/SyncProductIncoRequest.php index 486eab31..6e6ee69b 100644 --- a/app/Http/Requests/Bo/ProductIncos/SyncProductIncoRequest.php +++ b/app/Http/Requests/Bo/ProductIncos/SyncProductIncoRequest.php @@ -5,7 +5,7 @@ declare(strict_types=1); namespace App\Http\Requests\Bo\ProductIncos; use App\Cqs\Actions\ProductIncos\SyncProductIncoInput; -use App\Models\Product; +use Domain\Models\ValueObjects\Entities\ProductId; use Illuminate\Foundation\Http\FormRequest; use Infrastructure\Adapters\Services\AppAdminAuthService; @@ -27,10 +27,10 @@ class SyncProductIncoRequest extends FormRequest return []; } - public function toSyncProductIncoInput(Product $product): SyncProductIncoInput + public function toSyncProductIncoInput(ProductId $productId): SyncProductIncoInput { return new SyncProductIncoInput( - product: $product + productId: $productId ); } } diff --git a/app/Http/Resources/Fo/Ajax/FilteredProductResource.php b/app/Http/Resources/Fo/Ajax/FilteredProductResource.php index e46f5207..7573a33e 100644 --- a/app/Http/Resources/Fo/Ajax/FilteredProductResource.php +++ b/app/Http/Resources/Fo/Ajax/FilteredProductResource.php @@ -4,16 +4,15 @@ declare(strict_types=1); namespace App\Http\Resources\Fo\Ajax; +use App\Dto\ProductWithPricingDto; use App\Lib\Helpers\MoneyHelper; -use App\Models\Product; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Support\Facades\Gate; -use Infrastructure\Adapters\Repositories\EloquentProductRepository; class FilteredProductResource extends JsonResource { - public function __construct(private readonly Product $product) + public function __construct(private readonly ProductWithPricingDto $tuple) { } @@ -21,33 +20,29 @@ class FilteredProductResource extends JsonResource #[\Override] public function toArray(Request $request): array { - $productRepository = resolve(EloquentProductRepository::class); - - $domainProduct = $productRepository->toEntity($this->product); - $productPricing = $domainProduct->pricing(); - $discount = $productPricing->hasDiscount ? $productPricing->discountedPriceTtc() : null; + $canViewPrices = Gate::allows('viewPrices', $this->tuple); return [ - 'id' => $this->product->id, - 'slug' => $this->product->slug, - 'name' => $this->product->name, - 'picture' => url($this->product->picture), - 'picture_alt' => $this->product->picture_alt, - 'picture_title' => $this->product->picture_title, - 'weight_variable' => $this->product->weight_variable, - 'sell_unit' => $this->product->sell_unit, - 'sell_unit_label' => $this->product->sell_unit->label(), - 'shortDescription' => $this->product->short_description, - 'priceTtc' => Gate::allows('viewPrices', $this->product) ? - MoneyHelper::serialized($productPricing->basePriceTtc()) : null, - 'priceKgTtc' => Gate::allows('viewPrices', $this->product) ? - MoneyHelper::serialized($productPricing->priceKgTtc()) : null, - 'discountedPriceTtc' => Gate::allows('viewPrices', $this->product) ? - MoneyHelper::serialized($discount) : null, - 'is_available' => $domainProduct->isOrderable(), - 'can_add_to_basket' => Gate::allows('addToBasket', $this->product), - 'showStrippedPrice' => (bool) $this->product->validDiscount?->is_old_price_displayed, - 'nutriscore' => $this->product->inco?->nutriscore?->value(), + 'id' => $this->tuple->product->id, + 'slug' => $this->tuple->product->slug, + 'name' => $this->tuple->product->name, + 'picture' => publicS3Asset($this->tuple->product->picture), + 'picture_alt' => $this->tuple->product->picture_alt, + 'picture_title' => $this->tuple->product->picture_title, + 'weight_variable' => $this->tuple->product->weight_variable, + 'sell_unit' => $this->tuple->product->sell_unit, + 'sell_unit_label' => $this->tuple->product->sell_unit?->label(), + 'shortDescription' => $this->tuple->product->short_description, + 'priceTtc' => $canViewPrices ? + MoneyHelper::serialized($this->tuple->pricing->basePriceTtc) : null, + 'priceKgTtc' => $canViewPrices ? + MoneyHelper::serialized($this->tuple->pricing->priceKgTtc) : null, + 'discountedPriceTtc' => $canViewPrices ? + MoneyHelper::serialized($this->tuple->pricing->discountedPriceTtc) : null, + 'is_orderable' => $this->tuple->product->is_orderable, + 'can_add_to_basket' => Gate::allows('addToBasket', $this->tuple), + 'showStrippedPrice' => (bool) $this->tuple->product->discount?->is_old_price_displayed, + 'nutriscore' => $this->tuple->product->inco?->nutriscore?->value(), ]; } } diff --git a/app/Policies/Backend/ProductPolicy.php b/app/Policies/Backend/ProductPolicy.php index 9d039b53..222d5f96 100644 --- a/app/Policies/Backend/ProductPolicy.php +++ b/app/Policies/Backend/ProductPolicy.php @@ -9,9 +9,7 @@ use App\Models\Customer; use App\Models\Product; use App\Models\User; use Domain\Enums\UserRole; -use Domain\Models\ValueObjects\Entities\ProductId; use Domain\Ports\Repositories\ProductRepository; -use Ramsey\Uuid\Uuid; class ProductPolicy { @@ -78,7 +76,7 @@ class ProductPolicy return $user->role->isAtLeastEqualsTo(UserRole::Admin) && $hasInco; } - public function associateInco(Customer | User $user, Product | ProductDto $product): bool + public function associateInco(Customer | User $user, Product | ProductDto $_): bool { if ($user instanceof Customer) { return false; @@ -121,11 +119,11 @@ class ProductPolicy public function viewPublished(null | Customer | User $_, Product | ProductDto $product): bool { - $productId = $product instanceof ProductDto - ? new ProductId(Uuid::fromString($product->id)) - : $product->getId(); + if ($product instanceof ProductDto) { + return $product->status; + } - $domainProduct = $this->productRepository->find($productId); + $domainProduct = $this->productRepository->find($product->getId()); return $domainProduct && $domainProduct->isPublished(); } diff --git a/app/Policies/Frontend/ProductPolicy.php b/app/Policies/Frontend/ProductPolicy.php index 3e22e638..046deb5f 100644 --- a/app/Policies/Frontend/ProductPolicy.php +++ b/app/Policies/Frontend/ProductPolicy.php @@ -4,40 +4,27 @@ declare(strict_types=1); namespace App\Policies\Frontend; +use App\Dto\ProductWithPricingDto; use App\Models\Customer; -use App\Models\Product; use App\Models\User; -use Domain\Ports\Repositories\ProductRepository; +/** + * Policy FO des produits, enregistrée pour {@see ProductWithPricingDto}. + * Elle ne dépend que du DTO : commandabilité et publication y sont déjà calculées. + */ class ProductPolicy { - public function __construct( - private readonly ProductRepository $productRepository - ) { + public function addToBasket(null | User | Customer $_, ProductWithPricingDto $product): bool + { + return $product->product->is_orderable; } - public function viewPublished(null | Customer | User $_, Product $product): bool + public function viewPrices(null | User | Customer $user, ProductWithPricingDto $product): bool { - $domainProduct = $this->productRepository->find($product->getId()); - - return $domainProduct && $domainProduct->isPublished(); - } - - public function addToBasket(null | User | Customer $_, Product $product): bool - { - $domainProduct = $this->productRepository->find($product->getId()); - - return $domainProduct && $domainProduct->isOrderable(); - } - - public function viewPrices(null | User | Customer $_, Product $product): bool - { - if (! ($_ instanceof Customer || $_ instanceof User)) { + if (! ($user instanceof Customer || $user instanceof User)) { return false; } - $domainProduct = $this->productRepository->find($product->getId()); - - return $domainProduct && $domainProduct->isPublished(); + return $product->product->status; } } diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 4f76bc1a..59c07000 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -9,6 +9,7 @@ use App\Dto\FaqDto; use App\Dto\PageDto; use App\Dto\PickupExceptionDto; use App\Dto\ProductDto; +use App\Dto\ProductWithPricingDto; use App\Dto\RangeDto; use App\Dto\SettingDto; use App\Dto\ShopDto; @@ -29,9 +30,11 @@ use App\Policies\Backend\ShopPolicy; use App\Policies\Backend\SlidePolicy; use App\Policies\Backend\TagPolicy; use App\Policies\Frontend\BasketPolicy; +use App\Policies\Frontend\ProductPolicy as FrontendProductPolicy; use App\Services\CrmService; use Domain\Models\ValueObjects\BasketProduct; use Domain\Services\ShopperService; +use Illuminate\Foundation\Application; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; @@ -56,6 +59,7 @@ class AuthServiceProvider extends ServiceProvider PageDto::class => PagePolicy::class, PickupExceptionDto::class => PickupExceptionPolicy::class, ProductDto::class => ProductPolicy::class, + ProductWithPricingDto::class => FrontendProductPolicy::class, RangeDto::class => RangePolicy::class, Setting::class => SettingPolicy::class, SettingDto::class => SettingPolicy::class, @@ -74,14 +78,14 @@ class AuthServiceProvider extends ServiceProvider { $this->app->singleton( AppAdminAuthService::class, - fn ($app): AppAdminAuthService => new AppAdminAuthService( + fn (Application $app): AppAdminAuthService => new AppAdminAuthService( Auth::guard('backend') ) ); $this->app->singleton( AppCustomerAuthService::class, - fn ($app): AppCustomerAuthService => new AppCustomerAuthService( + fn (Application $app): AppCustomerAuthService => new AppCustomerAuthService( Auth::guard('frontend'), $app->make(CrmService::class) ) diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index bc93b955..0fb46aa6 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace App\Providers; +use App\Cqs\Queries\Products\GetPublishedProductWithPricingQuery; +use App\Cqs\Queries\Products\GetPublishedProductWithPricingQueryInput; use App\Dto\ProductWithPricingDto; use App\Lib\Helpers\RequestHelper; use App\Models\Discount; @@ -13,14 +15,12 @@ use App\Models\ProductInco; use App\Models\Range; use App\Models\Slide; use App\Models\Tag; -use Domain\Ports\Repositories\ProductRepository; +use Domain\Models\ValueObjects\Slug; use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Foundation\Http\Middleware\PreventRequestForgery; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use Illuminate\Http\Request; use Illuminate\Support\Arr; -use Illuminate\Support\Collection; -use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\Route; @@ -140,26 +140,14 @@ class RouteServiceProvider extends ServiceProvider private function resolvePublishedProductWithPricing(string $value): ProductWithPricingDto { - $domainProductRepository = resolve(ProductRepository::class); - $product = Product::query() - ->where('slug', $value) - ->published() - ->firstOrFail(); - - if (Gate::denies('viewPublished', $product)) { + try { + $input = new GetPublishedProductWithPricingQueryInput(new Slug($value)); + } catch (\InvalidArgumentException) { throw new NotFoundHttpException(); } - $product->load(['inco', 'validDiscount', 'products']); - - $domainProduct = $domainProductRepository->find($product->getId()); - $pricing = $domainProduct?->pricing(); - - if (! $pricing) { - throw new NotFoundHttpException(); - } - - return new ProductWithPricingDto($product, $pricing); + return resolve(GetPublishedProductWithPricingQuery::class)($input) + ?? throw new NotFoundHttpException(); } /** @@ -184,7 +172,7 @@ class RouteServiceProvider extends ServiceProvider $cspReport = (function (array $data): array { // Format Reporting API moderne - if (isset($data[0]['type']) && $data[0]['type'] === 'csp-violation') { + if (isset($data[0]) && is_array($data[0]) && isset($data[0]['type']) && $data[0]['type'] === 'csp-violation') { return (array) ($data[0]['body'] ?? []); } @@ -197,25 +185,34 @@ class RouteServiceProvider extends ServiceProvider })((array) $request->json()->all()); // * Filter array keys - $cspReport = Collection::make([ - 'document-uri' => Arr::string($cspReport, 'documentURL', Arr::string($cspReport, 'document-uri', 'unknown')), - 'referrer' => Arr::string($cspReport, 'referrer', ''), - 'blocked-uri' => Arr::string($cspReport, 'blockedURL', Arr::string($cspReport, 'blocked-uri', '')), - 'effective-directive' => Arr::string($cspReport, 'effectiveDirective', Arr::string($cspReport, 'effective-directive', 'unknown')), - 'original-policy' => Arr::string($cspReport, 'originalPolicy', Arr::string($cspReport, 'original-policy', 'unknown')), - 'disposition' => Arr::string($cspReport, 'disposition', 'enforce'), - 'status-code' => Arr::integer( + $cspReport = [ + 'document-uri' => Arr::get($cspReport, 'documentURL', Arr::get($cspReport, 'document-uri', 'unknown')), + 'referrer' => Arr::get($cspReport, 'referrer', ''), + 'blocked-uri' => Arr::get($cspReport, 'blockedURL', Arr::get($cspReport, 'blocked-uri', '')), + 'effective-directive' => Arr::get($cspReport, 'effectiveDirective', Arr::get($cspReport, 'effective-directive', 'unknown')), + 'original-policy' => Arr::get($cspReport, 'originalPolicy', Arr::get($cspReport, 'original-policy', 'unknown')), + 'disposition' => Arr::get($cspReport, 'disposition', 'enforce'), + 'status-code' => Arr::get( $cspReport, 'statusCode', - Arr::integer($cspReport, 'status-code', 200) + Arr::get($cspReport, 'status-code', 200) ), - 'line-number' => Arr::integer($cspReport, 'lineNumber'), - 'column-number' => Arr::integer($cspReport, 'columnNumber'), - 'source-file' => Arr::string($cspReport, 'sourceFile'), - ]); + 'line-number' => Arr::get($cspReport, 'lineNumber'), + 'column-number' => Arr::get($cspReport, 'columnNumber'), + 'source-file' => Arr::get($cspReport, 'sourceFile'), + ]; + + /** @var array $cspReport */ + $cspReport = array_filter($cspReport, fn ($value) => ! is_string($value) || trim($value) !== ''); + $cspReportLines = array_map( + fn ($key, $value) => "\t{$key} -> {$value}", + array_keys($cspReport), + $cspReport + ); + Log::warning(sprintf( "CSP REPORT : \n %s", - $cspReport->transform(fn ($value, $key) => "\t{$key} -> {$value}")->join("\n") + implode("\n", $cspReportLines) )); })->middleware('throttle:5,2') ->withoutMiddleware(PreventRequestForgery::class) diff --git a/app/Providers/ViewServiceProvider.php b/app/Providers/ViewServiceProvider.php index 3c10a3da..936db110 100644 --- a/app/Providers/ViewServiceProvider.php +++ b/app/Providers/ViewServiceProvider.php @@ -5,13 +5,11 @@ declare(strict_types=1); namespace App\Providers; use App\Models\Page; -use App\Models\Product; use App\Services\EmployeeSyncService; +use Illuminate\Contracts\View\View as ContractsView; use Illuminate\Pagination\Paginator; -use Illuminate\Support\Facades\Blade; use Illuminate\Support\Facades\View; use Illuminate\Support\ServiceProvider; -use Infrastructure\Adapters\Repositories\EloquentProductRepository; class ViewServiceProvider extends ServiceProvider { @@ -20,10 +18,8 @@ class ViewServiceProvider extends ServiceProvider * * @return void */ - public function boot(EloquentProductRepository $productRepository) + public function boot() { - $this->setUpBladeMacros($productRepository); - if ($this->app->runningInConsole() && ! $this->app->runningUnitTests()) { return; } @@ -41,7 +37,7 @@ class ViewServiceProvider extends ServiceProvider } // * PAGE LIST - View::composer('*', function ($view) { + View::composer('*', function (ContractsView $view) { $view->with('PageList', Page::getCached() ->mapWithKeys(fn ($page) => [ $page->slug->value() => $page, @@ -49,12 +45,4 @@ class ViewServiceProvider extends ServiceProvider $view->with('EmployeeSyncService', resolve(EmployeeSyncService::class)); }); } - - private function setUpBladeMacros(EloquentProductRepository $productRepository): void - { - Blade::if( - 'orderable', - fn (Product $product) => $productRepository->toEntity($product)->isOrderable() - ); - } } diff --git a/app/Services/ProductDtoAssemblerService.php b/app/Services/ProductDtoAssemblerService.php new file mode 100644 index 00000000..f4068d8e --- /dev/null +++ b/app/Services/ProductDtoAssemblerService.php @@ -0,0 +1,145 @@ +toDtos([$product])[0]; + } + + public function toDtoWithPricing(Product $product): ProductWithPricingDto + { + return $this->toDtosWithPricing([$product])[0]; + } + + /** + * @param iterable $products + * @return list + */ + public function toDtos(iterable $products): array + { + [$models, $entities] = $this->load($products); + + return array_values(array_map( + fn (Product $model): ProductDto => ProductDto::fromModel( + $model, + $this->entityOf($entities, $model)->isOrderable(), + ), + $models + )); + } + + /** + * @param iterable $products + * @return list + */ + public function toDtosWithPricing(iterable $products): array + { + [$models, $entities] = $this->load($products); + + return array_values(array_map( + function (Product $model) use ($entities): ProductWithPricingDto { + $entity = $this->entityOf($entities, $model); + + return new ProductWithPricingDto( + product: ProductDto::fromModel( + $model, + $entity->isOrderable(), + validDiscountOnly: true, + ), + pricing: ProductPricingDto::fromModel($entity->pricing()), + ); + }, + $models + )); + } + + /** + * Remplace le contenu d'un paginator de modèles par des DTOs (sans pricing). + * + * @param LengthAwarePaginator $paginator + * @return LengthAwarePaginator + */ + public function paginateDtos(LengthAwarePaginator $paginator): LengthAwarePaginator + { + $dtos = $this->toDtos($paginator->items()); + + /** @var LengthAwarePaginator $paginator */ + $paginator = $paginator->setCollection(new BaseCollection($dtos)); + + return $paginator; + } + + /** + * @param LengthAwarePaginator $paginator + * @return LengthAwarePaginator + */ + public function paginateDtosWithPricing(LengthAwarePaginator $paginator): LengthAwarePaginator + { + $dtos = $this->toDtosWithPricing($paginator->items()); + + /** @var LengthAwarePaginator $paginator */ + $paginator = $paginator->setCollection(new BaseCollection($dtos)); + + return $paginator; + } + + /** + * @param iterable $products + * @return array{0: list, 1: array} + */ + private function load(iterable $products): array + { + $models = []; + foreach ($products as $product) { + $models[] = $product; + } + + (new Collection($models))->loadMissing('range'); + + $ids = array_map( + static fn (Product $m): ProductId => new ProductId(Uuid::fromString((string) $m->id)), + $models + ); + + return [$models, $this->productRepository->findMany($ids)]; + } + + /** + * @param array $entities + */ + private function entityOf(array $entities, Product $model): DomainProduct + { + $entity = $entities[(string) $model->id] ?? null; + Assert::notNull($entity, "Domain product not found for ID {$model->id}"); + + return $entity; + } +} diff --git a/domain/Ports/Repositories/ProductRepository.php b/domain/Ports/Repositories/ProductRepository.php index 9449d305..454a8960 100644 --- a/domain/Ports/Repositories/ProductRepository.php +++ b/domain/Ports/Repositories/ProductRepository.php @@ -7,6 +7,7 @@ namespace Domain\Ports\Repositories; use Domain\Models\Entities\Product; use Domain\Models\ValueObjects\BasketProduct; use Domain\Models\ValueObjects\Entities\ProductId; +use Domain\Models\ValueObjects\Slug; use Shared\DDD\Repository; /** @@ -16,6 +17,16 @@ interface ProductRepository extends Repository { public function find(ProductId $id): ?Product; + public function findByslug(Slug $slug): ?Product; + + /** + * Charge plusieurs entités en une seule requête. + * + * @param list $ids + * @return array entités indexées par l'UUID du produit + */ + public function findMany(array $ids): array; + public function persist(Product $product): void; public function delete(Product $product): void; diff --git a/infra/Adapters/Repositories/EloquentProductRepository.php b/infra/Adapters/Repositories/EloquentProductRepository.php index 10e3884b..4b93fe95 100644 --- a/infra/Adapters/Repositories/EloquentProductRepository.php +++ b/infra/Adapters/Repositories/EloquentProductRepository.php @@ -10,6 +10,7 @@ use Domain\Enums\Units\OrderUnit; use Domain\Models\Entities\Product as DomainProduct; use Domain\Models\ValueObjects\BasketProduct; use Domain\Models\ValueObjects\Entities\ProductId; +use Domain\Models\ValueObjects\Slug; use Domain\Ports\Repositories\ProductRepository; use Illuminate\Support\Carbon; use Ramsey\Uuid\Uuid; @@ -27,6 +28,37 @@ class EloquentProductRepository implements ProductRepository return $product ? $this->toEntity($product) : null; } + #[\Override] + public function findByslug(Slug $slug): ?DomainProduct + { + $product = Product::query() + ->with(['inco', 'validDiscount']) + ->where('slug', $slug->value) + ->first(); + + return $product ? $this->toEntity($product) : null; + } + + #[\Override] + public function findMany(array $ids): array + { + if ($ids === []) { + return []; + } + + $entities = []; + $models = Product::query() + ->with(['inco', 'validDiscount']) + ->whereIn('id', array_map(static fn (ProductId $id): string => $id->value->toString(), $ids)) + ->get(); + + foreach ($models as $model) { + $entities[(string) $model->id] = $this->toEntity($model); + } + + return $entities; + } + #[\Override] public function persist(DomainProduct $entity): void { diff --git a/resources/ts/fo/components/ProductsViewer/ProductCard.vue b/resources/ts/fo/components/ProductsViewer/ProductCard.vue index 1e201f2f..ed2fc3ed 100644 --- a/resources/ts/fo/components/ProductsViewer/ProductCard.vue +++ b/resources/ts/fo/components/ProductsViewer/ProductCard.vue @@ -2,14 +2,14 @@
- @can('addToBasket', $productWithPricing->product) + @can('addToBasket', $productWithPricing)
$productWithPricing->product->id])'>
diff --git a/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php b/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php index 66503945..5ad2dc6a 100644 --- a/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php @@ -12,6 +12,7 @@ use App\Models\Customer; use App\Models\Discount; use App\Models\Page; use App\Models\Product; +use App\Models\ProductInco; use App\Models\Range; use Database\Seeders\ContentSeeder; use Domain\Enums\DiscountType; @@ -31,6 +32,7 @@ use Tests\TestCase; use function Pest\Laravel\actingAs; use function Pest\Laravel\get; +use function Pest\Laravel\seed; /** * Tests de caractérisation (étape 0 du refactoring Product) : figent le @@ -54,8 +56,13 @@ function characterizationCustomer(string $email): Customer return $customer; } -function characterizationProduct(string $name, bool $status = true, ?Discount $discount = null): Product -{ +function characterizationProduct( + string $name, + bool $status = true, + ?Discount $discount = null, + bool $withInco = false, + bool $star = false, +): Product { $range = new Range(); $range->name = "Gamme {$name}"; $range->status = true; @@ -74,6 +81,7 @@ function characterizationProduct(string $name, bool $status = true, ?Discount $d 'tax_rate' => TaxRate::TVA_20, 'description' => 'Description', 'status' => $status, + 'star' => $star, ]); $product->order = 1; $product->price = Money::EUR(1000); @@ -85,6 +93,13 @@ function characterizationProduct(string $name, bool $status = true, ?Discount $d $product->discount_id = $discount?->id; $product->save(); + if ($withInco) { + $inco = new ProductInco(); + $inco->product_id = $product->id; + $inco->no_art = random_int(10000, 99999); + $inco->saveOrFail(); + } + return $product; } @@ -281,4 +296,58 @@ describe('FO product page (characterization)', function (): void { $response->assertOk(); expect($executed)->toContain(GetPublishedProductWithPricingQuery::class); }); + + it('renders prices and add-to-basket button for an authenticated customer on an orderable product', function (): void { + // GIVEN + seed(ContentSeeder::class); + View::share('PageList', Page::getCached()->mapWithKeys(fn ($page) => [$page->slug->value() => $page])); + Cache::flush(); + actingAs(characterizationCustomer('buyer@example.com'), 'frontend'); + $product = characterizationProduct('Produit Achetable', withInco: true); + + // WHEN + $response = get(route('fo.products.show', ['productWithPricingPublished' => $product->slug])); + + // THEN + $response->assertOk() + ->assertSee('Produit Achetable') + ->assertSee('12,00') + ->assertDontSee('-.--') + ->assertSee('class="basket-buttons"', false); + }); + + it('hides prices for guests on the product page while keeping add-to-basket absent without INCO', function (): void { + // GIVEN + seed(ContentSeeder::class); + View::share('PageList', Page::getCached()->mapWithKeys(fn ($page) => [$page->slug->value() => $page])); + Cache::flush(); + $product = characterizationProduct('Produit Invité Fiche'); + + // WHEN + $response = get(route('fo.products.show', ['productWithPricingPublished' => $product->slug])); + + // THEN + $response->assertOk() + ->assertSee('-.--') + ->assertDontSee('class="basket-buttons"', false); + }); + + it('renders prices and add-to-basket button in home slider for an authenticated customer', function (): void { + // GIVEN + seed(ContentSeeder::class); + View::share('PageList', Page::getCached()->mapWithKeys(fn ($page) => [$page->slug->value() => $page])); + Cache::flush(); + actingAs(characterizationCustomer('home-buyer@example.com'), 'frontend'); + characterizationProduct('Produit Vedette', withInco: true, star: true); + + // WHEN + $response = get(route('fo.pages.home')); + + // THEN + $response->assertOk() + ->assertSee('Produit Vedette') + ->assertSee('12,00') + ->assertDontSee('-.--') + ->assertSee('basket-buttons', false); + }); }); diff --git a/tests/Unit/App/Policies/Frontend/ProductPolicyTest.php b/tests/Unit/App/Policies/Frontend/ProductPolicyTest.php index 873bafab..e433f41b 100644 --- a/tests/Unit/App/Policies/Frontend/ProductPolicyTest.php +++ b/tests/Unit/App/Policies/Frontend/ProductPolicyTest.php @@ -107,4 +107,30 @@ describe('Frontend ProductPolicy', function (): void { expect($result)->toBeTrue(); }); }); + + describe('viewPublished', function (): void { + it('allows viewing a published product', function (): void { + // GIVEN + $policy = new ProductPolicy(); + $product = policyTestProduct(status: true, isOrderable: false); + + // WHEN + $result = $policy->viewPublished(null, $product); + + // THEN + expect($result)->toBeTrue(); + }); + + it('rejects viewing an unpublished product', function (): void { + // GIVEN + $policy = new ProductPolicy(); + $product = policyTestProduct(status: false, isOrderable: true); + + // WHEN + $result = $policy->viewPublished(new Customer(), $product); + + // THEN + expect($result)->toBeFalse(); + }); + }); }); From 6663f0f66f88fa1c304315abd1659ca365e839a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 01:30:10 +0100 Subject: [PATCH 095/183] fix(fo): invert is_orderable condition for opacity and coming soon badge --- .../fo/home-parts/sliders/discounts.blade.php | 2 +- .../fo/pages/products/show-info.blade.php | 2 +- .../views/fo/pages/products/show.blade.php | 4 +-- .../Fo/ProductCharacterizationTest.php | 27 +++++++++++++++++-- 4 files changed, 29 insertions(+), 6 deletions(-) diff --git a/resources/views/fo/home-parts/sliders/discounts.blade.php b/resources/views/fo/home-parts/sliders/discounts.blade.php index aa251956..db8daa5e 100644 --- a/resources/views/fo/home-parts/sliders/discounts.blade.php +++ b/resources/views/fo/home-parts/sliders/discounts.blade.php @@ -13,7 +13,7 @@
- @if ($productWithPricing->product->is_orderable) + @if (! $productWithPricing->product->is_orderable) {{ __('Coming soon') }} @endif
diff --git a/resources/views/fo/pages/products/show-info.blade.php b/resources/views/fo/pages/products/show-info.blade.php index 7509d915..e9894a3d 100644 --- a/resources/views/fo/pages/products/show-info.blade.php +++ b/resources/views/fo/pages/products/show-info.blade.php @@ -1,5 +1,5 @@ {{-- blade-formatter-disable --}} -
product->is_orderable) class=" opacity-75" @endif> +
product->is_orderable) class="opacity-75" @endif>

{{ $productWithPricing->product->name }}

diff --git a/resources/views/fo/pages/products/show.blade.php b/resources/views/fo/pages/products/show.blade.php index 30a17289..86069096 100644 --- a/resources/views/fo/pages/products/show.blade.php +++ b/resources/views/fo/pages/products/show.blade.php @@ -9,7 +9,7 @@
-
diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php index be346894..e8f2243f 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php @@ -210,4 +210,50 @@ describe('HomeController', function () { // Regular product price span does NOT have text-danger class ->and($content)->toMatch('/Poulet Standard.*?/s'); }); + + it('escapes decoded HTML payloads in featured product slider description', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached()->mapWithKeys(fn ($page) => [$page->slug->value() => $page])); + + $range = new Range(); + $range->name = 'Volaille'; + $range->slug = 'volaille'; + $range->picture = 'ranges/volaille.jpg'; + $range->picture_alt = 'Volaille'; + $range->picture_title = 'Volaille'; + $range->status = true; + $range->order = 1; + $range->save(); + + $product = new Product(); + $product->id = (string) Uuid::uuid7(); + $product->name = 'Poulet Sûr'; + $product->brand = ProductBrand::loue; + $product->slug = 'poulet-sur'; + $product->description = '

Rôti <img src=x onerror=alert(1)>

'; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt'; + $product->picture_large_title = 'title'; + $product->price = Money::EUR(1500); + $product->invoicing_unit = InvoicingUnit::PCE; + $product->sell_unit = SellUnit::PCE; + $product->tax_rate = TaxRate::TVA_5_5; + $product->stock = 10; + $product->range_id = $range->id; + $product->order = 1; + $product->star = true; + $product->status = true; + $product->save(); + + // WHEN + $response = $this->get('/'); + + // THEN + $response->assertOk(); + $response->assertDontSee('', false); + $response->assertSee('Rôti <img src=x onerror=alert(1)>', false); + }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Products/StoreProductRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Products/StoreProductRequestTest.php index 8c56cdf7..4689e318 100644 --- a/tests/Feature/App/Http/Requests/Bo/Products/StoreProductRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Products/StoreProductRequestTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use App\Http\Requests\Bo\Products\StoreProductRequest; +use Domain\Enums\ProductBrand; use Illuminate\Http\UploadedFile; use Infrastructure\Adapters\Services\AppAdminAuthService; use Money\Currency; @@ -119,4 +120,36 @@ describe('StoreProductRequest', function () { expect($smallValidator->errors()->has('picture'))->toBeTrue() ->and($largeValidator->errors()->has('picture_large'))->toBeTrue(); }); + + it('requires a valid ProductBrand enum value for brand and validates picture alt/title lengths', function () { + // GIVEN + $authService = mock(AppAdminAuthService::class); + $request = new StoreProductRequest($authService, new Currency('EUR')); + $rules = $request->rules(); + + // WHEN + $invalidBrandValidator = validator(['brand' => 'unknown-brand'], ['brand' => $rules['brand']]); + $nullBrandValidator = validator(['brand' => null], ['brand' => $rules['brand']]); + $validBrandValidator = validator(['brand' => ProductBrand::loue->value], ['brand' => $rules['brand']]); + $tooLongAltValidator = validator([ + 'picture_alt' => str_repeat('a', 256), + 'picture_title' => str_repeat('b', 256), + 'picture_large_alt' => str_repeat('c', 256), + 'picture_large_title' => str_repeat('d', 256), + ], [ + 'picture_alt' => $rules['picture_alt'], + 'picture_title' => $rules['picture_title'], + 'picture_large_alt' => $rules['picture_large_alt'], + 'picture_large_title' => $rules['picture_large_title'], + ]); + + // THEN + expect($invalidBrandValidator->fails())->toBeTrue() + ->and($nullBrandValidator->fails())->toBeTrue() + ->and($validBrandValidator->passes())->toBeTrue() + ->and($tooLongAltValidator->errors()->has('picture_alt'))->toBeTrue() + ->and($tooLongAltValidator->errors()->has('picture_title'))->toBeTrue() + ->and($tooLongAltValidator->errors()->has('picture_large_alt'))->toBeTrue() + ->and($tooLongAltValidator->errors()->has('picture_large_title'))->toBeTrue(); + }); }); From 3e4dfdad4e32d10fbcff160139d0307907b821a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 03:10:25 +0100 Subject: [PATCH 102/183] feat(tunnel): detect basket price changes during order finalization --- app/Cqs/Actions/Orders/FinalizeOrder.php | 7 +++ .../Actions/Orders/FinalizeOrderOutput.php | 8 +++ app/Enums/FinalizeOrderStatus.php | 1 + app/Http/Controllers/Fo/TunnelController.php | 1 + .../BasketPriceChangedException.php | 19 ++++++ domain/Services/OrderTunnelService.php | 28 ++++++++- lang/en.json | 1 + lang/fr.json | 1 + .../Controllers/Fo/TunnelControllerTest.php | 42 +++++++++++++ .../App/Actions/Orders/FinalizeOrderTest.php | 58 ++++++++++++----- .../App/Actions/Orders/FinalizeOrderTest.php | 55 ++++++++++++---- .../Services/OrderTunnelServiceTest.php | 62 ++++++++++++++++++- 12 files changed, 251 insertions(+), 32 deletions(-) create mode 100644 domain/Exceptions/OrderTunnel/BasketPriceChangedException.php diff --git a/app/Cqs/Actions/Orders/FinalizeOrder.php b/app/Cqs/Actions/Orders/FinalizeOrder.php index edd13222..84cac1e9 100644 --- a/app/Cqs/Actions/Orders/FinalizeOrder.php +++ b/app/Cqs/Actions/Orders/FinalizeOrder.php @@ -9,11 +9,13 @@ use App\Contracts\Action; use App\Contracts\ActionInput; use App\Contracts\HandlesLockTimeout; use App\Contracts\ProvidesLockKey; +use Domain\Exceptions\OrderTunnel\BasketPriceChangedException; use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException; use Domain\Exceptions\OrderTunnel\InactiveShopperException; use Domain\Exceptions\OrderTunnel\OrderLimitExceededException; use Domain\Exceptions\OrderTunnel\UnorderableProductException; use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException; +use Domain\Ports\Repositories\BasketRepository; use Domain\Services\OrderTunnelService; use Webmozart\Assert\Assert; @@ -33,6 +35,7 @@ final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey { public function __construct( private readonly OrderTunnelService $orderTunnelService, + private readonly BasketRepository $basketRepository, ) { } @@ -72,6 +75,10 @@ final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey try { $order = $this->orderTunnelService->finalizeOrder($builder); + } catch (BasketPriceChangedException $e) { + $this->basketRepository->persist($e->refreshedBasket); + + return FinalizeOrderOutput::basketPriceChanged($e->getMessage()); } catch ( ExpiredPickupTimeSlotException | InactiveShopperException diff --git a/app/Cqs/Actions/Orders/FinalizeOrderOutput.php b/app/Cqs/Actions/Orders/FinalizeOrderOutput.php index 599221eb..a4028001 100644 --- a/app/Cqs/Actions/Orders/FinalizeOrderOutput.php +++ b/app/Cqs/Actions/Orders/FinalizeOrderOutput.php @@ -48,6 +48,14 @@ final readonly class FinalizeOrderOutput ); } + public static function basketPriceChanged(string $errorMessage): self + { + return new self( + status: FinalizeOrderStatus::BASKET_PRICE_CHANGED, + errorMessage: $errorMessage, + ); + } + public static function orderLimitExceeded(string $errorMessage): self { return new self( diff --git a/app/Enums/FinalizeOrderStatus.php b/app/Enums/FinalizeOrderStatus.php index 9953047f..4a2b8416 100644 --- a/app/Enums/FinalizeOrderStatus.php +++ b/app/Enums/FinalizeOrderStatus.php @@ -9,6 +9,7 @@ enum FinalizeOrderStatus case SUCCESS; case EXPIRED_TIME_SLOT; case INACTIVE_SHOPPER; + case BASKET_PRICE_CHANGED; case UNORDERABLE_PRODUCT; case ORDER_LIMIT_EXCEEDED; case WEEKLY_LIMIT_EXCEEDED; diff --git a/app/Http/Controllers/Fo/TunnelController.php b/app/Http/Controllers/Fo/TunnelController.php index c349b10e..d57176e9 100644 --- a/app/Http/Controllers/Fo/TunnelController.php +++ b/app/Http/Controllers/Fo/TunnelController.php @@ -150,6 +150,7 @@ class TunnelController extends Controller 'timeslot' => trans($output->errorMessage ?? ''), ]), FinalizeOrderStatus::INACTIVE_SHOPPER => throw new CustomerNotEmployedException(), + FinalizeOrderStatus::BASKET_PRICE_CHANGED, FinalizeOrderStatus::UNORDERABLE_PRODUCT => to_route('fo.sales.summary')->withErrors([ 'basket' => trans($output->errorMessage ?? ''), ]), diff --git a/domain/Exceptions/OrderTunnel/BasketPriceChangedException.php b/domain/Exceptions/OrderTunnel/BasketPriceChangedException.php new file mode 100644 index 00000000..563dcb5d --- /dev/null +++ b/domain/Exceptions/OrderTunnel/BasketPriceChangedException.php @@ -0,0 +1,19 @@ +items() as $item) { - $refreshedItems[] = $this->productRepository->getBasketProduct($item->id, $item->qty); + $refreshed = $this->productRepository->getBasketProduct($item->id, $item->qty); + + if ($this->hasItemPricingChanged($item, $refreshed)) { + $priceChanged = true; + } + + $refreshedItems[] = $refreshed; } - return new Basket($basket->id, $refreshedItems); + $refreshedBasket = new Basket($basket->id, $refreshedItems); + + if ($priceChanged || ! $refreshedBasket->totalTaxIncluded()->equals($basket->totalTaxIncluded())) { + throw new BasketPriceChangedException($refreshedBasket); + } + + return $refreshedBasket; + } + + private function hasItemPricingChanged(BasketProduct $original, BasketProduct $refreshed): bool + { + return ! $refreshed->unitPriceHt->equals($original->unitPriceHt) + || ! $refreshed->unitDiscount->equals($original->unitDiscount) + || $refreshed->taxRate !== $original->taxRate + || ! $refreshed->totalTtc()->equals($original->totalTtc()); } /** diff --git a/lang/en.json b/lang/en.json index 1afd1c5f..f9765592 100644 --- a/lang/en.json +++ b/lang/en.json @@ -764,6 +764,7 @@ "The order": "The order", "The order deadline has passed. This item will no longer be available for purchase.": "The order deadline has passed. This item will no longer be available for purchase.", "The password must contain": "The password must contain", + "The price of one or more products in your basket has changed.": "The price of one or more products in your basket has changed.", "The publication status is updated according to the scheduled dates. To change the publication status, please edit or remove the corresponding dates.": "The publication status is updated according to the scheduled dates. To change the publication status, please edit or remove the corresponding dates.", "The range associated with the product": "The range associated with the product", "The response is not a streamed response.": "The response is not a streamed response.", diff --git a/lang/fr.json b/lang/fr.json index 035ac78f..9be9c2a8 100644 --- a/lang/fr.json +++ b/lang/fr.json @@ -764,6 +764,7 @@ "The order": "La commande", "The order deadline has passed. This item will no longer be available for purchase.": "La date limite de commande est dépassée. Le remplacement ne sera plus proposé aux clients.", "The password must contain": "Le mot de passe doit contenir", + "The price of one or more products in your basket has changed.": "Le prix d'un ou plusieurs produits de votre panier a changé.", "The publication status is updated according to the scheduled dates. To change the publication status, please edit or remove the corresponding dates.": "La publication est modifiée en concordance avec les dates enregistrées. Pour modifier l'état de publication, veuillez modifier ou enlever les dates correspondantes.", "The range associated with the product": "La gamme associée au produit", "The response is not a streamed response.": "La réponse n'est pas une réponse diffusée.", diff --git a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php index 8e6005ed..c5acc13a 100644 --- a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php @@ -638,6 +638,48 @@ describe('TunnelController', function (): void { ]); }); + it('redirects to basket summary with errors when BasketPriceChangedException occurs on confirmation submit', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + $customer = new Customer(); + $customer->email = new Email('test@example.com'); + $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + + $this->withoutMiddleware([ + CustomerIsEmployed::class, + EnsureCustomerEmailIsVerified::class, + ]); + Gate::before(fn () => true); + + $this->mock(Executor::class, function ($mock): void { + $mock->shouldReceive('execute') + ->once() + ->andReturn(FinalizeOrderOutput::basketPriceChanged( + 'The price of one or more products in your basket has changed.' + )); + }); + + // WHEN + $response = $this->from('/commande/confirmation')->post('/commande/confirmation', [ + 'ok_cgv' => '1', + ]); + + // THEN + $response->assertRedirectToRoute('fo.sales.summary') + ->assertSessionHasErrors([ + 'basket' => trans('The price of one or more products in your basket has changed.'), + ]); + }); + it('redirects back with message when LockTimeout occurs on confirmation submit', function (): void { /** @var \Tests\TestCase $this */ // GIVEN diff --git a/tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php b/tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php index d14d752d..f7555be9 100644 --- a/tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php +++ b/tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php @@ -63,6 +63,8 @@ use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; use Infrastructure\Adapters\Repositories\EloquentProductRepository; use Infrastructure\Adapters\Repositories\EloquentShopperRepository; use Infrastructure\Adapters\Repositories\EloquentShopRepository; +use Infrastructure\Adapters\Repositories\SessionBasketRepository; +use Infrastructure\Adapters\Serializers\BasketSerializer; use Infrastructure\Adapters\Services\CsvGeneratorImpl; use Infrastructure\Adapters\Services\EloquentEmployeeStatisticsService; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; @@ -197,6 +199,8 @@ describe('FinalizeOrder action', function (): void { ->withPickupTimeSlot($shop->getId(), $slot); $session = Session::driver(); + $basketRepo = new SessionBasketRepository($session, 'basket_', new BasketSerializer()); + $basketRepo->persist($basket); $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); $builderManager->save($builder); @@ -227,14 +231,16 @@ describe('FinalizeOrder action', function (): void { ); return [ - 'customer' => $customer, - 'employee' => $employee, - 'shop' => $shop, - 'product' => $product, - 'builderManager' => $builderManager, - 'dispatcher' => $dispatcher, - 'tunnelService' => $tunnelService, - 'executor' => $executor, + 'customer' => $customer, + 'employee' => $employee, + 'shop' => $shop, + 'product' => $product, + 'basketId' => $basket->id, + 'basketRepository' => $basketRepo, + 'builderManager' => $builderManager, + 'dispatcher' => $dispatcher, + 'tunnelService' => $tunnelService, + 'executor' => $executor, ]; } @@ -242,7 +248,7 @@ describe('FinalizeOrder action', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $ctx = buildFinalizeOrderScenario(priceCents: 2000, qty: 2); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); @@ -273,7 +279,7 @@ describe('FinalizeOrder action', function (): void { ->andThrow(new RegateExportFailedException('SMTP transport failure')); $ctx = buildFinalizeOrderScenario(regateService: $failingRegate); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN & THEN expect(fn () => $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()))) @@ -289,7 +295,7 @@ describe('FinalizeOrder action', function (): void { // GIVEN // 210 EUR HT -> > 200 EUR TTC order limit $ctx = buildFinalizeOrderScenario(priceCents: 21000, qty: 1); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); @@ -324,7 +330,7 @@ describe('FinalizeOrder action', function (): void { 'pickup_day' => '2026-11-20 14:00:00', ]); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); @@ -339,7 +345,7 @@ describe('FinalizeOrder action', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $ctx = buildFinalizeOrderScenario(activeEmployee: false); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); @@ -357,7 +363,7 @@ describe('FinalizeOrder action', function (): void { $ctx['product']->status = false; $ctx['product']->saveOrFail(); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); @@ -375,7 +381,7 @@ describe('FinalizeOrder action', function (): void { $ctx = buildFinalizeOrderScenario( pickupAt: CarbonImmutable::parse('2026-11-13 14:00:00', 'Europe/Paris'), ); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); @@ -396,7 +402,7 @@ describe('FinalizeOrder action', function (): void { ->andThrow(new LockTimeoutException('Lock timed out')); $ctx = buildFinalizeOrderScenario(lock: $lock); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); @@ -406,4 +412,24 @@ describe('FinalizeOrder action', function (): void { ->and($output->orderReference)->toBeNull(); $this->assertDatabaseCount('orders', 0); }); + + it('updates session basket and returns BASKET_PRICE_CHANGED when catalog price increases before finalization', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $ctx = buildFinalizeOrderScenario(priceCents: 1000, qty: 2); + $ctx['product']->price = Money::EUR(1500); + $ctx['product']->saveOrFail(); + + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); + + // WHEN + $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); + + // THEN + expect($output->status)->toBe(FinalizeOrderStatus::BASKET_PRICE_CHANGED) + ->and($output->orderReference)->toBeNull() + ->and($ctx['basketRepository']->find($ctx['basketId'])?->totalTaxIncluded()->getAmount())->toBe('3165'); + $this->assertDatabaseCount('orders', 0); + Mail::assertNothingSent(); + }); }); diff --git a/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php b/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php index 0e51c735..cd974949 100644 --- a/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php +++ b/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php @@ -13,14 +13,17 @@ use App\Cqs\Actions\Orders\FinalizeOrderOutput; use App\Enums\FinalizeOrderStatus; use Domain\Builders\OrderBuilderCompleted; use Domain\Enums\OrderStatus; +use Domain\Exceptions\OrderTunnel\BasketPriceChangedException; use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException; use Domain\Exceptions\OrderTunnel\InactiveShopperException; use Domain\Exceptions\OrderTunnel\OrderLimitExceededException; use Domain\Exceptions\OrderTunnel\RegateExportFailedException; use Domain\Exceptions\OrderTunnel\UnorderableProductException; use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException; +use Domain\Models\Entities\Basket; use Domain\Models\Entities\Order; use Domain\Models\ValueObjects\DeliveryAddress; +use Domain\Models\ValueObjects\Entities\BasketId; use Domain\Models\ValueObjects\Entities\OrderId; use Domain\Models\ValueObjects\Entities\ShopId; use Domain\Models\ValueObjects\Entities\ShopperId; @@ -31,6 +34,7 @@ use Domain\Models\ValueObjects\PickupTimeSlot; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; +use Domain\Ports\Repositories\BasketRepository; use Domain\Services\OrderTunnelService; use Money\Money; use Ramsey\Uuid\Uuid; @@ -75,7 +79,7 @@ describe('FinalizeOrder', function (): void { ->with($builder) ->andReturn($order); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $result = $action($input); @@ -98,7 +102,7 @@ describe('FinalizeOrder', function (): void { ->with($builder) ->andThrow(new ExpiredPickupTimeSlotException('Invalid or unavailable time slot')); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $result = $action($input); @@ -123,7 +127,7 @@ describe('FinalizeOrder', function (): void { ->with($builder) ->andThrow(new InactiveShopperException('Employee account is no longer active.')); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $result = $action($input); @@ -146,7 +150,7 @@ describe('FinalizeOrder', function (): void { ->with($builder) ->andThrow(new UnorderableProductException('One or more products in your basket are no longer available for order.')); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $result = $action($input); @@ -169,7 +173,7 @@ describe('FinalizeOrder', function (): void { ->with($builder) ->andThrow(new OrderLimitExceededException()); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $result = $action($input); @@ -192,7 +196,7 @@ describe('FinalizeOrder', function (): void { ->with($builder) ->andThrow(new WeeklyLimitExceededException()); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $result = $action($input); @@ -215,7 +219,7 @@ describe('FinalizeOrder', function (): void { ->with($builder) ->andThrow(new RegateExportFailedException('SMTP transport error')); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN expect(fn () => $action($input)) @@ -226,7 +230,7 @@ describe('FinalizeOrder', function (): void { it('has Locked attribute with expected TTL and wait seconds and implements lock contracts', function (): void { // GIVEN $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); $reflection = new \ReflectionClass(FinalizeOrder::class); $attributes = $reflection->getAttributes(Locked::class); @@ -249,7 +253,7 @@ describe('FinalizeOrder', function (): void { $orderTunnelService = \Mockery::mock(OrderTunnelService::class); $orderTunnelService->shouldNotReceive('getBuilderCompletedOrFail'); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $key = $action->lockKey($input); @@ -273,7 +277,7 @@ describe('FinalizeOrder', function (): void { ->once() ->andReturn($builder); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $key = $action->lockKey($input); @@ -287,7 +291,7 @@ describe('FinalizeOrder', function (): void { $input = new FinalizeOrderInput(); $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $result = $action->onLockTimeout($input); @@ -298,4 +302,33 @@ describe('FinalizeOrder', function (): void { ->and($result->orderReference)->toBeNull() ->and($result->errorMessage)->toBeNull(); }); + + it('persists refreshed basket and returns basketPriceChanged output when finalizeOrder throws BasketPriceChangedException', function (): void { + // GIVEN + $input = new FinalizeOrderInput(); + $builder = \Mockery::mock(OrderBuilderCompleted::class); + $refreshedBasket = new Basket(new BasketId(Uuid::uuid7()), []); + $orderTunnelService = \Mockery::mock(OrderTunnelService::class); + $orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder); + $orderTunnelService->shouldReceive('finalizeOrder') + ->once() + ->with($builder) + ->andThrow(new BasketPriceChangedException($refreshedBasket)); + + $basketRepository = \Mockery::mock(BasketRepository::class); + $basketRepository->shouldReceive('persist') + ->once() + ->with($refreshedBasket); + + $action = new FinalizeOrder($orderTunnelService, $basketRepository); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeInstanceOf(FinalizeOrderOutput::class) + ->and($result->status)->toBe(FinalizeOrderStatus::BASKET_PRICE_CHANGED) + ->and($result->orderReference)->toBeNull() + ->and($result->errorMessage)->toBe('The price of one or more products in your basket has changed.'); + }); }); diff --git a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php index bbd60cf6..a1a2f3bd 100644 --- a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php +++ b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php @@ -12,6 +12,7 @@ use Domain\Builders\OrderBuilderCompleted; use Domain\Builders\OrderBuilderWithBasket; use Domain\Enums\TaxRate; use Domain\Enums\Units\OrderUnit; +use Domain\Exceptions\OrderTunnel\BasketPriceChangedException; use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException; use Domain\Exceptions\OrderTunnel\InactiveShopperException; use Domain\Exceptions\OrderTunnel\MissingOrderBuilderException; @@ -650,8 +651,8 @@ describe('OrderTunnelService', function (): void { id: $id, name: 'Updated Product Name', qty: $qty, - unitPriceHt: Money::EUR(250), - unitDiscount: Money::EUR(50), + unitPriceHt: Money::EUR(100), + unitDiscount: Money::EUR(0), taxRate: TaxRate::TVA_20, weightGrams: 200, brand: null, @@ -662,7 +663,7 @@ describe('OrderTunnelService', function (): void { description: null, weightVariable: false, discountRate: DiscountRate::fromRatio(0.0), - priceKgTtc: Money::EUR(240) + priceKgTtc: Money::EUR(120) ); }); @@ -682,6 +683,61 @@ describe('OrderTunnelService', function (): void { expect($order)->toBeInstanceOf(Order::class); }); + it('throws BasketPriceChangedException with refreshed basket when product price changes before finalization', function (): void { + // GIVEN + $builder = createTestBuilder(completed: true); + $shopperRepo = mock(ShopperRepository::class); + $shopperRepo->shouldNotReceive('getByIdOrFail'); + + $orderRepo = mock(OrderRepository::class); + $orderRepo->shouldNotReceive('persist'); + + $eventDispatcher = mock(DomainEventDispatcher::class); + $eventDispatcher->shouldNotReceive('dispatch'); + + $productRepo = mock(ProductRepository::class); + $productRepo->shouldReceive('getBasketProduct')->once()->andReturnUsing(function ($id, $qty) { + return new BasketProduct( + id: $id, + name: 'Updated Price Product', + qty: $qty, + unitPriceHt: Money::EUR(250), + unitDiscount: Money::EUR(50), + taxRate: TaxRate::TVA_20, + weightGrams: 200, + brand: null, + incoId: new IncoId(123), + orderUnit: OrderUnit::PCE, + slug: 'updated-price-product', + picture: null, + description: null, + weightVariable: false, + discountRate: DiscountRate::fromRatio(0.2), + priceKgTtc: Money::EUR(240) + ); + }); + + $service = createOrderTunnelService( + productRepository: $productRepo, + shopperRepository: $shopperRepo, + orderRepository: $orderRepo, + eventDispatcher: $eventDispatcher + ); + + // WHEN + $caught = null; + + try { + $service->finalizeOrder($builder); + } catch (BasketPriceChangedException $e) { + $caught = $e; + } + + // THEN + expect($caught)->toBeInstanceOf(BasketPriceChangedException::class) + ->and($caught?->refreshedBasket->totalTaxIncluded()->getAmount())->toBe('240'); + }); + it('throws ExpiredPickupTimeSlotException when finalizing order with an expired or unavailable pickup time slot', function (): void { // GIVEN $basket = createTestBasket(1); From 3d1c798c08e1f64d05dd1e27694f88d41ea4d6fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 03:32:57 +0100 Subject: [PATCH 103/183] refactor(orders): split pending placement, non-transactional Regate SMTP export and final confirmation --- app/Attributes/WithoutTransaction.php | 10 + app/Cqs/Actions/Orders/CancelPendingOrder.php | 41 ++ .../Orders/CancelPendingOrderInput.php | 16 + .../Orders/CancelPendingOrderOutput.php | 11 + app/Cqs/Actions/Orders/ConfirmPlacedOrder.php | 43 ++ .../Orders/ConfirmPlacedOrderInput.php | 16 + .../Orders/ConfirmPlacedOrderOutput.php | 11 + .../Actions/Orders/ExportOrderToRegate.php | 77 +++ .../Orders/ExportOrderToRegateInput.php | 16 + .../Orders/ExportOrderToRegateOutput.php | 12 + ...inalizeOrder.php => PlacePendingOrder.php} | 46 +- ...erInput.php => PlacePendingOrderInput.php} | 2 +- ...Output.php => PlacePendingOrderOutput.php} | 27 +- ...Status.php => PlacePendingOrderStatus.php} | 4 +- app/Http/Controllers/Fo/TunnelController.php | 91 +++- .../Fo/Orders/ConfirmOrderRequest.php | 6 +- app/Services/ActionExecutorService.php | 31 +- domain/Models/Entities/Order.php | 50 +- domain/Services/OrderService.php | 31 ++ domain/Services/OrderTunnelService.php | 108 +++- .../EloquentEmployeeStatisticsService.php | 2 +- .../Controllers/Fo/TunnelControllerTest.php | 138 +++++- .../Fo/Orders/ConfirmOrderRequestTest.php | 8 +- .../App/Actions/Orders/FinalizeOrderTest.php | 435 ---------------- .../Actions/Orders/PlacePendingOrderTest.php | 466 ++++++++++++++++++ .../Services/ActionExecutorServiceTest.php | 58 +++ .../EloquentEmployeeStatisticsServiceTest.php | 52 ++ .../App/Actions/Orders/FinalizeOrderTest.php | 334 ------------- ...est.php => PlacePendingOrderInputTest.php} | 8 +- .../Actions/Orders/PlacePendingOrderTest.php | 307 ++++++++++++ .../Unit/Domain/Models/Entities/OrderTest.php | 63 +++ .../Services/OrderTunnelServiceTest.php | 110 +++++ 32 files changed, 1754 insertions(+), 876 deletions(-) create mode 100644 app/Attributes/WithoutTransaction.php create mode 100644 app/Cqs/Actions/Orders/CancelPendingOrder.php create mode 100644 app/Cqs/Actions/Orders/CancelPendingOrderInput.php create mode 100644 app/Cqs/Actions/Orders/CancelPendingOrderOutput.php create mode 100644 app/Cqs/Actions/Orders/ConfirmPlacedOrder.php create mode 100644 app/Cqs/Actions/Orders/ConfirmPlacedOrderInput.php create mode 100644 app/Cqs/Actions/Orders/ConfirmPlacedOrderOutput.php create mode 100644 app/Cqs/Actions/Orders/ExportOrderToRegate.php create mode 100644 app/Cqs/Actions/Orders/ExportOrderToRegateInput.php create mode 100644 app/Cqs/Actions/Orders/ExportOrderToRegateOutput.php rename app/Cqs/Actions/Orders/{FinalizeOrder.php => PlacePendingOrder.php} (60%) rename app/Cqs/Actions/Orders/{FinalizeOrderInput.php => PlacePendingOrderInput.php} (78%) rename app/Cqs/Actions/Orders/{FinalizeOrderOutput.php => PlacePendingOrderOutput.php} (62%) rename app/Enums/{FinalizeOrderStatus.php => PlacePendingOrderStatus.php} (82%) delete mode 100644 tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php create mode 100644 tests/Integration/WithApp/App/Actions/Orders/PlacePendingOrderTest.php delete mode 100644 tests/Unit/App/Actions/Orders/FinalizeOrderTest.php rename tests/Unit/App/Actions/Orders/{FinalizeOrderInputTest.php => PlacePendingOrderInputTest.php} (69%) create mode 100644 tests/Unit/App/Actions/Orders/PlacePendingOrderTest.php diff --git a/app/Attributes/WithoutTransaction.php b/app/Attributes/WithoutTransaction.php new file mode 100644 index 00000000..4de4f016 --- /dev/null +++ b/app/Attributes/WithoutTransaction.php @@ -0,0 +1,10 @@ + + */ +final class CancelPendingOrder implements Action +{ + public function __construct( + private readonly OrderTunnelService $orderTunnelService, + ) { + } + + /** + * @param \App\Cqs\Actions\Orders\CancelPendingOrderInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): CancelPendingOrderOutput + { + Assert::isInstanceOf($input, CancelPendingOrderInput::class); + + try { + $this->orderTunnelService->cancelPendingOrder($input->orderId); + } catch (\DomainException) { + return CancelPendingOrderOutput::NOT_FOUND; + } + + return CancelPendingOrderOutput::CANCELLED; + } +} diff --git a/app/Cqs/Actions/Orders/CancelPendingOrderInput.php b/app/Cqs/Actions/Orders/CancelPendingOrderInput.php new file mode 100644 index 00000000..2ee4f740 --- /dev/null +++ b/app/Cqs/Actions/Orders/CancelPendingOrderInput.php @@ -0,0 +1,16 @@ + + */ +final class ConfirmPlacedOrder implements Action +{ + public function __construct( + private readonly OrderTunnelService $orderTunnelService, + ) { + } + + /** + * @param \App\Cqs\Actions\Orders\ConfirmPlacedOrderInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): ConfirmPlacedOrderOutput + { + Assert::isInstanceOf($input, ConfirmPlacedOrderInput::class); + + try { + $this->orderTunnelService->confirmPlacedOrder($input->orderId); + } catch (\Throwable $e) { + report($e); + + return ConfirmPlacedOrderOutput::FAILED; + } + + return ConfirmPlacedOrderOutput::CONFIRMED; + } +} diff --git a/app/Cqs/Actions/Orders/ConfirmPlacedOrderInput.php b/app/Cqs/Actions/Orders/ConfirmPlacedOrderInput.php new file mode 100644 index 00000000..d52dcf73 --- /dev/null +++ b/app/Cqs/Actions/Orders/ConfirmPlacedOrderInput.php @@ -0,0 +1,16 @@ + + * @implements \App\Contracts\ProvidesLockKey<\App\Cqs\Actions\Orders\ExportOrderToRegateInput> + * @implements \App\Contracts\HandlesLockTimeout< + * \App\Cqs\Actions\Orders\ExportOrderToRegateInput, + * \App\Cqs\Actions\Orders\ExportOrderToRegateOutput + * > + */ +#[Locked(ttlSeconds: 30, waitSeconds: 10)] +#[WithoutTransaction] +final class ExportOrderToRegate implements Action, HandlesLockTimeout, ProvidesLockKey +{ + public function __construct( + private readonly OrderTunnelService $orderTunnelService, + ) { + } + + /** + * @param \App\Cqs\Actions\Orders\ExportOrderToRegateInput $input + */ + #[\Override] + public function lockKey(ActionInput $input): string + { + Assert::isInstanceOf($input, ExportOrderToRegateInput::class); + + return "order:export:{$input->orderId->value}"; + } + + /** + * @param \App\Cqs\Actions\Orders\ExportOrderToRegateInput $input + */ + #[\Override] + public function onLockTimeout(ActionInput $input): ExportOrderToRegateOutput + { + Assert::isInstanceOf($input, ExportOrderToRegateInput::class); + + return ExportOrderToRegateOutput::LOCK_TIMEOUT; + } + + /** + * @param \App\Cqs\Actions\Orders\ExportOrderToRegateInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): ExportOrderToRegateOutput + { + Assert::isInstanceOf($input, ExportOrderToRegateInput::class); + + try { + $this->orderTunnelService->exportOrderToRegate($input->orderId); + } catch (RegateExportFailedException $e) { + report($e); + + return ExportOrderToRegateOutput::FAILED; + } + + return ExportOrderToRegateOutput::SENT; + } +} diff --git a/app/Cqs/Actions/Orders/ExportOrderToRegateInput.php b/app/Cqs/Actions/Orders/ExportOrderToRegateInput.php new file mode 100644 index 00000000..df98e15d --- /dev/null +++ b/app/Cqs/Actions/Orders/ExportOrderToRegateInput.php @@ -0,0 +1,16 @@ + - * @implements \App\Contracts\ProvidesLockKey<\App\Cqs\Actions\Orders\FinalizeOrderInput> + * @implements \App\Contracts\ProvidesLockKey<\App\Cqs\Actions\Orders\PlacePendingOrderInput> * @implements \App\Contracts\HandlesLockTimeout< - * \App\Cqs\Actions\Orders\FinalizeOrderInput, - * \App\Cqs\Actions\Orders\FinalizeOrderOutput + * \App\Cqs\Actions\Orders\PlacePendingOrderInput, + * \App\Cqs\Actions\Orders\PlacePendingOrderOutput * > */ #[Locked(ttlSeconds: 30, waitSeconds: 10)] -final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey +final class PlacePendingOrder implements Action, HandlesLockTimeout, ProvidesLockKey { public function __construct( private readonly OrderTunnelService $orderTunnelService, @@ -40,12 +40,12 @@ final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey } /** - * @param \App\Cqs\Actions\Orders\FinalizeOrderInput $input + * @param \App\Cqs\Actions\Orders\PlacePendingOrderInput $input */ #[\Override] public function lockKey(ActionInput $input): string { - Assert::isInstanceOf($input, FinalizeOrderInput::class); + Assert::isInstanceOf($input, PlacePendingOrderInput::class); $shopperId = $input->shopperId ?? $this->orderTunnelService->getBuilderCompletedOrFail()->getShopperId(); @@ -53,32 +53,32 @@ final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey } /** - * @param \App\Cqs\Actions\Orders\FinalizeOrderInput $input + * @param \App\Cqs\Actions\Orders\PlacePendingOrderInput $input */ #[\Override] - public function onLockTimeout(ActionInput $input): FinalizeOrderOutput + public function onLockTimeout(ActionInput $input): PlacePendingOrderOutput { - Assert::isInstanceOf($input, FinalizeOrderInput::class); + Assert::isInstanceOf($input, PlacePendingOrderInput::class); - return FinalizeOrderOutput::lockTimeout(); + return PlacePendingOrderOutput::lockTimeout(); } /** - * @param \App\Cqs\Actions\Orders\FinalizeOrderInput $input + * @param \App\Cqs\Actions\Orders\PlacePendingOrderInput $input */ #[\Override] - public function __invoke(ActionInput $input): FinalizeOrderOutput + public function __invoke(ActionInput $input): PlacePendingOrderOutput { - Assert::isInstanceOf($input, FinalizeOrderInput::class); + Assert::isInstanceOf($input, PlacePendingOrderInput::class); $builder = $this->orderTunnelService->getBuilderCompletedOrFail(); try { - $order = $this->orderTunnelService->finalizeOrder($builder); + $order = $this->orderTunnelService->placePendingOrder($builder); } catch (BasketPriceChangedException $e) { $this->basketRepository->persist($e->refreshedBasket); - return FinalizeOrderOutput::basketPriceChanged($e->getMessage()); + return PlacePendingOrderOutput::basketPriceChanged($e->getMessage()); } catch ( ExpiredPickupTimeSlotException | InactiveShopperException @@ -87,14 +87,14 @@ final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey | WeeklyLimitExceededException $e ) { return match (true) { - $e instanceof ExpiredPickupTimeSlotException => FinalizeOrderOutput::expiredTimeSlot($e->getMessage()), - $e instanceof InactiveShopperException => FinalizeOrderOutput::inactiveShopper($e->getMessage()), - $e instanceof UnorderableProductException => FinalizeOrderOutput::unorderableProduct($e->getMessage()), - $e instanceof OrderLimitExceededException => FinalizeOrderOutput::orderLimitExceeded($e->getMessage()), - $e instanceof WeeklyLimitExceededException => FinalizeOrderOutput::weeklyLimitExceeded($e->getMessage()), + $e instanceof ExpiredPickupTimeSlotException => PlacePendingOrderOutput::expiredTimeSlot($e->getMessage()), + $e instanceof InactiveShopperException => PlacePendingOrderOutput::inactiveShopper($e->getMessage()), + $e instanceof UnorderableProductException => PlacePendingOrderOutput::unorderableProduct($e->getMessage()), + $e instanceof OrderLimitExceededException => PlacePendingOrderOutput::orderLimitExceeded($e->getMessage()), + $e instanceof WeeklyLimitExceededException => PlacePendingOrderOutput::weeklyLimitExceeded($e->getMessage()), }; } - return FinalizeOrderOutput::success($order->reference); + return PlacePendingOrderOutput::pendingCreated($order->id(), $order->reference); } } diff --git a/app/Cqs/Actions/Orders/FinalizeOrderInput.php b/app/Cqs/Actions/Orders/PlacePendingOrderInput.php similarity index 78% rename from app/Cqs/Actions/Orders/FinalizeOrderInput.php rename to app/Cqs/Actions/Orders/PlacePendingOrderInput.php index 9e9b6f75..3ca77a0e 100644 --- a/app/Cqs/Actions/Orders/FinalizeOrderInput.php +++ b/app/Cqs/Actions/Orders/PlacePendingOrderInput.php @@ -7,7 +7,7 @@ namespace App\Cqs\Actions\Orders; use App\Contracts\ActionInput; use Domain\Models\ValueObjects\Entities\ShopperId; -final readonly class FinalizeOrderInput implements ActionInput +final readonly class PlacePendingOrderInput implements ActionInput { public function __construct( public ?ShopperId $shopperId = null, diff --git a/app/Cqs/Actions/Orders/FinalizeOrderOutput.php b/app/Cqs/Actions/Orders/PlacePendingOrderOutput.php similarity index 62% rename from app/Cqs/Actions/Orders/FinalizeOrderOutput.php rename to app/Cqs/Actions/Orders/PlacePendingOrderOutput.php index a4028001..bb0d61f9 100644 --- a/app/Cqs/Actions/Orders/FinalizeOrderOutput.php +++ b/app/Cqs/Actions/Orders/PlacePendingOrderOutput.php @@ -4,22 +4,25 @@ declare(strict_types=1); namespace App\Cqs\Actions\Orders; -use App\Enums\FinalizeOrderStatus; +use App\Enums\PlacePendingOrderStatus; +use Domain\Models\ValueObjects\Entities\OrderId; use Domain\Models\ValueObjects\OrderReference; -final readonly class FinalizeOrderOutput +final readonly class PlacePendingOrderOutput { private function __construct( - public FinalizeOrderStatus $status, + public PlacePendingOrderStatus $status, + public ?OrderId $orderId = null, public ?OrderReference $orderReference = null, public ?string $errorMessage = null, ) { } - public static function success(OrderReference $orderReference): self + public static function pendingCreated(OrderId $orderId, OrderReference $orderReference): self { return new self( - status: FinalizeOrderStatus::SUCCESS, + status: PlacePendingOrderStatus::PENDING_CREATED, + orderId: $orderId, orderReference: $orderReference, ); } @@ -27,7 +30,7 @@ final readonly class FinalizeOrderOutput public static function expiredTimeSlot(string $errorMessage): self { return new self( - status: FinalizeOrderStatus::EXPIRED_TIME_SLOT, + status: PlacePendingOrderStatus::EXPIRED_TIME_SLOT, errorMessage: $errorMessage, ); } @@ -35,7 +38,7 @@ final readonly class FinalizeOrderOutput public static function inactiveShopper(string $errorMessage): self { return new self( - status: FinalizeOrderStatus::INACTIVE_SHOPPER, + status: PlacePendingOrderStatus::INACTIVE_SHOPPER, errorMessage: $errorMessage, ); } @@ -43,7 +46,7 @@ final readonly class FinalizeOrderOutput public static function unorderableProduct(string $errorMessage): self { return new self( - status: FinalizeOrderStatus::UNORDERABLE_PRODUCT, + status: PlacePendingOrderStatus::UNORDERABLE_PRODUCT, errorMessage: $errorMessage, ); } @@ -51,7 +54,7 @@ final readonly class FinalizeOrderOutput public static function basketPriceChanged(string $errorMessage): self { return new self( - status: FinalizeOrderStatus::BASKET_PRICE_CHANGED, + status: PlacePendingOrderStatus::BASKET_PRICE_CHANGED, errorMessage: $errorMessage, ); } @@ -59,7 +62,7 @@ final readonly class FinalizeOrderOutput public static function orderLimitExceeded(string $errorMessage): self { return new self( - status: FinalizeOrderStatus::ORDER_LIMIT_EXCEEDED, + status: PlacePendingOrderStatus::ORDER_LIMIT_EXCEEDED, errorMessage: $errorMessage, ); } @@ -67,7 +70,7 @@ final readonly class FinalizeOrderOutput public static function weeklyLimitExceeded(string $errorMessage): self { return new self( - status: FinalizeOrderStatus::WEEKLY_LIMIT_EXCEEDED, + status: PlacePendingOrderStatus::WEEKLY_LIMIT_EXCEEDED, errorMessage: $errorMessage, ); } @@ -75,7 +78,7 @@ final readonly class FinalizeOrderOutput public static function lockTimeout(): self { return new self( - status: FinalizeOrderStatus::LOCK_TIMEOUT, + status: PlacePendingOrderStatus::LOCK_TIMEOUT, ); } } diff --git a/app/Enums/FinalizeOrderStatus.php b/app/Enums/PlacePendingOrderStatus.php similarity index 82% rename from app/Enums/FinalizeOrderStatus.php rename to app/Enums/PlacePendingOrderStatus.php index 4a2b8416..3efc0a1d 100644 --- a/app/Enums/FinalizeOrderStatus.php +++ b/app/Enums/PlacePendingOrderStatus.php @@ -4,9 +4,9 @@ declare(strict_types=1); namespace App\Enums; -enum FinalizeOrderStatus +enum PlacePendingOrderStatus { - case SUCCESS; + case PENDING_CREATED; case EXPIRED_TIME_SLOT; case INACTIVE_SHOPPER; case BASKET_PRICE_CHANGED; diff --git a/app/Http/Controllers/Fo/TunnelController.php b/app/Http/Controllers/Fo/TunnelController.php index d57176e9..489ffa83 100644 --- a/app/Http/Controllers/Fo/TunnelController.php +++ b/app/Http/Controllers/Fo/TunnelController.php @@ -6,9 +6,17 @@ namespace App\Http\Controllers\Fo; use App\Contracts\Executor; use App\Cqs\Actions\Orders\ApplyPickTimeSlot; -use App\Cqs\Actions\Orders\FinalizeOrder; -use App\Cqs\Actions\Orders\FinalizeOrderOutput; +use App\Cqs\Actions\Orders\CancelPendingOrder; +use App\Cqs\Actions\Orders\CancelPendingOrderInput; +use App\Cqs\Actions\Orders\ConfirmPlacedOrder; +use App\Cqs\Actions\Orders\ConfirmPlacedOrderInput; +use App\Cqs\Actions\Orders\ConfirmPlacedOrderOutput; +use App\Cqs\Actions\Orders\ExportOrderToRegate; +use App\Cqs\Actions\Orders\ExportOrderToRegateInput; +use App\Cqs\Actions\Orders\ExportOrderToRegateOutput; use App\Cqs\Actions\Orders\InitializeOrderTunnel; +use App\Cqs\Actions\Orders\PlacePendingOrder; +use App\Cqs\Actions\Orders\PlacePendingOrderOutput; use App\Cqs\Queries\Orders\GetBasketSummaryQuery; use App\Cqs\Queries\Orders\GetBasketSummaryQueryInput; use App\Cqs\Queries\Orders\GetOrderConfirmationQuery; @@ -18,7 +26,7 @@ use App\Cqs\Queries\Orders\GetPickTimeSlotQueryInput; use App\Cqs\Queries\Orders\GetTunnelOrderConfirmedQuery; use App\Cqs\Queries\Orders\GetTunnelOrderConfirmedQueryInput; use App\Enums\ApplyPickTimeSlotStatus; -use App\Enums\FinalizeOrderStatus; +use App\Enums\PlacePendingOrderStatus; use App\Exceptions\CustomerNotEmployedException; use App\Http\Controllers\Controller; use App\Http\Requests\Fo\Orders\ConfirmOrderRequest; @@ -130,33 +138,78 @@ class TunnelController extends Controller public function confirmationSubmit( ConfirmOrderRequest $request, - FinalizeOrder $action + PlacePendingOrder $placePendingOrder, + ExportOrderToRegate $exportOrderToRegate, + ConfirmPlacedOrder $confirmPlacedOrder, + CancelPendingOrder $cancelPendingOrder, ): RedirectResponse { $this->authorize('canFinalizeOrder', OrderTunnelStep::class); - /** @var FinalizeOrderOutput $output */ - $output = $this->executor->execute( - $action, - $request->toFinalizeOrderInput() + /** @var PlacePendingOrderOutput $placeOutput */ + $placeOutput = $this->executor->execute( + $placePendingOrder, + $request->toPlacePendingOrderInput() ); - return match ($output->status) { - FinalizeOrderStatus::SUCCESS => to_route( + if ($placeOutput->status !== PlacePendingOrderStatus::PENDING_CREATED) { + return $this->redirectOnPendingFailure($placeOutput); + } + + $orderId = $placeOutput->orderId + ?? throw new \LogicException('Order ID is missing on pending created output.'); + $orderReference = $placeOutput->orderReference + ?? throw new \LogicException('Order reference is missing on pending created output.'); + + /** @var ExportOrderToRegateOutput $exportOutput */ + $exportOutput = $this->executor->execute( + $exportOrderToRegate, + new ExportOrderToRegateInput($orderId) + ); + + if ($exportOutput !== ExportOrderToRegateOutput::SENT) { + $this->executor->execute($cancelPendingOrder, new CancelPendingOrderInput($orderId)); + + return to_route('fo.sales.confirmation')->with( + 'message', + __('An error occurred while validating your order. Please try again later.') + ); + } + + /** @var ConfirmPlacedOrderOutput $confirmOutput */ + $confirmOutput = $this->executor->execute( + $confirmPlacedOrder, + new ConfirmPlacedOrderInput($orderId) + ); + + return match ($confirmOutput) { + ConfirmPlacedOrderOutput::CONFIRMED => to_route( 'fo.sales.confirmation.show-confirmed', - (string) ($output->orderReference - ?? throw new \LogicException('Order reference is missing on success output.')) + (string) $orderReference ), - FinalizeOrderStatus::EXPIRED_TIME_SLOT => to_route('fo.sales.pick-time-slot')->withErrors([ + ConfirmPlacedOrderOutput::FAILED => to_route('fo.sales.confirmation')->with( + 'message', + __('An error occurred while validating your order. Please try again later.') + ), + }; + } + + private function redirectOnPendingFailure(PlacePendingOrderOutput $output): RedirectResponse + { + return match ($output->status) { + PlacePendingOrderStatus::PENDING_CREATED => throw new \LogicException( + 'Unexpected PENDING_CREATED status in failure handler.' + ), + PlacePendingOrderStatus::EXPIRED_TIME_SLOT => to_route('fo.sales.pick-time-slot')->withErrors([ 'timeslot' => trans($output->errorMessage ?? ''), ]), - FinalizeOrderStatus::INACTIVE_SHOPPER => throw new CustomerNotEmployedException(), - FinalizeOrderStatus::BASKET_PRICE_CHANGED, - FinalizeOrderStatus::UNORDERABLE_PRODUCT => to_route('fo.sales.summary')->withErrors([ + PlacePendingOrderStatus::INACTIVE_SHOPPER => throw new CustomerNotEmployedException(), + PlacePendingOrderStatus::BASKET_PRICE_CHANGED, + PlacePendingOrderStatus::UNORDERABLE_PRODUCT => to_route('fo.sales.summary')->withErrors([ 'basket' => trans($output->errorMessage ?? ''), ]), - FinalizeOrderStatus::ORDER_LIMIT_EXCEEDED, - FinalizeOrderStatus::WEEKLY_LIMIT_EXCEEDED => back()->with('message', $output->errorMessage), - FinalizeOrderStatus::LOCK_TIMEOUT => back()->with( + PlacePendingOrderStatus::ORDER_LIMIT_EXCEEDED, + PlacePendingOrderStatus::WEEKLY_LIMIT_EXCEEDED => back()->with('message', $output->errorMessage), + PlacePendingOrderStatus::LOCK_TIMEOUT => back()->with( 'message', __('Your order is already being processed. Please wait a moment and try again.') ), diff --git a/app/Http/Requests/Fo/Orders/ConfirmOrderRequest.php b/app/Http/Requests/Fo/Orders/ConfirmOrderRequest.php index 487adf43..f96721f7 100644 --- a/app/Http/Requests/Fo/Orders/ConfirmOrderRequest.php +++ b/app/Http/Requests/Fo/Orders/ConfirmOrderRequest.php @@ -4,7 +4,7 @@ declare(strict_types=1); namespace App\Http\Requests\Fo\Orders; -use App\Cqs\Actions\Orders\FinalizeOrderInput; +use App\Cqs\Actions\Orders\PlacePendingOrderInput; use Illuminate\Foundation\Http\FormRequest; use Infrastructure\Adapters\Services\AppCustomerAuthService; @@ -20,11 +20,11 @@ class ConfirmOrderRequest extends FormRequest return $this->authService->check(); } - public function toFinalizeOrderInput(): FinalizeOrderInput + public function toPlacePendingOrderInput(): PlacePendingOrderInput { $customer = $this->authService->getCustomerAsMandatory(); - return new FinalizeOrderInput( + return new PlacePendingOrderInput( shopperId: $customer->getId(), ); } diff --git a/app/Services/ActionExecutorService.php b/app/Services/ActionExecutorService.php index b32c0e9c..453cd647 100644 --- a/app/Services/ActionExecutorService.php +++ b/app/Services/ActionExecutorService.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Services; use App\Attributes\Locked; +use App\Attributes\WithoutTransaction; use App\Contracts\Action; use App\Contracts\ActionInput; use App\Contracts\Executor; @@ -102,6 +103,18 @@ final class ActionExecutorService implements Executor return ($attributes[0] ?? null)?->newInstance(); } + /** + * @template TAction of Action + * + * @param TAction $executable + */ + private function hasWithoutTransactionAttribute(Action $executable): bool + { + $reflection = new \ReflectionClass($executable); + + return $reflection->getAttributes(WithoutTransaction::class) !== []; + } + /** * @template TAction of Action * @template TActionInput of ActionInput @@ -205,14 +218,18 @@ final class ActionExecutorService implements Executor { $this->eventDispatcher->beginBuffering(); + $run = function () use ($executable, $input, $actionName): mixed { + $result = $executable($input); + + $this->logger->info("[Action] Succeeded {$actionName}"); + + return $result; + }; + try { - return DB::transaction(function () use ($executable, $input, $actionName): mixed { - $result = $executable($input); - - $this->logger->info("[Action] Succeeded {$actionName}"); - - return $result; - }); + return $this->hasWithoutTransactionAttribute($executable) + ? $run() + : DB::transaction($run); } catch (\Throwable $e) { $this->eventDispatcher->discard(); diff --git a/domain/Models/Entities/Order.php b/domain/Models/Entities/Order.php index 6156e564..dccf4056 100644 --- a/domain/Models/Entities/Order.php +++ b/domain/Models/Entities/Order.php @@ -71,6 +71,34 @@ final class Order implements Entity $this->status = OrderStatus::CANCELED; } + public function validate(): void + { + if ($this->status === OrderStatus::CANCELED) { + throw new \DomainException('Cannot validate a canceled order.'); + } + + $this->status = OrderStatus::VALIDATED; + } + + public static function pendingFromBasket( + OrderId $id, + OrderReference $reference, + Basket $basket, + PickupTimeSlot $pickupTimeSlot, + Shopper $shopper, + Shop $shop + ): self { + return self::buildFromBasket( + id: $id, + reference: $reference, + basket: $basket, + pickupTimeSlot: $pickupTimeSlot, + shopper: $shopper, + shop: $shop, + status: OrderStatus::WAITING, + ); + } + public static function fromBasket( OrderId $id, OrderReference $reference, @@ -78,6 +106,26 @@ final class Order implements Entity PickupTimeSlot $pickupTimeSlot, Shopper $shopper, Shop $shop + ): self { + return self::buildFromBasket( + id: $id, + reference: $reference, + basket: $basket, + pickupTimeSlot: $pickupTimeSlot, + shopper: $shopper, + shop: $shop, + status: OrderStatus::VALIDATED, + ); + } + + private static function buildFromBasket( + OrderId $id, + OrderReference $reference, + Basket $basket, + PickupTimeSlot $pickupTimeSlot, + Shopper $shopper, + Shop $shop, + OrderStatus $status ): self { $lines = array_map( fn (BasketProduct $item) => OrderLine::fromBasketProduct($item), @@ -91,7 +139,7 @@ final class Order implements Entity employee: OrderEmployee::fromShopper($shopper), deliveryAddress: DeliveryAddress::fromShop($shop), pickupTimeSlot: clone $pickupTimeSlot, - status: OrderStatus::VALIDATED, + status: $status, total: clone $basket->totalTaxIncluded(), lines: $lines ); diff --git a/domain/Services/OrderService.php b/domain/Services/OrderService.php index a0736665..66dce286 100644 --- a/domain/Services/OrderService.php +++ b/domain/Services/OrderService.php @@ -21,6 +21,22 @@ class OrderService ) { } + public function createPendingOrderFromBasket( + Basket $basket, + PickupTimeSlot $pickupTimeSlot, + Shopper $shopper, + Shop $shop + ): Order { + return Order::pendingFromBasket( + id: $this->newOrderId(), + reference: $this->newReference(), + basket: $basket, + pickupTimeSlot: $pickupTimeSlot, + shopper: $shopper, + shop: $shop + ); + } + public function createOrderFromBasket( Basket $basket, PickupTimeSlot $pickupTimeSlot, @@ -47,6 +63,21 @@ class OrderService return new OrderReference(Uuid::uuid7()); } + public function validateOrder(OrderId $id): Order + { + $order = $this->orderRepository->find($id); + + if (! $order) { + throw new \DomainException('Order not found'); + } + + $order->validate(); + + $this->orderRepository->persist($order); + + return $order; + } + public function cancelOrder(OrderId $id): void { $order = $this->orderRepository->find($id); diff --git a/domain/Services/OrderTunnelService.php b/domain/Services/OrderTunnelService.php index 71e48e35..4cd4d18c 100644 --- a/domain/Services/OrderTunnelService.php +++ b/domain/Services/OrderTunnelService.php @@ -22,6 +22,7 @@ use Domain\Models\Entities\Order; use Domain\Models\Entities\Shop; use Domain\Models\Entities\Shopper; use Domain\Models\ValueObjects\BasketProduct; +use Domain\Models\ValueObjects\Entities\OrderId; use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Models\ValueObjects\PickupTimeSlot; use Domain\Policies\CustomerOrderLimitPolicy; @@ -157,6 +158,69 @@ class OrderTunnelService return $matchedSlot; } + /** + * Step 1 of order confirmation: validates basket, limits, shopper and slot, + * then persists the order in WAITING state without dispatching external notifications. + * + * @throws WeeklyLimitExceededException + * @throws OrderLimitExceededException + * @throws ExpiredPickupTimeSlotException + * @throws BasketPriceChangedException + * @throws UnorderableProductException + * @throws InactiveShopperException + */ + public function placePendingOrder(OrderBuilderCompleted $builder): Order + { + $order = $this->validateAndCreateOrder($builder, pending: true); + + $this->orderRepository->persist($order); + + return $order; + } + + /** + * Step 2a (outside DB transaction): exports the pending order to Regate via SMTP. + * + * @throws RegateExportFailedException + */ + public function exportOrderToRegate(OrderId $orderId): void + { + $order = $this->orderRepository->find($orderId); + + if (! $order) { + throw new \DomainException("Order with id '{$orderId->value}' not found."); + } + + $placedEvent = $order->toPlacedEvent(); + + $this->regateService->processOrder( + $order->reference, + $order->employee->matricule, + CarbonImmutable::instance($order->pickupTimeSlot->getAt()), + $placedEvent->lines, + ); + } + + /** + * Step 2b (on Regate success): validates the order and dispatches AnOrderHasBeenPlaced. + */ + public function confirmPlacedOrder(OrderId $orderId): Order + { + $order = $this->orderService->validateOrder($orderId); + + $this->eventDispatcher->dispatch($order->toPlacedEvent()); + + return $order; + } + + /** + * Step 2c (on Regate failure): cancels the WAITING order without emptying the basket. + */ + public function cancelPendingOrder(OrderId $orderId): void + { + $this->orderService->cancelOrder($orderId); + } + /** * @throws WeeklyLimitExceededException * @throws OrderLimitExceededException @@ -167,6 +231,26 @@ class OrderTunnelService * @throws RegateExportFailedException */ public function finalizeOrder(OrderBuilderCompleted $builder): Order + { + $order = $this->validateAndCreateOrder($builder, pending: false); + + $this->orderRepository->persist($order); + + $placedEvent = $order->toPlacedEvent(); + + $this->regateService->processOrder( + $order->reference, + $order->employee->matricule, + CarbonImmutable::instance($order->pickupTimeSlot->getAt()), + $placedEvent->lines, + ); + + $this->eventDispatcher->dispatch($placedEvent); + + return $order; + } + + private function validateAndCreateOrder(OrderBuilderCompleted $builder, bool $pending): Order { $shopperId = $builder->getShopperId(); $basket = $this->revalidateBasket($builder->getBasket()); @@ -192,27 +276,9 @@ class OrderTunnelService $this->assertPickupTimeSlotIsAvailable($shop, $pickupTimeSlot); - $order = $this->orderService->createOrderFromBasket( - $basket, - $pickupTimeSlot, - $shopper, - $shop - ); - - $this->orderRepository->persist($order); - - $placedEvent = $order->toPlacedEvent(); - - $this->regateService->processOrder( - $order->reference, - $order->employee->matricule, - CarbonImmutable::instance($order->pickupTimeSlot->getAt()), - $placedEvent->lines, - ); - - $this->eventDispatcher->dispatch($placedEvent); - - return $order; + return $pending + ? $this->orderService->createPendingOrderFromBasket($basket, $pickupTimeSlot, $shopper, $shop) + : $this->orderService->createOrderFromBasket($basket, $pickupTimeSlot, $shopper, $shop); } /** @throws \Domain\Exceptions\OrderTunnel\OrderLimitExceededException */ diff --git a/infra/Adapters/Services/EloquentEmployeeStatisticsService.php b/infra/Adapters/Services/EloquentEmployeeStatisticsService.php index f0b28152..9c699a8f 100644 --- a/infra/Adapters/Services/EloquentEmployeeStatisticsService.php +++ b/infra/Adapters/Services/EloquentEmployeeStatisticsService.php @@ -30,7 +30,7 @@ class EloquentEmployeeStatisticsService implements EmployeeStatisticsService { $weekTotal = Order::query() ->where('employee_matricule', $matricule->value) - ->where('status', OrderStatus::VALIDATED) + ->whereIn('status', [OrderStatus::VALIDATED, OrderStatus::WAITING]) ->whereBetween('pickup_day', [$start, $end]) ->sum('total'); diff --git a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php index c5acc13a..601fef81 100644 --- a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php @@ -4,7 +4,18 @@ declare(strict_types=1); use App\Contracts\Executor; use App\Cqs\Actions\Orders\ApplyPickTimeSlotOutput; -use App\Cqs\Actions\Orders\FinalizeOrderOutput; +use App\Cqs\Actions\Orders\CancelPendingOrder; +use App\Cqs\Actions\Orders\CancelPendingOrderInput; +use App\Cqs\Actions\Orders\CancelPendingOrderOutput; +use App\Cqs\Actions\Orders\ConfirmPlacedOrder; +use App\Cqs\Actions\Orders\ConfirmPlacedOrderInput; +use App\Cqs\Actions\Orders\ConfirmPlacedOrderOutput; +use App\Cqs\Actions\Orders\ExportOrderToRegate; +use App\Cqs\Actions\Orders\ExportOrderToRegateInput; +use App\Cqs\Actions\Orders\ExportOrderToRegateOutput; +use App\Cqs\Actions\Orders\PlacePendingOrder; +use App\Cqs\Actions\Orders\PlacePendingOrderInput; +use App\Cqs\Actions\Orders\PlacePendingOrderOutput; use App\Cqs\Queries\Orders\GetBasketSummaryQueryOutput; use App\Cqs\Queries\Orders\GetOrderConfirmationQueryOutput; use App\Cqs\Queries\Orders\GetPickTimeSlotQueryOutput; @@ -26,6 +37,7 @@ use Domain\Models\Entities\Shopper; use Domain\Models\ValueObjects\DeliveryAddress; use Domain\Models\ValueObjects\Email; use Domain\Models\ValueObjects\Entities\BasketId; +use Domain\Models\ValueObjects\Entities\OrderId; use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\OrderEmployee; use Domain\Models\ValueObjects\OrderReference; @@ -500,11 +512,21 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); + $orderId = new OrderId(Uuid::uuid7()); $orderReference = new OrderReference(Uuid::uuid7()); - $this->mock(Executor::class, function ($mock) use ($orderReference): void { + $this->mock(Executor::class, function ($mock) use ($orderId, $orderReference): void { $mock->shouldReceive('execute') ->once() - ->andReturn(FinalizeOrderOutput::success($orderReference)); + ->with(\Mockery::type(PlacePendingOrder::class), \Mockery::type(PlacePendingOrderInput::class)) + ->andReturn(PlacePendingOrderOutput::pendingCreated($orderId, $orderReference)); + $mock->shouldReceive('execute') + ->once() + ->with(\Mockery::type(ExportOrderToRegate::class), \Mockery::type(ExportOrderToRegateInput::class)) + ->andReturn(ExportOrderToRegateOutput::SENT); + $mock->shouldReceive('execute') + ->once() + ->with(\Mockery::type(ConfirmPlacedOrder::class), \Mockery::type(ConfirmPlacedOrderInput::class)) + ->andReturn(ConfirmPlacedOrderOutput::CONFIRMED); }); // WHEN @@ -516,6 +538,104 @@ describe('TunnelController', function (): void { $response->assertRedirectToRoute('fo.sales.confirmation.show-confirmed', (string) $orderReference); }); + it('cancels pending order and redirects back cleanly when Regate export fails on confirmation submit', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + $customer = new Customer(); + $customer->email = new Email('regate-export-fail@example.com'); + $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + + $this->withoutMiddleware([ + CustomerIsEmployed::class, + EnsureCustomerEmailIsVerified::class, + ]); + Gate::before(fn () => true); + + $orderId = new OrderId(Uuid::uuid7()); + $orderReference = new OrderReference(Uuid::uuid7()); + $this->mock(Executor::class, function ($mock) use ($orderId, $orderReference): void { + $mock->shouldReceive('execute') + ->once() + ->with(\Mockery::type(PlacePendingOrder::class), \Mockery::type(PlacePendingOrderInput::class)) + ->andReturn(PlacePendingOrderOutput::pendingCreated($orderId, $orderReference)); + $mock->shouldReceive('execute') + ->once() + ->with(\Mockery::type(ExportOrderToRegate::class), \Mockery::type(ExportOrderToRegateInput::class)) + ->andReturn(ExportOrderToRegateOutput::FAILED); + $mock->shouldReceive('execute') + ->once() + ->with(\Mockery::type(CancelPendingOrder::class), \Mockery::type(CancelPendingOrderInput::class)) + ->andReturn(CancelPendingOrderOutput::CANCELLED); + }); + + // WHEN + $response = $this->from('/commande/confirmation')->post('/commande/confirmation', [ + 'ok_cgv' => '1', + ]); + + // THEN + $response->assertRedirectToRoute('fo.sales.confirmation') + ->assertSessionHas('message', __('An error occurred while validating your order. Please try again later.')); + }); + + it('redirects to confirmation with error when ConfirmPlacedOrder fails after Regate export', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + $customer = new Customer(); + $customer->email = new Email('confirm-sql-fail@example.com'); + $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + + $this->withoutMiddleware([ + CustomerIsEmployed::class, + EnsureCustomerEmailIsVerified::class, + ]); + Gate::before(fn () => true); + + $orderId = new OrderId(Uuid::uuid7()); + $orderReference = new OrderReference(Uuid::uuid7()); + $this->mock(Executor::class, function ($mock) use ($orderId, $orderReference): void { + $mock->shouldReceive('execute') + ->once() + ->with(\Mockery::type(PlacePendingOrder::class), \Mockery::type(PlacePendingOrderInput::class)) + ->andReturn(PlacePendingOrderOutput::pendingCreated($orderId, $orderReference)); + $mock->shouldReceive('execute') + ->once() + ->with(\Mockery::type(ExportOrderToRegate::class), \Mockery::type(ExportOrderToRegateInput::class)) + ->andReturn(ExportOrderToRegateOutput::SENT); + $mock->shouldReceive('execute') + ->once() + ->with(\Mockery::type(ConfirmPlacedOrder::class), \Mockery::type(ConfirmPlacedOrderInput::class)) + ->andReturn(ConfirmPlacedOrderOutput::FAILED); + }); + + // WHEN + $response = $this->from('/commande/confirmation')->post('/commande/confirmation', [ + 'ok_cgv' => '1', + ]); + + // THEN + $response->assertRedirectToRoute('fo.sales.confirmation') + ->assertSessionHas('message', __('An error occurred while validating your order. Please try again later.')); + }); + it('redirects back with message when limit exception occurs on confirmation submit', function (): void { /** @var \Tests\TestCase $this */ // GIVEN @@ -541,7 +661,7 @@ describe('TunnelController', function (): void { $this->mock(Executor::class, function ($mock): void { $mock->shouldReceive('execute') ->once() - ->andReturn(FinalizeOrderOutput::weeklyLimitExceeded( + ->andReturn(PlacePendingOrderOutput::weeklyLimitExceeded( 'The total amount for this delivery date has been exceeded. Please modify it to validate.' )); }); @@ -581,7 +701,7 @@ describe('TunnelController', function (): void { $this->mock(Executor::class, function ($mock): void { $mock->shouldReceive('execute') ->once() - ->andReturn(FinalizeOrderOutput::expiredTimeSlot('Invalid or unavailable time slot')); + ->andReturn(PlacePendingOrderOutput::expiredTimeSlot('Invalid or unavailable time slot')); }); // WHEN @@ -621,7 +741,7 @@ describe('TunnelController', function (): void { $this->mock(Executor::class, function ($mock): void { $mock->shouldReceive('execute') ->once() - ->andReturn(FinalizeOrderOutput::unorderableProduct( + ->andReturn(PlacePendingOrderOutput::unorderableProduct( 'One or more products in your basket are no longer available for order.' )); }); @@ -663,7 +783,7 @@ describe('TunnelController', function (): void { $this->mock(Executor::class, function ($mock): void { $mock->shouldReceive('execute') ->once() - ->andReturn(FinalizeOrderOutput::basketPriceChanged( + ->andReturn(PlacePendingOrderOutput::basketPriceChanged( 'The price of one or more products in your basket has changed.' )); }); @@ -705,7 +825,7 @@ describe('TunnelController', function (): void { $this->mock(Executor::class, function ($mock): void { $mock->shouldReceive('execute') ->once() - ->andReturn(FinalizeOrderOutput::lockTimeout()); + ->andReturn(PlacePendingOrderOutput::lockTimeout()); }); // WHEN @@ -743,7 +863,7 @@ describe('TunnelController', function (): void { $this->mock(Executor::class, function ($mock): void { $mock->shouldReceive('execute') ->once() - ->andReturn(FinalizeOrderOutput::inactiveShopper('Employee account is no longer active.')); + ->andReturn(PlacePendingOrderOutput::inactiveShopper('Employee account is no longer active.')); }); // WHEN diff --git a/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php index 462d09fb..8a43fb73 100644 --- a/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -use App\Cqs\Actions\Orders\FinalizeOrderInput; +use App\Cqs\Actions\Orders\PlacePendingOrderInput; use App\Http\Requests\Fo\Orders\ConfirmOrderRequest; use App\Models\Customer; use Domain\Models\ValueObjects\Entities\ShopperId; @@ -51,7 +51,7 @@ describe('ConfirmOrderRequest', function () { ->and($rules['ok_cgv'])->toContain('accepted'); }); - it('maps to FinalizeOrderInput', function () { + it('maps to PlacePendingOrderInput', function () { // GIVEN $shopperId = new ShopperId(Uuid::uuid7()); $customer = \Mockery::mock(Customer::class); @@ -64,10 +64,10 @@ describe('ConfirmOrderRequest', function () { $request->initialize(); // WHEN - $input = $request->toFinalizeOrderInput(); + $input = $request->toPlacePendingOrderInput(); // THEN - expect($input)->toBeInstanceOf(FinalizeOrderInput::class) + expect($input)->toBeInstanceOf(PlacePendingOrderInput::class) ->and($input->shopperId)->toBe($shopperId); }); }); diff --git a/tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php b/tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php deleted file mode 100644 index f7555be9..00000000 --- a/tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php +++ /dev/null @@ -1,435 +0,0 @@ -create(['default' => true]); - - $customer = new Customer(); - $customer->email = new Email('buyer.order@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); - $customer->saveOrFail(); - - $employee = new Employee(); - $employee->customer_id = $customer->id; - $employee->matricule = new Matricule('1000404'); - $employee->code = new Code('ABCDEF'); - $employee->nom = 'Petit'; - $employee->prenom = 'Luc'; - $employee->start_date = CarbonImmutable::parse('2025-01-01'); - $employee->end_date = $activeEmployee ? null : CarbonImmutable::parse('2026-01-01'); - $employee->etablissement = new ShopperEstablishmentCode('01'); - $employee->site = new ShopperSiteCode('SITE'); - $employee->service = new ShopperServiceCode('01'); - $employee->saveOrFail(); - - $range = new Range(); - $range->name = 'Gamme Commande ' . uniqid(); - $range->status = true; - $range->order = ((int) Range::query()->max('order')) + 1; - $range->picture_alt = 'alt'; - $range->picture_title = 'title'; - $range->saveOrFail(); - - $product = new Product([ - 'range_id' => $range->id, - 'name' => 'Rôti Fermier', - 'brand' => ProductBrand::loue, - 'invoicing_unit' => InvoicingUnit::PCE, - 'sell_unit' => SellUnit::PCE, - 'order_unit' => OrderUnit::PCE, - 'tax_rate' => TaxRate::TVA_5_5, - 'description' => 'Desc', - 'weight' => 1000, - 'status' => true, - ]); - $product->price = Money::EUR($priceCents); - $product->short_description = 'Court'; - $product->picture_alt = 'alt'; - $product->picture_title = 'title'; - $product->picture_large_alt = 'alt large'; - $product->picture_large_title = 'title large'; - $product->saveOrFail(); - - $inco = new ProductInco(); - $inco->product_id = $product->id; - $inco->no_art = 778899; - $inco->saveOrFail(); - - $basket = new Basket(new BasketId(Uuid::uuid7()), [ - $product->id => new BasketProduct( - id: $product->getId(), - name: $product->name, - qty: $qty, - unitPriceHt: $product->price, - unitDiscount: Money::EUR(0), - taxRate: $product->tax_rate, - weightGrams: 1000, - brand: $product->brand, - incoId: new IncoId($inco->no_art), - orderUnit: OrderUnit::PCE, - slug: $product->slug, - picture: null, - description: $product->description, - weightVariable: false, - discountRate: DiscountRate::zero(), - priceKgTtc: Money::EUR(1000), - options: [], - ), - ]); - - $slot = new PickupTimeSlot( - $pickupAt ?? CarbonImmutable::parse('2026-11-20 14:00:00', 'Europe/Paris'), - new \DateInterval('PT2H'), - ); - - $builder = OrderBuilder::fromBasket($basket, $customer->getId()) - ->withPickupTimeSlot($shop->getId(), $slot); - - $session = Session::driver(); - $basketRepo = new SessionBasketRepository($session, 'basket_', new BasketSerializer()); - $basketRepo->persist($basket); - $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); - $builderManager->save($builder); - - $dispatcher = new LaravelDomainEventDispatcher(); - $shopRepo = new EloquentShopRepository(); - $shopperRepo = new EloquentShopperRepository(); - $orderRepo = new EloquentOrderRepository(); - - $tunnelService = new OrderTunnelService( - $dispatcher, - new ShopperService($shopRepo, $shopperRepo), - $builderManager, - new PickupSchedulingService(new EloquentPickupExceptionRepository()), - $orderRepo, - new EloquentProductRepository(), - new CustomerOrderLimitPolicy(20000, 20000, new Currency('EUR')), - $shopRepo, - $shopperRepo, - new OrderService($orderRepo), - new EloquentEmployeeStatisticsService(), - $regateService ?? new MailRegateService(new CsvGeneratorImpl(), Mail::getFacadeRoot()), - ); - - $executor = new ActionExecutorService( - $lock ?? new LaravelCacheLock(new Repository(new ArrayStore())), - new NullLogger(), - $dispatcher, - ); - - return [ - 'customer' => $customer, - 'employee' => $employee, - 'shop' => $shop, - 'product' => $product, - 'basketId' => $basket->id, - 'basketRepository' => $basketRepo, - 'builderManager' => $builderManager, - 'dispatcher' => $dispatcher, - 'tunnelService' => $tunnelService, - 'executor' => $executor, - ]; - } - - it('persists order and lines, sends Regate mail synchronously, dispatches notifications, and returns SUCCESS', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - $ctx = buildFinalizeOrderScenario(priceCents: 2000, qty: 2); - $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); - - // WHEN - $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); - - // THEN - expect($output)->toBeInstanceOf(FinalizeOrderOutput::class) - ->and($output->status)->toBe(FinalizeOrderStatus::SUCCESS) - ->and($output->orderReference)->not->toBeNull(); - - $persistedOrder = Order::query()->with('lines')->first(); - expect($persistedOrder)->not->toBeNull() - ->and($persistedOrder?->status)->toBe(OrderStatus::VALIDATED) - ->and($persistedOrder?->shop_id)->toBe($ctx['shop']->id) - ->and($persistedOrder?->lines)->toHaveCount(1); - - Mail::assertSent(RegateOrderMail::class, 1); - Mail::assertQueued(OrderConfirmAdminMail::class, 1); - Notification::assertSentTo($ctx['employee'], OrderConfirmed::class); - }); - - it('rolls back database order and rethrows when Regate export fails', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - /** @var \Domain\Ports\Services\RegateService&\Mockery\MockInterface $failingRegate */ - $failingRegate = \Mockery::mock(RegateService::class); - $failingRegate->shouldReceive('processOrder') - ->once() - ->andThrow(new RegateExportFailedException('SMTP transport failure')); - - $ctx = buildFinalizeOrderScenario(regateService: $failingRegate); - $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); - - // WHEN & THEN - expect(fn () => $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()))) - ->toThrow(RegateExportFailedException::class); - - $this->assertDatabaseCount('orders', 0); - $this->assertDatabaseCount('order_lines', 0); - Notification::assertNothingSent(); - }); - - it('returns ORDER_LIMIT_EXCEEDED and avoids persisting order when basket exceeds 200 EUR', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - // 210 EUR HT -> > 200 EUR TTC order limit - $ctx = buildFinalizeOrderScenario(priceCents: 21000, qty: 1); - $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); - - // WHEN - $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); - - // THEN - expect($output->status)->toBe(FinalizeOrderStatus::ORDER_LIMIT_EXCEEDED) - ->and($output->orderReference)->toBeNull(); - $this->assertDatabaseCount('orders', 0); - Mail::assertNothingSent(); - }); - - it('returns WEEKLY_LIMIT_EXCEEDED when cumulative weekly orders exceed 200 EUR', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - $ctx = buildFinalizeOrderScenario(priceCents: 6000, qty: 1); - - Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'shop_id' => $ctx['shop']->id, - 'reference' => new OrderReference(Uuid::uuid7()), - 'status' => OrderStatus::VALIDATED->value, - 'total' => Money::EUR(16000), - 'employee' => new OrderEmployee( - $ctx['employee']->matricule, - $ctx['employee']->prenom, - $ctx['employee']->nom, - $ctx['employee']->etablissement, - $ctx['employee']->site, - $ctx['employee']->service, - ), - 'delivery_address' => new DeliveryAddress('Shop', '1 rue Test', '72300', 'Sablé'), - 'pickup_day' => '2026-11-20 14:00:00', - ]); - - $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); - - // WHEN - $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); - - // THEN - expect($output->status)->toBe(FinalizeOrderStatus::WEEKLY_LIMIT_EXCEEDED); - $this->assertDatabaseCount('orders', 1); - Mail::assertNothingSent(); - }); - - it('returns INACTIVE_SHOPPER when linked employee end_date is in the past', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - $ctx = buildFinalizeOrderScenario(activeEmployee: false); - $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); - - // WHEN - $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); - - // THEN - expect($output->status)->toBe(FinalizeOrderStatus::INACTIVE_SHOPPER); - $this->assertDatabaseCount('orders', 0); - Mail::assertNothingSent(); - }); - - it('returns UNORDERABLE_PRODUCT when a basket product was disabled before finalization', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - $ctx = buildFinalizeOrderScenario(); - $ctx['product']->status = false; - $ctx['product']->saveOrFail(); - - $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); - - // WHEN - $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); - - // THEN - expect($output->status)->toBe(FinalizeOrderStatus::UNORDERABLE_PRODUCT); - $this->assertDatabaseCount('orders', 0); - Mail::assertNothingSent(); - }); - - it('returns EXPIRED_TIME_SLOT when selected pickup date is no longer open', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - // Past Friday (2026-11-13) relative to test now (2026-11-16) - $ctx = buildFinalizeOrderScenario( - pickupAt: CarbonImmutable::parse('2026-11-13 14:00:00', 'Europe/Paris'), - ); - $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); - - // WHEN - $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); - - // THEN - expect($output->status)->toBe(FinalizeOrderStatus::EXPIRED_TIME_SLOT); - $this->assertDatabaseCount('orders', 0); - Mail::assertNothingSent(); - }); - - it('returns LOCK_TIMEOUT when lock acquisition times out inside ActionExecutorService', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - /** @var \Shared\Concurrency\Lock&\Mockery\MockInterface $lock */ - $lock = \Mockery::mock(Lock::class); - $lock->shouldReceive('synchronize') - ->once() - ->andThrow(new LockTimeoutException('Lock timed out')); - - $ctx = buildFinalizeOrderScenario(lock: $lock); - $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); - - // WHEN - $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); - - // THEN - expect($output->status)->toBe(FinalizeOrderStatus::LOCK_TIMEOUT) - ->and($output->orderReference)->toBeNull(); - $this->assertDatabaseCount('orders', 0); - }); - - it('updates session basket and returns BASKET_PRICE_CHANGED when catalog price increases before finalization', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - $ctx = buildFinalizeOrderScenario(priceCents: 1000, qty: 2); - $ctx['product']->price = Money::EUR(1500); - $ctx['product']->saveOrFail(); - - $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); - - // WHEN - $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); - - // THEN - expect($output->status)->toBe(FinalizeOrderStatus::BASKET_PRICE_CHANGED) - ->and($output->orderReference)->toBeNull() - ->and($ctx['basketRepository']->find($ctx['basketId'])?->totalTaxIncluded()->getAmount())->toBe('3165'); - $this->assertDatabaseCount('orders', 0); - Mail::assertNothingSent(); - }); -}); diff --git a/tests/Integration/WithApp/App/Actions/Orders/PlacePendingOrderTest.php b/tests/Integration/WithApp/App/Actions/Orders/PlacePendingOrderTest.php new file mode 100644 index 00000000..3c75ffdd --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Orders/PlacePendingOrderTest.php @@ -0,0 +1,466 @@ +forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'email' => new Email('buyer-' . uniqid() . '@example.com'), + 'hashcode' => new CrmHashcode(Uuid::uuid4()), + ]); + + /** @var int $sequence */ + static $sequence = 0; + $sequence++; + $chars = Code::ALLOWED_CHARACTERS; + $uniqueCode = 'ABCDE' . $chars[$sequence % strlen($chars)] . $chars[(intdiv($sequence, strlen($chars))) % strlen($chars)]; + + $employee = new Employee(); + $employee->matricule = new Matricule((string) random_int(1000000, 9999999)); + $employee->code = new Code($uniqueCode); + $employee->nom = 'Dupont'; + $employee->prenom = 'Jean'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITEA'); + $employee->service = new ShopperServiceCode('101'); + $employee->start_date = Date::now()->subMonth(); + $employee->end_date = $activeEmployee ? null : Date::now()->subDay(); + $employee->customer()->associate($customer); + $employee->saveOrFail(); + + $shop = new Shop(); + $shop->name = 'Boutique Sablé'; + $shop->address = '10 rue Test'; + $shop->postcode = '72300'; + $shop->city = 'Sablé'; + $shop->default = true; + $shop->saveOrFail(); + + $range = new Range(); + $range->name = 'Gamme Test ' . uniqid(); + $range->status = true; + $range->order = random_int(1, 99999); + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $product = new Product(); + $product->name = 'Poulet Test ' . uniqid(); + $product->brand = ProductBrand::loue; + $product->description = 'Description complète de test'; + $product->short_description = 'Court'; + $product->price = Money::EUR($priceCents); + $product->invoicing_unit = InvoicingUnit::PCE; + $product->tax_rate = TaxRate::TVA_5_5; + $product->stock = 50; + $product->weight = 1000; + $product->sell_unit = SellUnit::PCE; + $product->order_unit = OrderUnit::PCE; + $product->range_id = $range->id; + $product->status = true; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt large'; + $product->picture_large_title = 'title large'; + $product->saveOrFail(); + + $inco = new ProductInco(); + $inco->product_id = $product->id; + $inco->no_art = 778800 + $sequence; + $inco->saveOrFail(); + + /** @var BasketService $basketService */ + $basketService = resolve(BasketService::class); + $basketService->empty(); + $basketService->add($product->getId(), $qty); + $basket = $basketService->getBasket(); + + /** @var BasketRepository $basketRepo */ + $basketRepo = resolve(BasketRepository::class); + + $slot = new PickupTimeSlot( + $pickupAt ?? CarbonImmutable::parse('2026-11-20 14:00:00', 'Europe/Paris'), + new \DateInterval('PT2H'), + ); + + $builder = OrderBuilder::fromBasket($basket, $customer->getId()) + ->withPickupTimeSlot($shop->getId(), $slot); + + /** @var \Illuminate\Contracts\Session\Session $session */ + $session = Session::driver(); + $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); + $builderManager->save($builder); + + $dispatcher = new LaravelDomainEventDispatcher(); + $shopRepo = new EloquentShopRepository(); + $shopperRepo = new EloquentShopperRepository(); + $orderRepo = new EloquentOrderRepository(); + /** @var \Illuminate\Contracts\Mail\Mailer $mailer */ + $mailer = Mail::getFacadeRoot(); + + $tunnelService = new OrderTunnelService( + $dispatcher, + new ShopperService($shopRepo, $shopperRepo), + $builderManager, + new PickupSchedulingService(new EloquentPickupExceptionRepository()), + $orderRepo, + new EloquentProductRepository(), + new CustomerOrderLimitPolicy(20000, 20000, new Currency('EUR')), + $shopRepo, + $shopperRepo, + new OrderService($orderRepo), + new EloquentEmployeeStatisticsService(), + $regateService ?? new MailRegateService(new CsvGeneratorImpl(), $mailer), + ); + + $executor = new ActionExecutorService( + $lock ?? new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + $dispatcher, + ); + + return [ + 'customer' => $customer, + 'employee' => $employee, + 'shop' => $shop, + 'product' => $product, + 'basketId' => $basket->id, + 'basketRepository' => $basketRepo, + 'builderManager' => $builderManager, + 'dispatcher' => $dispatcher, + 'tunnelService' => $tunnelService, + 'executor' => $executor, + ]; + } + + it('creates WAITING order, exports to Regate outside SQL transaction, and validates order with notifications', function (): void { + // GIVEN + $baseTxLevel = DB::transactionLevel(); + + $spyRegate = new class () implements RegateService + { + public ?int $recordedTxLevel = null; + + #[\Override] + public function processOrder( + OrderReference $reference, + Matricule $employeeMatricule, + CarbonImmutable $pickupDay, + array $lines, + ): void { + $this->recordedTxLevel = DB::transactionLevel(); + } + }; + + $ctx = buildOrderPlacementScenario(priceCents: 2000, qty: 2, regateService: $spyRegate); + + $placeAction = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']); + $exportAction = new ExportOrderToRegate($ctx['tunnelService']); + $confirmAction = new ConfirmPlacedOrder($ctx['tunnelService']); + + // WHEN: Step 1 - create pending WAITING order + $placeOutput = $ctx['executor']->execute($placeAction, new PlacePendingOrderInput($ctx['customer']->getId())); + + // THEN: Order is WAITING and no notifications or emails were sent yet + expect($placeOutput->status)->toBe(PlacePendingOrderStatus::PENDING_CREATED) + ->and($placeOutput->orderId)->toBeInstanceOf(OrderId::class); + + $pendingOrder = Order::query()->find($placeOutput->orderId?->value->toString()); + expect($pendingOrder?->status)->toBe(OrderStatus::WAITING); + Notification::assertNothingSent(); + + // WHEN: Step 2 - export to Regate outside any extra SQL transaction + /** @var OrderId $orderId */ + $orderId = $placeOutput->orderId; + $exportOutput = $ctx['executor']->execute($exportAction, new ExportOrderToRegateInput($orderId)); + + expect($exportOutput)->toBe(ExportOrderToRegateOutput::SENT) + ->and($spyRegate->recordedTxLevel)->toBe($baseTxLevel); + + // WHEN: Step 3 - confirm placed order (VALIDATED + AnOrderHasBeenPlaced) + $confirmOutput = $ctx['executor']->execute($confirmAction, new ConfirmPlacedOrderInput($orderId)); + + // THEN + expect($confirmOutput)->toBe(ConfirmPlacedOrderOutput::CONFIRMED); + $confirmedOrder = Order::query()->with('lines')->find($orderId->value->toString()); + expect($confirmedOrder?->status)->toBe(OrderStatus::VALIDATED) + ->and($confirmedOrder?->lines)->toHaveCount(1); + + Mail::assertQueued(OrderConfirmAdminMail::class, 1); + Notification::assertSentTo($ctx['employee'], OrderConfirmed::class); + expect($ctx['basketRepository']->find($ctx['basketId']))->toBeNull(); + }); + + it('cancels WAITING order cleanly and keeps basket intact when Regate export fails', function (): void { + // GIVEN + /** @var \Domain\Ports\Services\RegateService&\Mockery\MockInterface $failingRegate */ + $failingRegate = \Mockery::mock(RegateService::class); + $failingRegate->shouldReceive('processOrder') + ->once() + ->andThrow(new RegateExportFailedException('SMTP transport failure')); + + $ctx = buildOrderPlacementScenario(regateService: $failingRegate); + $placeAction = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']); + $exportAction = new ExportOrderToRegate($ctx['tunnelService']); + $cancelAction = new CancelPendingOrder($ctx['tunnelService']); + + // WHEN + $placeOutput = $ctx['executor']->execute($placeAction, new PlacePendingOrderInput($ctx['customer']->getId())); + /** @var OrderId $orderId */ + $orderId = $placeOutput->orderId; + $exportOutput = $ctx['executor']->execute($exportAction, new ExportOrderToRegateInput($orderId)); + $cancelOutput = $ctx['executor']->execute($cancelAction, new CancelPendingOrderInput($orderId)); + + // THEN + expect($exportOutput)->toBe(ExportOrderToRegateOutput::FAILED) + ->and($cancelOutput)->toBe(CancelPendingOrderOutput::CANCELLED); + + $persistedOrder = Order::query()->find($orderId->value->toString()); + expect($persistedOrder?->status)->toBe(OrderStatus::CANCELED) + ->and($ctx['basketRepository']->find($ctx['basketId']))->not->toBeNull(); + Mail::assertNothingQueued(); + Notification::assertNothingSent(); + }); + + it('sends Regate order email through real MailRegateService when export succeeds', function (): void { + // GIVEN + $ctx = buildOrderPlacementScenario(priceCents: 2000, qty: 2); + $placeAction = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']); + $exportAction = new ExportOrderToRegate($ctx['tunnelService']); + $confirmAction = new ConfirmPlacedOrder($ctx['tunnelService']); + + // WHEN + $placeOutput = $ctx['executor']->execute($placeAction, new PlacePendingOrderInput($ctx['customer']->getId())); + /** @var OrderId $orderId */ + $orderId = $placeOutput->orderId; + $exportOutput = $ctx['executor']->execute($exportAction, new ExportOrderToRegateInput($orderId)); + $confirmOutput = $ctx['executor']->execute($confirmAction, new ConfirmPlacedOrderInput($orderId)); + + // THEN + expect($exportOutput)->toBe(ExportOrderToRegateOutput::SENT) + ->and($confirmOutput)->toBe(ConfirmPlacedOrderOutput::CONFIRMED); + Mail::assertSent(RegateOrderMail::class, 1); + }); + + it('returns ORDER_LIMIT_EXCEEDED and avoids persisting order when basket exceeds 200 EUR', function (): void { + // GIVEN + $ctx = buildOrderPlacementScenario(priceCents: 21000, qty: 1); + $action = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']); + + // WHEN + $output = $ctx['executor']->execute($action, new PlacePendingOrderInput($ctx['customer']->getId())); + + // THEN + expect($output->status)->toBe(PlacePendingOrderStatus::ORDER_LIMIT_EXCEEDED) + ->and($output->orderReference)->toBeNull() + ->and(Order::query()->count())->toBe(0); + Mail::assertNothingSent(); + }); + + it('counts existing WAITING orders toward weekly limit to prevent concurrent overspending', function (): void { + // GIVEN + $ctx = buildOrderPlacementScenario(priceCents: 6000, qty: 1); + + Order::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'shop_id' => $ctx['shop']->id, + 'reference' => new OrderReference(Uuid::uuid7()), + 'status' => OrderStatus::WAITING->value, + 'total' => Money::EUR(16000), + 'employee' => new OrderEmployee( + $ctx['employee']->matricule, + $ctx['employee']->prenom, + $ctx['employee']->nom, + $ctx['employee']->etablissement, + $ctx['employee']->site, + $ctx['employee']->service, + ), + 'delivery_address' => new DeliveryAddress('Shop', '1 rue Test', '72300', 'Sablé'), + 'pickup_day' => '2026-11-20', + ]); + + $action = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']); + + // WHEN + $output = $ctx['executor']->execute($action, new PlacePendingOrderInput($ctx['customer']->getId())); + + // THEN + expect($output->status)->toBe(PlacePendingOrderStatus::WEEKLY_LIMIT_EXCEEDED) + ->and(Order::query()->count())->toBe(1); + Mail::assertNothingSent(); + }); + + it('returns INACTIVE_SHOPPER, UNORDERABLE_PRODUCT, EXPIRED_TIME_SLOT, BASKET_PRICE_CHANGED and LOCK_TIMEOUT appropriately', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN: inactive employee + $inactiveCtx = buildOrderPlacementScenario(activeEmployee: false); + $inactiveOut = $inactiveCtx['executor']->execute( + new PlacePendingOrder($inactiveCtx['tunnelService'], $inactiveCtx['basketRepository']), + new PlacePendingOrderInput($inactiveCtx['customer']->getId()), + ); + expect($inactiveOut->status)->toBe(PlacePendingOrderStatus::INACTIVE_SHOPPER); + + // GIVEN: disabled product + $unorderableCtx = buildOrderPlacementScenario(); + $unorderableCtx['product']->status = false; + $unorderableCtx['product']->saveOrFail(); + $unorderableOut = $unorderableCtx['executor']->execute( + new PlacePendingOrder($unorderableCtx['tunnelService'], $unorderableCtx['basketRepository']), + new PlacePendingOrderInput($unorderableCtx['customer']->getId()), + ); + expect($unorderableOut->status)->toBe(PlacePendingOrderStatus::UNORDERABLE_PRODUCT); + + // GIVEN: expired pickup slot + $expiredCtx = buildOrderPlacementScenario( + pickupAt: CarbonImmutable::parse('2026-11-13 14:00:00', 'Europe/Paris'), + ); + $expiredOut = $expiredCtx['executor']->execute( + new PlacePendingOrder($expiredCtx['tunnelService'], $expiredCtx['basketRepository']), + new PlacePendingOrderInput($expiredCtx['customer']->getId()), + ); + expect($expiredOut->status)->toBe(PlacePendingOrderStatus::EXPIRED_TIME_SLOT); + + // GIVEN: price increase before finalization + $priceCtx = buildOrderPlacementScenario(priceCents: 1000, qty: 2); + $priceCtx['product']->price = Money::EUR(1500); + $priceCtx['product']->saveOrFail(); + $priceOut = $priceCtx['executor']->execute( + new PlacePendingOrder($priceCtx['tunnelService'], $priceCtx['basketRepository']), + new PlacePendingOrderInput($priceCtx['customer']->getId()), + ); + expect($priceOut->status)->toBe(PlacePendingOrderStatus::BASKET_PRICE_CHANGED) + ->and($priceCtx['basketRepository']->find($priceCtx['basketId'])?->totalTaxIncluded()->getAmount())->toBe('3165'); + + // GIVEN: lock timeout + /** @var \Shared\Concurrency\Lock&\Mockery\MockInterface $lock */ + $lock = \Mockery::mock(Lock::class); + $lock->shouldReceive('synchronize')->once()->andThrow(new LockTimeoutException('Lock timed out')); + $lockCtx = buildOrderPlacementScenario(lock: $lock); + $lockOut = $lockCtx['executor']->execute( + new PlacePendingOrder($lockCtx['tunnelService'], $lockCtx['basketRepository']), + new PlacePendingOrderInput($lockCtx['customer']->getId()), + ); + expect($lockOut->status)->toBe(PlacePendingOrderStatus::LOCK_TIMEOUT); + }); +}); diff --git a/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php b/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php index fe5609f7..62e8e040 100644 --- a/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php +++ b/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use App\Attributes\Locked; +use App\Attributes\WithoutTransaction; use App\Contracts\Action; use App\Contracts\ActionInput; use App\Contracts\HandlesFailure; @@ -796,4 +797,61 @@ describe('ActionExecutorService', function (): void { expect($capturedException)->toBeInstanceOf(LockTimeoutException::class); }); + + it('runs WithoutTransaction action outside DB transaction and flushes events dispatched inside onSuccess', function (): void { + // GIVEN + $lock = \Mockery::mock(Lock::class); + $lock->shouldNotReceive('synchronize'); + + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldIgnoreMissing(); + + $postHookEvent = new class () implements Event + { + }; + + $eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class); + $eventDispatcher->shouldReceive('beginBuffering')->once()->ordered(); + $eventDispatcher->shouldReceive('flush')->once()->ordered(); + $eventDispatcher->shouldReceive('dispatch')->once()->with($postHookEvent)->ordered(); + + $txLevelInsideAction = null; + $action = new #[WithoutTransaction] class ($txLevelInsideAction, $postHookEvent, $eventDispatcher) implements Action, HandlesSuccess + { + public function __construct( + private ?int &$txLevelInsideAction, + private readonly Event $event, + private readonly LaravelDomainEventDispatcher $dispatcher, + ) { + } + + #[\Override] + public function __invoke(ActionInput $input): string + { + $this->txLevelInsideAction = DB::transactionLevel(); + + return 'exported'; + } + + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + $this->dispatcher->dispatch($this->event); + } + }; + + $input = new class () implements ActionInput + { + }; + + $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); + $baseTx = DB::transactionLevel(); + + // WHEN + $result = $executor->execute($action, $input); + + // THEN + expect($result)->toBe('exported') + ->and($txLevelInsideAction)->toBe($baseTx); + }); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php index 88483682..15e7cef1 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php @@ -63,3 +63,55 @@ it('retrieves the weekly order total for a given employee', function () { expect($result->getAmount())->toBe('1500') ->and($result->getCurrency()->getCode())->toBe('EUR'); }); + +it('includes WAITING orders and excludes CANCELED orders in weekly total', function (): void { + // GIVEN + DB::table('shops')->insertOrIgnore(['id' => 1, 'name' => 'Shop 1', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); + + $baseRow = [ + 'shop_id' => 1, + 'employee' => json_encode([ + 'matricule' => '1234567', + 'firstname' => 'Jean', + 'lastname' => 'Dupont', + 'facility' => 'Main Facility', + 'site' => 'HQ', + 'service' => 'IT', + ]), + 'delivery_address' => '{}', + 'pickup_day' => '2023-01-05', + ]; + + DB::table('orders')->insert([ + array_merge($baseRow, [ + 'id' => Uuid::uuid7()->toString(), + 'reference' => Uuid::uuid7()->toString(), + 'status' => OrderStatus::VALIDATED->value, + 'total' => 1000, + ]), + array_merge($baseRow, [ + 'id' => Uuid::uuid7()->toString(), + 'reference' => Uuid::uuid7()->toString(), + 'status' => OrderStatus::WAITING->value, + 'total' => 2500, + ]), + array_merge($baseRow, [ + 'id' => Uuid::uuid7()->toString(), + 'reference' => Uuid::uuid7()->toString(), + 'status' => OrderStatus::CANCELED->value, + 'total' => 9000, + ]), + ]); + + $service = new EloquentEmployeeStatisticsService(); + + // WHEN + $result = $service->getWeeklyTotalForEmployee( + new Matricule('1234567'), + CarbonImmutable::parse('2023-01-01'), + CarbonImmutable::parse('2023-01-07') + ); + + // THEN + expect($result->getAmount())->toBe('3500'); +}); diff --git a/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php b/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php deleted file mode 100644 index cd974949..00000000 --- a/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php +++ /dev/null @@ -1,334 +0,0 @@ -shouldReceive('getBuilderCompletedOrFail') - ->once() - ->andReturn($builder); - $orderTunnelService->shouldReceive('finalizeOrder') - ->once() - ->with($builder) - ->andReturn($order); - - $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); - - // WHEN - $result = $action($input); - - // THEN - expect($result)->toBeInstanceOf(FinalizeOrderOutput::class) - ->and($result->status)->toBe(FinalizeOrderStatus::SUCCESS) - ->and($result->orderReference)->not->toBeNull() - ->and($result->orderReference?->value)->toBe($orderReference->value); - }); - - it('returns expiredTimeSlot output when finalizeOrder throws ExpiredPickupTimeSlotException', function (): void { - // GIVEN - $input = new FinalizeOrderInput(); - $builder = \Mockery::mock(OrderBuilderCompleted::class); - $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder); - $orderTunnelService->shouldReceive('finalizeOrder') - ->once() - ->with($builder) - ->andThrow(new ExpiredPickupTimeSlotException('Invalid or unavailable time slot')); - - $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); - - // WHEN - $result = $action($input); - - // THEN - expect($action)->not->toBeInstanceOf(HandlesFailure::class) - ->and($action)->not->toBeInstanceOf(HandlesSuccess::class) - ->and($result)->toBeInstanceOf(FinalizeOrderOutput::class) - ->and($result->status)->toBe(FinalizeOrderStatus::EXPIRED_TIME_SLOT) - ->and($result->orderReference)->toBeNull() - ->and($result->errorMessage)->toBe('Invalid or unavailable time slot'); - }); - - it('returns inactiveShopper output when finalizeOrder throws InactiveShopperException', function (): void { - // GIVEN - $input = new FinalizeOrderInput(); - $builder = \Mockery::mock(OrderBuilderCompleted::class); - $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder); - $orderTunnelService->shouldReceive('finalizeOrder') - ->once() - ->with($builder) - ->andThrow(new InactiveShopperException('Employee account is no longer active.')); - - $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); - - // WHEN - $result = $action($input); - - // THEN - expect($result)->toBeInstanceOf(FinalizeOrderOutput::class) - ->and($result->status)->toBe(FinalizeOrderStatus::INACTIVE_SHOPPER) - ->and($result->orderReference)->toBeNull() - ->and($result->errorMessage)->toBe('Employee account is no longer active.'); - }); - - it('returns unorderableProduct output when finalizeOrder throws UnorderableProductException', function (): void { - // GIVEN - $input = new FinalizeOrderInput(); - $builder = \Mockery::mock(OrderBuilderCompleted::class); - $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder); - $orderTunnelService->shouldReceive('finalizeOrder') - ->once() - ->with($builder) - ->andThrow(new UnorderableProductException('One or more products in your basket are no longer available for order.')); - - $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); - - // WHEN - $result = $action($input); - - // THEN - expect($result)->toBeInstanceOf(FinalizeOrderOutput::class) - ->and($result->status)->toBe(FinalizeOrderStatus::UNORDERABLE_PRODUCT) - ->and($result->orderReference)->toBeNull() - ->and($result->errorMessage)->toBe('One or more products in your basket are no longer available for order.'); - }); - - it('returns orderLimitExceeded output when finalizeOrder throws OrderLimitExceededException', function (): void { - // GIVEN - $input = new FinalizeOrderInput(); - $builder = \Mockery::mock(OrderBuilderCompleted::class); - $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder); - $orderTunnelService->shouldReceive('finalizeOrder') - ->once() - ->with($builder) - ->andThrow(new OrderLimitExceededException()); - - $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); - - // WHEN - $result = $action($input); - - // THEN - expect($result)->toBeInstanceOf(FinalizeOrderOutput::class) - ->and($result->status)->toBe(FinalizeOrderStatus::ORDER_LIMIT_EXCEEDED) - ->and($result->orderReference)->toBeNull() - ->and($result->errorMessage)->toBe('The total amount of this order has been exceeded. Please modify it to validate.'); - }); - - it('returns weeklyLimitExceeded output when finalizeOrder throws WeeklyLimitExceededException', function (): void { - // GIVEN - $input = new FinalizeOrderInput(); - $builder = \Mockery::mock(OrderBuilderCompleted::class); - $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder); - $orderTunnelService->shouldReceive('finalizeOrder') - ->once() - ->with($builder) - ->andThrow(new WeeklyLimitExceededException()); - - $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); - - // WHEN - $result = $action($input); - - // THEN - expect($result)->toBeInstanceOf(FinalizeOrderOutput::class) - ->and($result->status)->toBe(FinalizeOrderStatus::WEEKLY_LIMIT_EXCEEDED) - ->and($result->orderReference)->toBeNull() - ->and($result->errorMessage)->toBe('The total amount for this delivery date has been exceeded. Please modify it to validate.'); - }); - - it('propagates RegateExportFailedException so ActionExecutorService rolls back the transaction', function (): void { - // GIVEN - $input = new FinalizeOrderInput(); - $builder = \Mockery::mock(OrderBuilderCompleted::class); - $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder); - $orderTunnelService->shouldReceive('finalizeOrder') - ->once() - ->with($builder) - ->andThrow(new RegateExportFailedException('SMTP transport error')); - - $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); - - // WHEN - expect(fn () => $action($input)) - // THEN - ->toThrow(RegateExportFailedException::class, 'SMTP transport error'); - }); - - it('has Locked attribute with expected TTL and wait seconds and implements lock contracts', function (): void { - // GIVEN - $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); - $reflection = new \ReflectionClass(FinalizeOrder::class); - $attributes = $reflection->getAttributes(Locked::class); - - // WHEN - $locked = ($attributes[0] ?? null)?->newInstance(); - - // THEN - expect($locked)->toBeInstanceOf(Locked::class) - ->and($locked->ttlSeconds)->toBe(30) - ->and($locked->waitSeconds)->toBe(10) - ->and($locked->key)->toBeNull() - ->and($action)->toBeInstanceOf(ProvidesLockKey::class) - ->and($action)->toBeInstanceOf(HandlesLockTimeout::class); - }); - - it('builds lockKey from input shopperId when provided', function (): void { - // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); - $input = new FinalizeOrderInput(shopperId: $shopperId); - $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $orderTunnelService->shouldNotReceive('getBuilderCompletedOrFail'); - - $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); - - // WHEN - $key = $action->lockKey($input); - - // THEN - expect($key)->toBe("order:finalize:shopper:{$shopperId->value}"); - }); - - it('builds lockKey from completed builder when input shopperId is null', function (): void { - // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); - $input = new FinalizeOrderInput(); - - $builder = \Mockery::mock(OrderBuilderCompleted::class); - $builder->shouldReceive('getShopperId') - ->once() - ->andReturn($shopperId); - - $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $orderTunnelService->shouldReceive('getBuilderCompletedOrFail') - ->once() - ->andReturn($builder); - - $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); - - // WHEN - $key = $action->lockKey($input); - - // THEN - expect($key)->toBe("order:finalize:shopper:{$shopperId->value}"); - }); - - it('returns lockTimeout output on lock timeout', function (): void { - // GIVEN - $input = new FinalizeOrderInput(); - $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - - $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); - - // WHEN - $result = $action->onLockTimeout($input); - - // THEN - expect($result)->toBeInstanceOf(FinalizeOrderOutput::class) - ->and($result->status)->toBe(FinalizeOrderStatus::LOCK_TIMEOUT) - ->and($result->orderReference)->toBeNull() - ->and($result->errorMessage)->toBeNull(); - }); - - it('persists refreshed basket and returns basketPriceChanged output when finalizeOrder throws BasketPriceChangedException', function (): void { - // GIVEN - $input = new FinalizeOrderInput(); - $builder = \Mockery::mock(OrderBuilderCompleted::class); - $refreshedBasket = new Basket(new BasketId(Uuid::uuid7()), []); - $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder); - $orderTunnelService->shouldReceive('finalizeOrder') - ->once() - ->with($builder) - ->andThrow(new BasketPriceChangedException($refreshedBasket)); - - $basketRepository = \Mockery::mock(BasketRepository::class); - $basketRepository->shouldReceive('persist') - ->once() - ->with($refreshedBasket); - - $action = new FinalizeOrder($orderTunnelService, $basketRepository); - - // WHEN - $result = $action($input); - - // THEN - expect($result)->toBeInstanceOf(FinalizeOrderOutput::class) - ->and($result->status)->toBe(FinalizeOrderStatus::BASKET_PRICE_CHANGED) - ->and($result->orderReference)->toBeNull() - ->and($result->errorMessage)->toBe('The price of one or more products in your basket has changed.'); - }); -}); diff --git a/tests/Unit/App/Actions/Orders/FinalizeOrderInputTest.php b/tests/Unit/App/Actions/Orders/PlacePendingOrderInputTest.php similarity index 69% rename from tests/Unit/App/Actions/Orders/FinalizeOrderInputTest.php rename to tests/Unit/App/Actions/Orders/PlacePendingOrderInputTest.php index a283e7d7..5b8f417e 100644 --- a/tests/Unit/App/Actions/Orders/FinalizeOrderInputTest.php +++ b/tests/Unit/App/Actions/Orders/PlacePendingOrderInputTest.php @@ -2,14 +2,14 @@ declare(strict_types=1); -use App\Cqs\Actions\Orders\FinalizeOrderInput; +use App\Cqs\Actions\Orders\PlacePendingOrderInput; use Domain\Models\ValueObjects\Entities\ShopperId; use Ramsey\Uuid\Uuid; -describe('FinalizeOrderInput', function (): void { +describe('PlacePendingOrderInput', function (): void { it('can be instantiated with null shopperId', function (): void { // GIVEN & WHEN - $input = new FinalizeOrderInput(); + $input = new PlacePendingOrderInput(); // THEN expect($input->shopperId)->toBeNull(); @@ -20,7 +20,7 @@ describe('FinalizeOrderInput', function (): void { $shopperId = new ShopperId(Uuid::uuid7()); // WHEN - $input = new FinalizeOrderInput(shopperId: $shopperId); + $input = new PlacePendingOrderInput(shopperId: $shopperId); // THEN expect($input->shopperId)->toBe($shopperId); diff --git a/tests/Unit/App/Actions/Orders/PlacePendingOrderTest.php b/tests/Unit/App/Actions/Orders/PlacePendingOrderTest.php new file mode 100644 index 00000000..a2ef604c --- /dev/null +++ b/tests/Unit/App/Actions/Orders/PlacePendingOrderTest.php @@ -0,0 +1,307 @@ +shouldReceive('getBuilderCompletedOrFail') + ->once() + ->andReturn($builder); + $orderTunnelService->shouldReceive('placePendingOrder') + ->once() + ->with($builder) + ->andReturn($order); + + /** @var \Mockery\MockInterface&BasketRepository $basketRepository */ + $basketRepository = \Mockery::mock(BasketRepository::class); + $action = new PlacePendingOrder($orderTunnelService, $basketRepository); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeInstanceOf(PlacePendingOrderOutput::class) + ->and($result->status)->toBe(PlacePendingOrderStatus::PENDING_CREATED) + ->and($result->orderId)->toBe($orderId) + ->and($result->orderReference?->value)->toBe($orderReference->value); + }); + + it('maps domain exceptions cleanly into PlacePendingOrderOutput', function ( + \Throwable $exception, + PlacePendingOrderStatus $expectedStatus, + string $expectedMessage, + ): void { + // GIVEN + $input = new PlacePendingOrderInput(); + $builder = \Mockery::mock(OrderBuilderCompleted::class); + /** @var \Mockery\MockInterface&OrderTunnelService $orderTunnelService */ + $orderTunnelService = \Mockery::mock(OrderTunnelService::class); + $orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder); + $orderTunnelService->shouldReceive('placePendingOrder') + ->once() + ->with($builder) + ->andThrow($exception); + + /** @var \Mockery\MockInterface&BasketRepository $basketRepository */ + $basketRepository = \Mockery::mock(BasketRepository::class); + $action = new PlacePendingOrder($orderTunnelService, $basketRepository); + + // WHEN + $result = $action($input); + + // THEN + expect($action)->not->toBeInstanceOf(HandlesFailure::class) + ->and($action)->not->toBeInstanceOf(HandlesSuccess::class) + ->and($result)->toBeInstanceOf(PlacePendingOrderOutput::class) + ->and($result->status)->toBe($expectedStatus) + ->and($result->orderId)->toBeNull() + ->and($result->orderReference)->toBeNull() + ->and($result->errorMessage)->toBe($expectedMessage); + })->with([ + 'expired slot' => [ + new ExpiredPickupTimeSlotException('Invalid or unavailable time slot'), + PlacePendingOrderStatus::EXPIRED_TIME_SLOT, + 'Invalid or unavailable time slot', + ], + 'inactive shopper' => [ + new InactiveShopperException('Employee account is no longer active.'), + PlacePendingOrderStatus::INACTIVE_SHOPPER, + 'Employee account is no longer active.', + ], + 'unorderable product' => [ + new UnorderableProductException('One or more products in your basket are no longer available for order.'), + PlacePendingOrderStatus::UNORDERABLE_PRODUCT, + 'One or more products in your basket are no longer available for order.', + ], + 'order limit' => [ + new OrderLimitExceededException(), + PlacePendingOrderStatus::ORDER_LIMIT_EXCEEDED, + 'The total amount of this order has been exceeded. Please modify it to validate.', + ], + 'weekly limit' => [ + new WeeklyLimitExceededException(), + PlacePendingOrderStatus::WEEKLY_LIMIT_EXCEEDED, + 'The total amount for this delivery date has been exceeded. Please modify it to validate.', + ], + ]); + + it('persists refreshed basket and returns basketPriceChanged output when placePendingOrder throws BasketPriceChangedException', function (): void { + // GIVEN + $input = new PlacePendingOrderInput(); + $builder = \Mockery::mock(OrderBuilderCompleted::class); + $refreshedBasket = new Basket(new BasketId(Uuid::uuid7()), []); + /** @var \Mockery\MockInterface&OrderTunnelService $orderTunnelService */ + $orderTunnelService = \Mockery::mock(OrderTunnelService::class); + $orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder); + $orderTunnelService->shouldReceive('placePendingOrder') + ->once() + ->with($builder) + ->andThrow(new BasketPriceChangedException($refreshedBasket)); + + /** @var \Mockery\MockInterface&BasketRepository $basketRepository */ + $basketRepository = \Mockery::mock(BasketRepository::class); + $basketRepository->shouldReceive('persist') + ->once() + ->with($refreshedBasket); + + $action = new PlacePendingOrder($orderTunnelService, $basketRepository); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeInstanceOf(PlacePendingOrderOutput::class) + ->and($result->status)->toBe(PlacePendingOrderStatus::BASKET_PRICE_CHANGED) + ->and($result->orderReference)->toBeNull() + ->and($result->errorMessage)->toBe('The price of one or more products in your basket has changed.'); + }); + + it('has Locked attribute and lock key contracts', function (): void { + // GIVEN + $shopperId = new ShopperId(Uuid::uuid7()); + $input = new PlacePendingOrderInput(shopperId: $shopperId); + /** @var \Mockery\MockInterface&OrderTunnelService $orderTunnelService */ + $orderTunnelService = \Mockery::mock(OrderTunnelService::class); + /** @var \Mockery\MockInterface&BasketRepository $basketRepository */ + $basketRepository = \Mockery::mock(BasketRepository::class); + + $action = new PlacePendingOrder($orderTunnelService, $basketRepository); + $reflection = new \ReflectionClass(PlacePendingOrder::class); + $attributes = $reflection->getAttributes(Locked::class); + $locked = ($attributes[0] ?? null)?->newInstance(); + + // WHEN + $key = $action->lockKey($input); + $timeout = $action->onLockTimeout($input); + + // THEN + expect($locked)->toBeInstanceOf(Locked::class) + ->and($locked?->ttlSeconds)->toBe(30) + ->and($locked?->waitSeconds)->toBe(10) + ->and($action)->toBeInstanceOf(ProvidesLockKey::class) + ->and($action)->toBeInstanceOf(HandlesLockTimeout::class) + ->and($key)->toBe("order:finalize:shopper:{$shopperId->value}") + ->and($timeout->status)->toBe(PlacePendingOrderStatus::LOCK_TIMEOUT); + }); +}); + +describe('ExportOrderToRegate, ConfirmPlacedOrder and CancelPendingOrder', function (): void { + it('marks ExportOrderToRegate with WithoutTransaction and Locked attributes', function (): void { + // GIVEN + $reflection = new \ReflectionClass(ExportOrderToRegate::class); + + // WHEN + $withoutTx = $reflection->getAttributes(WithoutTransaction::class); + $locked = $reflection->getAttributes(Locked::class); + + // THEN + expect($withoutTx)->toHaveCount(1) + ->and($locked)->toHaveCount(1); + }); + + it('exports order via OrderTunnelService and handles lock timeout', function (): void { + // GIVEN + $orderId = new OrderId(Uuid::uuid7()); + $input = new ExportOrderToRegateInput($orderId); + + /** @var \Mockery\MockInterface&OrderTunnelService $orderTunnelService */ + $orderTunnelService = \Mockery::mock(OrderTunnelService::class); + $orderTunnelService->shouldReceive('exportOrderToRegate')->once()->with($orderId); + + $action = new ExportOrderToRegate($orderTunnelService); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBe(ExportOrderToRegateOutput::SENT) + ->and($action->lockKey($input))->toBe("order:export:{$orderId->value}") + ->and($action->onLockTimeout($input))->toBe(ExportOrderToRegateOutput::LOCK_TIMEOUT); + }); + + it('confirms a placed order and cancels a pending order', function (): void { + // GIVEN + $orderId = new OrderId(Uuid::uuid7()); + $order = new Order( + id: $orderId, + shopId: new ShopId(Uuid::uuid7()), + reference: new OrderReference(Uuid::uuid7()), + employee: new OrderEmployee( + matricule: new Matricule('1234567'), + firstname: 'Jean', + lastname: 'Dupont', + facility: new ShopperEstablishmentCode('ETAB01'), + site: new ShopperSiteCode('SITEA'), + service: new ShopperServiceCode('101'), + ), + deliveryAddress: new DeliveryAddress( + name: 'Shop', + address: '1 rue Test', + postcode: '75001', + city: 'Paris', + ), + pickupTimeSlot: new PickupTimeSlot(new \DateTimeImmutable('+2 days'), new \DateInterval('PT1H')), + status: OrderStatus::VALIDATED, + total: Money::EUR(1000), + lines: [], + ); + + /** @var \Mockery\MockInterface&OrderTunnelService $orderTunnelService */ + $orderTunnelService = \Mockery::mock(OrderTunnelService::class); + $orderTunnelService->shouldReceive('confirmPlacedOrder') + ->once() + ->with($orderId) + ->andReturn($order); + $orderTunnelService->shouldReceive('cancelPendingOrder') + ->once() + ->with($orderId); + + $confirmAction = new ConfirmPlacedOrder($orderTunnelService); + $cancelAction = new CancelPendingOrder($orderTunnelService); + + // WHEN + $confirmResult = $confirmAction(new ConfirmPlacedOrderInput($orderId)); + $cancelResult = $cancelAction(new CancelPendingOrderInput($orderId)); + + // THEN + expect($confirmResult)->toBe(ConfirmPlacedOrderOutput::CONFIRMED) + ->and($cancelResult)->toBe(CancelPendingOrderOutput::CANCELLED); + }); +}); diff --git a/tests/Unit/Domain/Models/Entities/OrderTest.php b/tests/Unit/Domain/Models/Entities/OrderTest.php index 9e63be35..4b642001 100644 --- a/tests/Unit/Domain/Models/Entities/OrderTest.php +++ b/tests/Unit/Domain/Models/Entities/OrderTest.php @@ -280,6 +280,69 @@ describe('Order - fromBasket factory', function (): void { ->and($order->getLines()[0]->product->name)->toBe('Poulet Rôti') ->and($order->getLines()[0]->quantity)->toBe(2); }); + + it('creates an order in WAITING status via pendingFromBasket and validates it to VALIDATED', function (): void { + // GIVEN + $basket = new Basket(new BasketId(Uuid::uuid7()), [ + new BasketProduct( + id: new ProductId(Uuid::uuid7()), + name: 'Poulet Rôti', + qty: 1, + unitPriceHt: Money::EUR(1000), + unitDiscount: Money::EUR(0), + taxRate: TaxRate::TVA_5_5, + weightGrams: 1000, + brand: ProductBrand::loue, + incoId: new IncoId(123456), + orderUnit: OrderUnit::PCE, + slug: 'poulet-roti', + picture: null, + description: null, + weightVariable: false, + discountRate: DiscountRate::zero(), + priceKgTtc: Money::EUR(1000), + ), + ]); + $shopper = new Shopper( + id: new ShopperId(Uuid::uuid7()), + email: new Email('jean.dupont@example.com'), + matricule: new Matricule('1234567'), + nom: 'Dupont', + prenom: 'Jean', + startDate: CarbonImmutable::now(), + endDate: null, + etablissement: new ShopperEstablishmentCode('ETAB01'), + site: new ShopperSiteCode('SITEA'), + service: new ShopperServiceCode('101') + ); + $shop = new Shop( + id: new ShopId(Uuid::uuid7()), + name: 'Cocotte Lyon', + address: '12 rue de la Paix', + postcode: '69001', + city: 'Lyon', + phone: '0478123456' + ); + + // WHEN + $order = Order::pendingFromBasket( + new OrderId(Uuid::uuid7()), + new OrderReference(Uuid::uuid7()), + $basket, + new PickupTimeSlot(new \DateTimeImmutable('+1 day 10:00'), new \DateInterval('PT10M')), + $shopper, + $shop + ); + + // THEN + expect($order->status)->toBe(OrderStatus::WAITING); + + $order->validate(); + expect($order->status)->toBe(OrderStatus::VALIDATED); + + $order->cancel(); + expect(fn () => $order->validate())->toThrow(\DomainException::class, 'Cannot validate a canceled order.'); + }); }); describe('Order - Domain Events', function (): void { diff --git a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php index a1a2f3bd..da9864e7 100644 --- a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php +++ b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php @@ -10,8 +10,10 @@ use DateInterval; use Domain\Builders\OrderBuilder; use Domain\Builders\OrderBuilderCompleted; use Domain\Builders\OrderBuilderWithBasket; +use Domain\Enums\OrderStatus; use Domain\Enums\TaxRate; use Domain\Enums\Units\OrderUnit; +use Domain\Events\AnOrderHasBeenPlaced; use Domain\Exceptions\OrderTunnel\BasketPriceChangedException; use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException; use Domain\Exceptions\OrderTunnel\InactiveShopperException; @@ -26,11 +28,13 @@ use Domain\Models\ValueObjects\BasketProduct; use Domain\Models\ValueObjects\DiscountRate; use Domain\Models\ValueObjects\Email; use Domain\Models\ValueObjects\Entities\BasketId; +use Domain\Models\ValueObjects\Entities\OrderId; use Domain\Models\ValueObjects\Entities\ProductId; use Domain\Models\ValueObjects\Entities\ShopId; use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Models\ValueObjects\IncoId; use Domain\Models\ValueObjects\Matricule; +use Domain\Models\ValueObjects\OrderReference; use Domain\Models\ValueObjects\PickupTimeSlot; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; @@ -910,4 +914,110 @@ describe('OrderTunnelService', function (): void { // THEN expect($action)->toThrow(InactiveShopperException::class); }); + + it('places a WAITING order without calling Regate or dispatching AnOrderHasBeenPlaced', function (): void { + // GIVEN + $builder = createTestBuilder(completed: true); + $shopperId = $builder->getShopperId(); + $shopper = new Shopper( + id: $shopperId, + email: new Email('pending@test.com'), + matricule: new Matricule('1234567'), + nom: 'Doe', + prenom: 'John', + startDate: CarbonImmutable::now()->subYear(), + endDate: null, + etablissement: new ShopperEstablishmentCode('ETAB01'), + site: new ShopperSiteCode('SITEA'), + service: new ShopperServiceCode('101') + ); + $shopperRepo = \Mockery::mock(ShopperRepository::class); + $shopperRepo->shouldReceive('getByIdOrFail')->andReturn($shopper); + + $shop = new Shop(clone $builder->getShopId(), 'Shop', 'Address', '75000', 'Paris'); + $shopRepo = \Mockery::mock(ShopRepository::class); + $shopRepo->shouldReceive('find')->andReturn($shop); + + $orderRepo = \Mockery::mock(OrderRepository::class); + $orderRepo->shouldReceive('persist')->once(); + + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); + $eventDispatcher->shouldNotReceive('dispatch'); + + $regateService = \Mockery::mock(RegateService::class); + $regateService->shouldNotReceive('processOrder'); + + $service = createOrderTunnelService( + shopRepository: $shopRepo, + shopperRepository: $shopperRepo, + orderRepository: $orderRepo, + eventDispatcher: $eventDispatcher, + regateService: $regateService, + ); + + // WHEN + $order = $service->placePendingOrder($builder); + + // THEN + expect($order)->toBeInstanceOf(Order::class) + ->and($order->status)->toBe(OrderStatus::WAITING); + }); + + it('exports, confirms and cancels a pending order across split steps', function (): void { + // GIVEN + $shopId = new ShopId(Uuid::uuid7()); + $shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris'); + $shopper = new Shopper( + id: new ShopperId(Uuid::uuid7()), + email: new Email('split@test.com'), + matricule: new Matricule('1234567'), + nom: 'Doe', + prenom: 'John', + startDate: CarbonImmutable::now()->subYear(), + endDate: null, + etablissement: new ShopperEstablishmentCode('ETAB01'), + site: new ShopperSiteCode('SITEA'), + service: new ShopperServiceCode('101') + ); + $basket = createTestBasket(1); + $order = Order::pendingFromBasket( + new OrderId(Uuid::uuid7()), + new OrderReference(Uuid::uuid7()), + $basket, + new PickupTimeSlot(CarbonImmutable::now()->next('Friday'), new DateInterval('PT1H')), + $shopper, + $shop + ); + + $orderRepo = \Mockery::mock(OrderRepository::class); + $orderRepo->shouldReceive('find')->with($order->id())->andReturn($order); + $orderRepo->shouldReceive('persist')->twice(); + + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); + $eventDispatcher->shouldReceive('dispatch') + ->once() + ->with(\Mockery::type(AnOrderHasBeenPlaced::class)); + + $regateService = \Mockery::mock(RegateService::class); + $regateService->shouldReceive('processOrder')->once(); + + $service = createOrderTunnelService( + orderRepository: $orderRepo, + eventDispatcher: $eventDispatcher, + regateService: $regateService, + ); + + // WHEN + $service->exportOrderToRegate($order->id()); + $confirmed = $service->confirmPlacedOrder($order->id()); + + // THEN + expect($confirmed->status)->toBe(OrderStatus::VALIDATED); + + // WHEN cancelPendingOrder is invoked + $service->cancelPendingOrder($order->id()); + + // THEN + expect($order->status)->toBe(OrderStatus::CANCELED); + }); }); From 1ae8f65d7c4dd7b8ecba8f8dcdc8ada7dd6ed965 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 03:41:39 +0100 Subject: [PATCH 104/183] fix(integrity): include trashed products in max order and purge CRM email cache on deletion --- .../Actions/Customers/RegisterCustomer.php | 23 ++-- app/Models/Product.php | 2 +- app/Services/CrmService.php | 55 ++++++--- .../Customers/RegisterCustomerTest.php | 5 +- .../WithApp/App/Models/ProductTest.php | 48 ++++++++ .../WithApp/App/Services/CrmServiceTest.php | 113 ++++++++++++++++++ 6 files changed, 215 insertions(+), 31 deletions(-) diff --git a/app/Cqs/Actions/Customers/RegisterCustomer.php b/app/Cqs/Actions/Customers/RegisterCustomer.php index 28015f6d..34a25a72 100644 --- a/app/Cqs/Actions/Customers/RegisterCustomer.php +++ b/app/Cqs/Actions/Customers/RegisterCustomer.php @@ -45,8 +45,8 @@ use Webmozart\Assert\Assert; #[Locked(ttlSeconds: 30, waitSeconds: 10)] final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeout, HandlesSuccess, ProvidesLockKey { - /** @var array */ - private array $createdCrmHashcodes = []; + /** @var array */ + private array $createdCrmCustomers = []; public function __construct( private readonly AppCustomerAuthService $authService, @@ -89,7 +89,7 @@ final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeo Assert::isInstanceOf($input, RegisterCustomerInput::class); $inputKey = spl_object_id($input); - unset($this->createdCrmHashcodes[$inputKey]); + unset($this->createdCrmCustomers[$inputKey]); $employee = Employee::query() ->where('matricule', $input->matricule->value) @@ -158,7 +158,10 @@ final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeo } $crmHashcode = CrmHashcode::fromString($result->hashcode); - $this->createdCrmHashcodes[$inputKey] = $crmHashcode; + $this->createdCrmCustomers[$inputKey] = [ + 'hashcode' => $crmHashcode, + 'email' => $input->email, + ]; $customer->hashcode = $crmHashcode; $customer->saveOrFail(); @@ -176,7 +179,7 @@ final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeo Assert::isInstanceOf($input, RegisterCustomerInput::class); Assert::isInstanceOf($result, RegisterCustomerOutput::class); - unset($this->createdCrmHashcodes[spl_object_id($input)]); + unset($this->createdCrmCustomers[spl_object_id($input)]); if ($result->status !== RegisterCustomerStatus::SUCCESS || ! $result->customer instanceof Customer) { return; @@ -199,16 +202,16 @@ final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeo { Assert::isInstanceOf($input, RegisterCustomerInput::class); - $inputKey = spl_object_id($input); - $crmHashcode = $this->createdCrmHashcodes[$inputKey] ?? null; - unset($this->createdCrmHashcodes[$inputKey]); + $inputKey = spl_object_id($input); + $createdCrm = $this->createdCrmCustomers[$inputKey] ?? null; + unset($this->createdCrmCustomers[$inputKey]); - if (! $crmHashcode instanceof CrmHashcode) { + if ($createdCrm === null) { return; } try { - $this->crmService->deleteByHashcode($crmHashcode); + $this->crmService->deleteByHashcode($createdCrm['hashcode'], $createdCrm['email']); } catch (\Throwable $e) { report($e); } diff --git a/app/Models/Product.php b/app/Models/Product.php index 28890bc4..2e99e54a 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -143,7 +143,7 @@ class Product extends Model implements ModelWithOrder, ModelWithStar, ModelWithS $model->slug = Str::slug($model->name); if ($model->order === null) { - $max = self::query()->max('order'); + $max = self::query()->withTrashed()->max('order'); $model->order = is_scalar($max) ? intval($max) + 1 : 1; } } diff --git a/app/Services/CrmService.php b/app/Services/CrmService.php index 1551355e..85e84c5a 100644 --- a/app/Services/CrmService.php +++ b/app/Services/CrmService.php @@ -305,14 +305,7 @@ class CrmService implements CrmCustomerGatewayService */ public function activate(CrmCustomer $customer): object { - if ($customer->hashcode) { - $this->cacheRepository->delete($this->getCustomerHashcodeCacheKey($customer->hashcode)); - unset($this->customerByHashcodeCache[$customer->hashcode]); - } - if ($customer->email) { - $this->cacheRepository->delete($this->getCustomerEmailCacheKey($customer->email)); - unset($this->customerByEmailCache[strtolower(trim($customer->email))]); - } + $this->forgetCustomerCache($customer->hashcode, $customer->email); try { $libCustomer = $this->toLibCrmCustomer($customer); @@ -348,14 +341,7 @@ class CrmService implements CrmCustomerGatewayService */ public function persist(CrmCustomer $customer): CrmCustomer { - if ($customer->hashcode) { - $this->cacheRepository->delete($this->getCustomerHashcodeCacheKey($customer->hashcode)); - unset($this->customerByHashcodeCache[$customer->hashcode]); - } - if ($customer->email) { - $this->cacheRepository->delete($this->getCustomerEmailCacheKey($customer->email)); - unset($this->customerByEmailCache[strtolower(trim($customer->email))]); - } + $this->forgetCustomerCache($customer->hashcode, $customer->email); try { $customer = $this->toLibCrmCustomer($customer); @@ -389,10 +375,27 @@ class CrmService implements CrmCustomerGatewayService /** * @throws \App\Exceptions\CrmServiceException */ - public function deleteByHashcode(CrmHashcode $hashcode): bool + public function deleteByHashcode(CrmHashcode $hashcode, ?Email $email = null): bool { - $this->cacheRepository->delete($this->getCustomerHashcodeCacheKey($hashcode->value)); - unset($this->customerByHashcodeCache[$hashcode->value]); + $resolvedEmail = $email?->value; + + if ($resolvedEmail === null) { + $cachedByHashcode = array_key_exists($hashcode->value, $this->customerByHashcodeCache) + ? $this->customerByHashcodeCache[$hashcode->value] + : $this->cacheRepository->get($this->getCustomerHashcodeCacheKey($hashcode->value)); + + if ($cachedByHashcode instanceof CrmCustomer) { + $resolvedEmail = $cachedByHashcode->email; + } + } + + $this->forgetCustomerCache($hashcode->value, $resolvedEmail); + + foreach ($this->customerByEmailCache as $cachedEmail => $cachedCustomer) { + if ($cachedCustomer instanceof CrmCustomer && $cachedCustomer->hashcode === $hashcode->value) { + $this->forgetCustomerCache(null, $cachedEmail); + } + } try { $customer = new Customer(['hashcode' => $hashcode->value]); @@ -510,6 +513,20 @@ class CrmService implements CrmCustomerGatewayService $refProp->setValue($customer, false); } + private function forgetCustomerCache(?string $hashcode, ?string $email): void + { + if ($hashcode !== null && $hashcode !== '') { + $this->cacheRepository->delete($this->getCustomerHashcodeCacheKey($hashcode)); + unset($this->customerByHashcodeCache[$hashcode]); + } + + if ($email !== null && $email !== '') { + $normalizedEmail = strtolower(trim($email)); + $this->cacheRepository->delete($this->getCustomerEmailCacheKey($normalizedEmail)); + unset($this->customerByEmailCache[$normalizedEmail]); + } + } + private function getCustomerHashcodeCacheKey(string $hashcode): string { return "crm_customer_hashcode_{$hashcode}"; diff --git a/tests/Integration/WithApp/App/Actions/Customers/RegisterCustomerTest.php b/tests/Integration/WithApp/App/Actions/Customers/RegisterCustomerTest.php index e2da5b78..6cefadec 100644 --- a/tests/Integration/WithApp/App/Actions/Customers/RegisterCustomerTest.php +++ b/tests/Integration/WithApp/App/Actions/Customers/RegisterCustomerTest.php @@ -646,7 +646,10 @@ describe('RegisterCustomer action', function (): void { )); $crmService->shouldReceive('deleteByHashcode') ->once() - ->withArgs(fn (CrmHashcode $hash): bool => $hash->value === $crmReturnedHashcode) + ->withArgs( + fn (CrmHashcode $hash, ?Email $deletedEmail): bool => $hash->value === $crmReturnedHashcode + && $deletedEmail?->value === $email->value + ) ->andReturnTrue(); $authService = \Mockery::mock(AppCustomerAuthService::class); diff --git a/tests/Integration/WithApp/App/Models/ProductTest.php b/tests/Integration/WithApp/App/Models/ProductTest.php index 0ac00de8..4e6fd90e 100644 --- a/tests/Integration/WithApp/App/Models/ProductTest.php +++ b/tests/Integration/WithApp/App/Models/ProductTest.php @@ -79,3 +79,51 @@ describe('Product::scopeOrderable', function (): void { Date::setTestNow(); }); }); + +describe('Product order auto-increment with SoftDeletes', function (): void { + it('computes max order including soft-deleted products when saving a new product without explicit order', function (): void { + // GIVEN + $range = new Range(); + $range->name = 'Gamme Order ' . uniqid(); + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $makeProduct = static function (string $name) use ($range): Product { + $product = new Product([ + 'range_id' => $range->id, + 'name' => $name, + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Description', + 'status' => true, + ]); + $product->price = Money::EUR(1000); + $product->short_description = 'Court'; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt'; + $product->picture_large_title = 'title'; + $product->saveOrFail(); + + return $product; + }; + + $first = $makeProduct('Produit 1 ' . uniqid()); + $second = $makeProduct('Produit 2 ' . uniqid()); + $second->delete(); + + // WHEN + $third = $makeProduct('Produit 3 ' . uniqid()); + + // THEN + expect($first->order)->toBe(1) + ->and($second->order)->toBe(2) + ->and($third->order)->toBe(3); + }); +}); diff --git a/tests/Integration/WithApp/App/Services/CrmServiceTest.php b/tests/Integration/WithApp/App/Services/CrmServiceTest.php index 766431e7..42b63aa1 100644 --- a/tests/Integration/WithApp/App/Services/CrmServiceTest.php +++ b/tests/Integration/WithApp/App/Services/CrmServiceTest.php @@ -6,6 +6,7 @@ use App\Exceptions\CrmServiceException; use App\Services\CrmService; use Domain\Enums\Country; use Domain\Models\ValueObjects\CrmCustomer; +use Domain\Models\ValueObjects\Email; use GuzzleHttp\Psr7\Response; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository as ArrayCacheRepository; @@ -256,6 +257,7 @@ describe('CrmService', function (): void { $uuid = Uuid::uuid4(); $expectedHashKey = "crm_customer_hashcode_{$uuid->toString()}"; + $cacheRepository->shouldReceive('get')->with($expectedHashKey)->once()->andReturnNull(); $cacheRepository->shouldReceive('delete')->with($expectedHashKey)->once(); $apiInterface = \Mockery::mock(ApiInterface::class); @@ -320,4 +322,115 @@ describe('CrmService', function (): void { expect(fn () => $service->deleteByHashcode(new CrmHashcode($uuid))) ->toThrow(CrmServiceException::class); }); + + it('clears both hashcode and email caches when email is provided to deleteByHashcode', function (): void { + // GIVEN + /** @var CrmApiV4&\Mockery\MockInterface $crmApi */ + $crmApi = \Mockery::mock(CrmApiV4::class); + $cacheRepository = new ArrayCacheRepository(new ArrayStore()); + $uuid = Uuid::uuid4(); + $email = new Email('Rollback@Example.com'); + $hashKey = "crm_customer_hashcode_{$uuid->toString()}"; + $emailKey = 'crm_customer_email_' . hash('sha256', 'rollback@example.com'); + + $cachedCustomer = new CrmCustomer( + hashcode: $uuid->toString(), + email: $email->value, + password: null, + firstname: 'Jane', + lastname: 'Doe', + birthDate: '1990-01-01', + phone: null, + address: null, + address2: null, + city: 'Paris', + postcode: '75001', + country: Country::france, + optIn: false, + status: false, + lastConnection: null, + ); + $crmApi->shouldReceive('getCustomer')->with('rollback@example.com')->once()->andReturnNull(); + $cacheRepository->put($hashKey, $cachedCustomer, 600); + $cacheRepository->put($emailKey, $cachedCustomer, 600); + + $apiInterface = \Mockery::mock(ApiInterface::class); + $apiInterface->shouldReceive('call')->once()->andReturn( + new \LDC\LDCCRM\Transport\Response( + ApiStatus::OK, + new Response(200, [], (string) json_encode([ + 'version' => Utils::getPackageInfo()['version'], + 'data' => [], + ])) + ) + ); + $refProp = new \ReflectionProperty(ClientModel::class, 'apiInterface'); + $refProp->setValue(null, $apiInterface); + + $service = new CrmService($crmApi, $cacheRepository); + // Prime internal in-memory email cache from repository + expect($service->getCustomerFromEmail($email->value))->toBeInstanceOf(CrmCustomer::class); + + // WHEN + $deleted = $service->deleteByHashcode(new CrmHashcode($uuid), $email); + + // THEN + expect($deleted)->toBeTrue() + ->and($cacheRepository->has($hashKey))->toBeFalse() + ->and($cacheRepository->has($emailKey))->toBeFalse() + ->and($service->getCustomerFromEmail($email->value))->toBeNull(); + }); + + it('clears cached email entry when deleteByHashcode resolves email from hashcode cache', function (): void { + // GIVEN + /** @var CrmApiV4&\Mockery\MockInterface $crmApi */ + $crmApi = \Mockery::mock(CrmApiV4::class); + $cacheRepository = new ArrayCacheRepository(new ArrayStore()); + $uuid = Uuid::uuid4(); + $hashKey = "crm_customer_hashcode_{$uuid->toString()}"; + $emailKey = 'crm_customer_email_' . hash('sha256', 'cached@example.com'); + + $cachedCustomer = new CrmCustomer( + hashcode: $uuid->toString(), + email: 'cached@example.com', + password: null, + firstname: 'Jane', + lastname: 'Doe', + birthDate: '1990-01-01', + phone: null, + address: null, + address2: null, + city: 'Paris', + postcode: '75001', + country: Country::france, + optIn: false, + status: false, + lastConnection: null, + ); + $cacheRepository->put($hashKey, $cachedCustomer, 600); + $cacheRepository->put($emailKey, $cachedCustomer, 600); + + $apiInterface = \Mockery::mock(ApiInterface::class); + $apiInterface->shouldReceive('call')->once()->andReturn( + new \LDC\LDCCRM\Transport\Response( + ApiStatus::OK, + new Response(200, [], (string) json_encode([ + 'version' => Utils::getPackageInfo()['version'], + 'data' => [], + ])) + ) + ); + $refProp = new \ReflectionProperty(ClientModel::class, 'apiInterface'); + $refProp->setValue(null, $apiInterface); + + $service = new CrmService($crmApi, $cacheRepository); + + // WHEN + $deleted = $service->deleteByHashcode(new CrmHashcode($uuid)); + + // THEN + expect($deleted)->toBeTrue() + ->and($cacheRepository->has($hashKey))->toBeFalse() + ->and($cacheRepository->has($emailKey))->toBeFalse(); + }); }); From 317ca4cd03efb02ae1a3c6adbe6036b2164dbc27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 08:45:40 +0100 Subject: [PATCH 105/183] fix(sync): move Arcadia API calls outside transactions, track per-site employee cursors, and release reminder claim on failure --- .../SynchronizeEmployeesWithArcadiaApi.php | 11 +- .../Orders/ReleaseTodayOrderReminder.php | 32 +++++ .../Orders/ReleaseTodayOrderReminderInput.php | 18 +++ .../SynchronizeProductIncosWithArcadiaApi.php | 24 +++- app/Jobs/SendReminderMail.php | 38 ++++-- app/Services/EmployeeSyncService.php | 85 +++++++++++-- config/queue.php | 2 +- tests/Feature/Jobs/SendReminderMailTest.php | 103 ++++++++++++++-- ...SynchronizeEmployeesWithArcadiaApiTest.php | 114 ++++++++++++++++++ .../Orders/ReleaseTodayOrderReminderTest.php | 61 ++++++++++ ...chronizeProductIncosWithArcadiaApiTest.php | 73 +++++++++++ .../App/Services/EmployeeSyncServiceTest.php | 82 +++++++++++++ 12 files changed, 607 insertions(+), 36 deletions(-) create mode 100644 app/Cqs/Actions/Orders/ReleaseTodayOrderReminder.php create mode 100644 app/Cqs/Actions/Orders/ReleaseTodayOrderReminderInput.php create mode 100644 tests/Integration/WithApp/App/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php create mode 100644 tests/Integration/WithApp/App/Actions/Orders/ReleaseTodayOrderReminderTest.php diff --git a/app/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApi.php b/app/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApi.php index cd46d309..e9882c2f 100644 --- a/app/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApi.php +++ b/app/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApi.php @@ -4,16 +4,17 @@ declare(strict_types=1); namespace App\Cqs\Actions\Employee; +use App\Attributes\WithoutTransaction; use App\Contracts\Action; use App\Contracts\ActionInput; use App\Contracts\ActionInputEmpty; -use App\Models\Employee; use App\Services\EmployeeSyncService; use Webmozart\Assert\Assert; /** * @implements \App\Contracts\Action<\App\Contracts\ActionInputEmpty, void> */ +#[WithoutTransaction] final class SynchronizeEmployeesWithArcadiaApi implements Action { public function __construct( @@ -22,15 +23,11 @@ final class SynchronizeEmployeesWithArcadiaApi implements Action } /** @param \App\Contracts\ActionInputEmpty $input */ + #[\Override] public function __invoke(ActionInput $input): void { Assert::isAOf($input, ActionInputEmpty::class); - $wasLastSyncedAt = Employee::query() - ->orderBy('last_sync', 'desc') - ->limit(1) - ->first('last_sync')?->last_sync; - - $this->syncService->synchronize($wasLastSyncedAt); + $this->syncService->synchronize(); } } diff --git a/app/Cqs/Actions/Orders/ReleaseTodayOrderReminder.php b/app/Cqs/Actions/Orders/ReleaseTodayOrderReminder.php new file mode 100644 index 00000000..da3a9536 --- /dev/null +++ b/app/Cqs/Actions/Orders/ReleaseTodayOrderReminder.php @@ -0,0 +1,32 @@ + + */ +final class ReleaseTodayOrderReminder implements Action +{ + /** + * @param \App\Cqs\Actions\Orders\ReleaseTodayOrderReminderInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): bool + { + Assert::isInstanceOf($input, ReleaseTodayOrderReminderInput::class); + + $updated = Order::query() + ->where('id', $input->orderId->value->toString()) + ->where('reminded_at', $input->remindedAt) + ->update(['reminded_at' => null]); + + return $updated > 0; + } +} diff --git a/app/Cqs/Actions/Orders/ReleaseTodayOrderReminderInput.php b/app/Cqs/Actions/Orders/ReleaseTodayOrderReminderInput.php new file mode 100644 index 00000000..5e5b3dd4 --- /dev/null +++ b/app/Cqs/Actions/Orders/ReleaseTodayOrderReminderInput.php @@ -0,0 +1,18 @@ + */ +#[WithoutTransaction] final class SynchronizeProductIncosWithArcadiaApi implements Action { public function __construct( @@ -38,7 +41,20 @@ final class SynchronizeProductIncosWithArcadiaApi implements Action $incos = ProductInco::query()->get(); foreach ($incos as $inco) { - $incoData = $this->arcadiaIncoService->fetchInco($inco->no_art); + try { + $incoData = $this->arcadiaIncoService->fetchInco($inco->no_art); + } catch (\Throwable $e) { + $this->logger->error( + "Failed to fetch ProductInco #{$inco->id} (no_art: {$inco->no_art}): {$e->getMessage()}", + [ + 'product_inco_id' => $inco->id, + 'no_art' => $inco->no_art, + 'exception' => $e, + ] + ); + + continue; + } if ($incoData === null) { $this->logger->warning("Could not sync ProductInco #{$inco->id} (no_art: {$inco->no_art}): not found on Arcadia."); @@ -46,8 +62,10 @@ final class SynchronizeProductIncosWithArcadiaApi implements Action continue; } - $inco->hydrateFromArcadiaDto($incoData); - $inco->saveOrFail(); + DB::transaction(static function () use ($inco, $incoData): void { + $inco->hydrateFromArcadiaDto($incoData); + $inco->saveOrFail(); + }); $updatedCount++; } diff --git a/app/Jobs/SendReminderMail.php b/app/Jobs/SendReminderMail.php index 5ffd7d63..b4d5fbf4 100644 --- a/app/Jobs/SendReminderMail.php +++ b/app/Jobs/SendReminderMail.php @@ -7,6 +7,8 @@ namespace App\Jobs; use App\Contracts\Executor; use App\Cqs\Actions\Orders\ClaimTodayOrderReminder; use App\Cqs\Actions\Orders\ClaimTodayOrderReminderInput; +use App\Cqs\Actions\Orders\ReleaseTodayOrderReminder; +use App\Cqs\Actions\Orders\ReleaseTodayOrderReminderInput; use App\Dto\OrderReminderDto; use App\Dto\OrderReminderLineDto; use App\Models\Employee; @@ -39,8 +41,11 @@ class SendReminderMail implements ShouldBeUnique, ShouldQueue return Date::now()->format('Y-m-d'); } - public function handle(Executor $executor, ClaimTodayOrderReminder $claimAction): void - { + public function handle( + Executor $executor, + ClaimTodayOrderReminder $claimAction, + ReleaseTodayOrderReminder $releaseAction, + ): void { $today = Date::now()->format('Y-m-d'); Order::query() @@ -50,9 +55,9 @@ class SendReminderMail implements ShouldBeUnique, ShouldQueue ->whereNull('reminded_at') ->chunkById( self::CHUNK_SIZE, - function (Collection $orders) use ($executor, $claimAction): void { + function (Collection $orders) use ($executor, $claimAction, $releaseAction): void { /** @var \Illuminate\Database\Eloquent\Collection $orders */ - $this->processChunk($orders, $executor, $claimAction); + $this->processChunk($orders, $executor, $claimAction, $releaseAction); }, 'id' ); @@ -65,6 +70,7 @@ class SendReminderMail implements ShouldBeUnique, ShouldQueue Collection $orders, Executor $executor, ClaimTodayOrderReminder $claimAction, + ReleaseTodayOrderReminder $releaseAction, ): void { $matricules = $orders ->map(fn (Order $order): string => $order->employee->matricule->value) @@ -84,19 +90,31 @@ class SendReminderMail implements ShouldBeUnique, ShouldQueue continue; } - $claimed = $executor->execute( + $dto = $this->toDto($order, $employee); + $remindedAt = CarbonImmutable::now()->utc()->startOfSecond(); + $claimed = $executor->execute( $claimAction, - new ClaimTodayOrderReminderInput($order->getId(), CarbonImmutable::now()), + new ClaimTodayOrderReminderInput($order->getId(), $remindedAt), ); if (! $claimed) { continue; } - $this->notifyEmployee( - $employee, - $this->toDto($order, $employee) - ); + try { + $this->notifyEmployee($employee, $dto); + } catch (\Throwable $e) { + try { + $executor->execute( + $releaseAction, + new ReleaseTodayOrderReminderInput($order->getId(), $remindedAt), + ); + } catch (\Throwable $releaseException) { + report($releaseException); + } + + throw $e; + } } } diff --git a/app/Services/EmployeeSyncService.php b/app/Services/EmployeeSyncService.php index 19f57cb6..13d9fdb8 100644 --- a/app/Services/EmployeeSyncService.php +++ b/app/Services/EmployeeSyncService.php @@ -6,14 +6,18 @@ namespace App\Services; use App\Contracts\QueryInputEmpty; use App\Cqs\Queries\Settings\GetSettingsQuery; +use App\Models\Employee; use Carbon\CarbonInterface; +use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Contracts\Cache\Repository as CacheRepository; use Illuminate\Support\Carbon; use Psr\Log\LoggerInterface; class EmployeeSyncService { - private const SYNC_TIMESTAMP_CACHE = 'EMPLOYEE_LAST_SYNC'; + private const SYNC_TIMESTAMP_CACHE = 'EMPLOYEE_LAST_SYNC'; + + private const SITE_SYNC_TIMESTAMP_CACHE = 'EMPLOYEE_LAST_SYNC:'; public function __construct( private readonly LoggerInterface $logger, @@ -32,31 +36,36 @@ class EmployeeSyncService ?array $sites = null ): void { $sitesToSync = $sites ?? ($this->getSettingsQuery)(new QueryInputEmpty())->getShopperSiteCodes(); - $sinceDate = $since ?? Carbon::createFromTimestamp(0); $this->logger->info('Starting employee synchronization.', [ - 'since' => $sinceDate->format(Carbon::RFC3339), + 'since' => $since?->format(Carbon::RFC3339), 'sites_count' => count($sitesToSync), ]); $totalInserted = 0; $totalUpdated = 0; + /** @var list $failedSites */ + $failedSites = []; foreach ($sitesToSync as $siteCode) { + $siteSince = $since !== null ? Carbon::instance($since) : $this->resolveSinceForSite($siteCode); + $siteSyncStartedAt = Carbon::now(); + $this->logger->debug("Fetching employees for site: {$siteCode->value}", [ 'site' => $siteCode->value, - 'since' => $sinceDate->format(Carbon::RFC3339), + 'since' => $siteSince->format(Carbon::RFC3339), ]); $employees = $this->arcadiaEmployeeService->getEmployeesOfSiteSince( $siteCode, - $sinceDate + $siteSince ); if ($employees === false) { $this->logger->warning("Failed to fetch employees from Arcadia for site: {$siteCode->value}", [ 'site' => $siteCode->value, ]); + $failedSites[] = $siteCode->value; continue; } @@ -66,20 +75,50 @@ class EmployeeSyncService 'count' => count($employees), ]); - $result = $this->employeeUpsertService->upsertEmployees($employees); + try { + $result = $this->employeeUpsertService->upsertEmployees($employees); + } catch (\Throwable $e) { + $this->logger->error("Failed to persist employees for site {$siteCode->value}: {$e->getMessage()}", [ + 'site' => $siteCode->value, + 'exception' => $e, + ]); + $failedSites[] = $siteCode->value; + + continue; + } + + $this->markSiteLastSync($siteCode, $siteSyncStartedAt); $totalInserted += $result->insertedCount; $totalUpdated += $result->updatedCount; } - $this->markLastSync(); + if ($failedSites === []) { + $this->markLastSync(); + } else { + $this->logger->warning('Employee synchronization finished with failed sites; global cursor unchanged.', [ + 'failed_sites' => $failedSites, + ]); + } - $this->logger->info('Employee synchronization completed successfully.', [ + $this->logger->info('Employee synchronization completed.', [ 'total_inserted' => $totalInserted, 'total_updated' => $totalUpdated, + 'failed_sites' => $failedSites, ]); } + public function getSiteLastSync(ShopperSiteCode $siteCode): ?CarbonInterface + { + $timestamp = $this->cacheRepository->get($this->getSiteLastSyncCacheKey($siteCode)); + + if (! is_string($timestamp)) { + return null; + } + + return Carbon::parse($timestamp); + } + public function getLastSync(): ?CarbonInterface { $timestamp = $this->cacheRepository->get(self::SYNC_TIMESTAMP_CACHE); @@ -93,6 +132,36 @@ class EmployeeSyncService return Carbon::parse($timestamp); } + private function resolveSinceForSite(ShopperSiteCode $siteCode): CarbonInterface + { + $cachedLastSync = $this->getSiteLastSync($siteCode); + $dbLastSync = Employee::query() + ->where('site', $siteCode->value) + ->orderBy('last_sync', 'desc') + ->limit(1) + ->first('last_sync')?->last_sync; + + if ($cachedLastSync !== null && $dbLastSync !== null) { + return $cachedLastSync->greaterThan($dbLastSync) ? $cachedLastSync : $dbLastSync; + } + + return $cachedLastSync ?? $dbLastSync ?? Carbon::createFromTimestamp(0); + } + + private function markSiteLastSync(ShopperSiteCode $siteCode, CarbonInterface $syncedAt): void + { + $this->cacheRepository->put( + $this->getSiteLastSyncCacheKey($siteCode), + $syncedAt->format(Carbon::RFC3339), + 3600 * 36 + ); + } + + private function getSiteLastSyncCacheKey(ShopperSiteCode $siteCode): string + { + return self::SITE_SYNC_TIMESTAMP_CACHE . $siteCode->value; + } + private function markLastSync(): void { $now = Carbon::now()->format(Carbon::RFC3339); diff --git a/config/queue.php b/config/queue.php index 71ae952f..eb079676 100644 --- a/config/queue.php +++ b/config/queue.php @@ -79,7 +79,7 @@ return [ 'queue' => env('REDIS_QUEUE', 'default'), 'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90), 'block_for' => null, - 'after_commit' => false, + 'after_commit' => true, ], 'deferred' => [ diff --git a/tests/Feature/Jobs/SendReminderMailTest.php b/tests/Feature/Jobs/SendReminderMailTest.php index ec8ec63a..31fc3acd 100644 --- a/tests/Feature/Jobs/SendReminderMailTest.php +++ b/tests/Feature/Jobs/SendReminderMailTest.php @@ -2,14 +2,15 @@ declare(strict_types=1); -use App\Contracts\Executor; use App\Cqs\Actions\Orders\ClaimTodayOrderReminder; +use App\Cqs\Actions\Orders\ReleaseTodayOrderReminder; use App\Jobs\SendReminderMail; use App\Models\Customer; use App\Models\Employee; use App\Models\Order; use App\Models\Shop; use App\Notifications\OrderTodayReminderNotification; +use App\Services\ActionExecutorService; use Domain\Enums\OrderStatus; use Domain\Models\ValueObjects\Code; use Domain\Models\ValueObjects\DeliveryAddress; @@ -20,12 +21,17 @@ use Domain\Models\ValueObjects\OrderReference; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; +use Illuminate\Cache\ArrayStore; +use Illuminate\Cache\Repository as CacheRepository; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Str; +use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; +use Infrastructure\Adapters\Locks\LaravelCacheLock; use Money\Currency; use Money\Money; use Money\MoneyFormatter; +use Psr\Log\NullLogger; use Ramsey\Uuid\Uuid; describe('SendReminderMail job', function (): void { @@ -69,22 +75,105 @@ describe('SendReminderMail job', function (): void { 'pickup_day' => '2026-11-20', ]); + /** @var MoneyFormatter&\Mockery\MockInterface $formatter */ $formatter = \Mockery::mock(MoneyFormatter::class); $formatter->shouldReceive('format')->once()->andReturn('30,00 €'); - $executor = $this->app->make(Executor::class); - $claimAction = new ClaimTodayOrderReminder(); - $job = new SendReminderMail($formatter); + $executor = new ActionExecutorService( + new LaravelCacheLock(new CacheRepository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + $claimAction = new ClaimTodayOrderReminder(); + $releaseAction = new ReleaseTodayOrderReminder(); + $job = new SendReminderMail($formatter); // WHEN - $job->handle($executor, $claimAction); + $job->handle($executor, $claimAction, $releaseAction); // Re-running on same day (e.g. retry or duplicate run) must not notify twice. - $job->handle($executor, $claimAction); + $job->handle($executor, $claimAction, $releaseAction); // THEN Notification::assertSentToTimes($employee, OrderTodayReminderNotification::class, 1); expect($order->fresh()?->reminded_at)->not->toBeNull() - ->and($job->uniqueId())->toBe('2026-11-20'); + ->and($job->uniqueId())->toBe('2026-11-20') + ->and(config('queue.connections.redis.after_commit'))->toBeTrue(); + + Date::setTestNow(); + }); + + it('releases reminded_at when notification queue dispatch fails so retry can remind the order', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + Date::setTestNow('2026-11-20 10:00:00'); + + $shop = Shop::factory()->create(); + $customer = Customer::query()->forceCreate([ + 'email' => new Email('retry-reminder@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + $employee = Employee::query()->forceCreate([ + 'customer_id' => $customer->id, + 'matricule' => new Matricule('6234567'), + 'nom' => 'Martin', + 'prenom' => 'Luc', + 'code' => new Code('PQR2345'), + 'etablissement' => new ShopperEstablishmentCode('01'), + 'site' => new ShopperSiteCode('SITE'), + 'service' => new ShopperServiceCode('01'), + ]); + + $order = Order::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(Uuid::uuid7()), + 'status' => OrderStatus::VALIDATED->value, + 'total' => new Money(3000, new Currency('EUR')), + 'employee' => new OrderEmployee( + new Matricule('6234567'), + 'Luc', + 'Martin', + new ShopperEstablishmentCode('01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('01'), + ), + 'delivery_address' => new DeliveryAddress('Shop', '1 rue Test', '75000', 'Paris'), + 'pickup_day' => '2026-11-20', + ]); + + /** @var MoneyFormatter&\Mockery\MockInterface $formatter */ + $formatter = \Mockery::mock(MoneyFormatter::class); + $formatter->shouldReceive('format')->twice()->andReturn('30,00 €'); + + $executor = new ActionExecutorService( + new LaravelCacheLock(new CacheRepository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + $claimAction = new ClaimTodayOrderReminder(); + $releaseAction = new ReleaseTodayOrderReminder(); + $job = new SendReminderMail($formatter); + + Notification::shouldReceive('send') + ->once() + ->andThrow(new \RuntimeException('Redis queue unavailable')); + + // WHEN (first attempt fails during queue dispatch) + expect(fn () => $job->handle($executor, $claimAction, $releaseAction)) + ->toThrow(\RuntimeException::class, 'Redis queue unavailable'); + + // THEN (reminded_at was released back to null) + expect($order->fresh()?->reminded_at)->toBeNull(); + + // WHEN (retry succeeds after queue recovers) + Notification::clearResolvedInstances(); + Notification::fake(); + + $job->handle($executor, $claimAction, $releaseAction); + + // THEN + Notification::assertSentToTimes($employee, OrderTodayReminderNotification::class, 1); + expect($order->fresh()?->reminded_at)->not->toBeNull(); Date::setTestNow(); }); diff --git a/tests/Integration/WithApp/App/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php b/tests/Integration/WithApp/App/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php new file mode 100644 index 00000000..867111cd --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php @@ -0,0 +1,114 @@ +employee_sites = ['PA', 'LY']; + $setting->saveOrFail(); + + $baseTxLevel = DB::transactionLevel(); + $arcadiaTxLevel = null; + $lySinceTimestamps = []; + + /** @var ArcadiaEmployeeService&\Mockery\MockInterface $arcadiaService */ + $arcadiaService = \Mockery::mock(ArcadiaEmployeeService::class); + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->once() + ->with(\Mockery::on(static fn (ShopperSiteCode $s): bool => $s->value === 'PA'), \Mockery::any()) + ->andReturnUsing(static function () use (&$arcadiaTxLevel): array { + $arcadiaTxLevel = DB::transactionLevel(); + + return [ + new ArcadiaEmployee( + matricule: new Matricule('9123456'), + lastname: 'Pa', + firstname: 'Alice', + startDate: CarbonImmutable::parse('2026-01-01'), + endDate: null, + etablissement: new ShopperEstablishmentCode('01'), + site: new ShopperSiteCode('PA'), + service: new ShopperServiceCode('01'), + ), + ]; + }); + + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->twice() + ->with(\Mockery::on(static fn (ShopperSiteCode $s): bool => $s->value === 'LY'), \Mockery::any()) + ->andReturnUsing(static function (ShopperSiteCode $site, \DateTimeInterface $since) use (&$lySinceTimestamps): false { + $lySinceTimestamps[] = $since->getTimestamp(); + + return false; + }); + + $cache = new CacheRepository(new ArrayStore()); + $upsertService = new EmployeeUpsertService( + new NullLogger(), + new CodeGenerationService(new SerialCasterBuilder(new NativeBaseConverter())), + new EloquentEmployeeImportStorageService(), + ); + $syncService = new EmployeeSyncService( + new NullLogger(), + $cache, + $arcadiaService, + $upsertService, + new GetSettingsQuery(), + ); + + $action = new SynchronizeEmployeesWithArcadiaApi($syncService); + $executor = new ActionExecutorService( + new LaravelCacheLock($cache), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->once() + ->with( + \Mockery::on(static fn (ShopperSiteCode $s): bool => $s->value === 'PA'), + \Mockery::on(static fn (\DateTimeInterface $since): bool => $since->getTimestamp() > 0), + ) + ->andReturn([]); + + // WHEN + $executor->execute($action, new ActionInputEmpty()); + $executor->execute($action, new ActionInputEmpty()); + + // THEN + expect($arcadiaTxLevel)->toBe($baseTxLevel) + ->and(Employee::query()->where('matricule', '9123456')->first()?->last_sync)->not->toBeNull() + ->and($lySinceTimestamps)->toBe([0, 0]); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Orders/ReleaseTodayOrderReminderTest.php b/tests/Integration/WithApp/App/Actions/Orders/ReleaseTodayOrderReminderTest.php new file mode 100644 index 00000000..db020ab5 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Orders/ReleaseTodayOrderReminderTest.php @@ -0,0 +1,61 @@ +create(); + $order = Order::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(Uuid::uuid7()), + 'status' => OrderStatus::VALIDATED->value, + 'total' => new Money(2000, new Currency('EUR')), + 'employee' => new OrderEmployee( + new Matricule('1000102'), + 'Jean', + 'Dupont', + new ShopperEstablishmentCode('01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('01'), + ), + 'delivery_address' => new DeliveryAddress('Shop', '1 rue Test', '75000', 'Paris'), + 'pickup_day' => '2026-11-20', + 'reminded_at' => $claimedAt, + ]); + + $action = new ReleaseTodayOrderReminder(); + + // WHEN + $mismatchedRelease = $action(new ReleaseTodayOrderReminderInput($order->getId(), $otherAt)); + $matchingRelease = $action(new ReleaseTodayOrderReminderInput($order->getId(), $claimedAt)); + + // THEN + expect($mismatchedRelease)->toBeFalse() + ->and($matchingRelease)->toBeTrue() + ->and($order->fresh()?->reminded_at)->toBeNull(); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php b/tests/Integration/WithApp/App/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php index c139e76f..9d369007 100644 --- a/tests/Integration/WithApp/App/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php +++ b/tests/Integration/WithApp/App/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php @@ -8,6 +8,7 @@ use App\Dto\ArcadiaIncoDataDto; use App\Models\Product; use App\Models\ProductInco; use App\Models\Range; +use App\Services\ActionExecutorService; use App\Services\ArcadiaIncoService; use Domain\Enums\Nutriscore; use Domain\Enums\ProductBrand; @@ -16,9 +17,15 @@ use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; use Domain\Models\ValueObjects\NutritionalValues; +use Illuminate\Cache\ArrayStore; +use Illuminate\Cache\Repository as CacheRepository; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\DB; +use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; +use Infrastructure\Adapters\Locks\LaravelCacheLock; use Money\Money; use Psr\Log\LoggerInterface; +use Psr\Log\NullLogger; uses(RefreshDatabase::class); @@ -122,4 +129,70 @@ describe('SynchronizeProductIncosWithArcadiaApi action', function (): void { ->and($fresh2?->allergens)->toBe('Lait') ->and($fresh2?->nutriscore)->toBe(Nutriscore::B); }); + + it('fetches Arcadia outside SQL transaction and persists other incos when one fetch throws', function () use ($createProductWithInco): void { + // GIVEN + $inco1 = $createProductWithInco(2001); + $inco2 = $createProductWithInco(2002); + $inco3 = $createProductWithInco(2003); + + $baseTxLevel = DB::transactionLevel(); + $fetchTxLevel = null; + /** @var ArcadiaIncoService&\Mockery\MockInterface $arcadiaService */ + $arcadiaService = \Mockery::mock(ArcadiaIncoService::class); + /** @var LoggerInterface&\Mockery\MockInterface $logger */ + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldReceive('info'); + $logger->shouldReceive('warning'); + $logger->shouldReceive('error')->once(); + + $makeDto = static fn (int $noArt, string $ing): ArcadiaIncoDataDto => new ArcadiaIncoDataDto( + noArt: $noArt, + name: "P{$noArt}", + libelle: "Produit {$noArt}", + brand: 'LDC', + ingredients: $ing, + preparation: null, + servings: null, + allergens: null, + sellingArgument: null, + nutriscore: Nutriscore::A, + nutriscoreArgs: null, + nutrition: new NutritionalValues(refWeightG: 100.0, kj: 500.0), + ); + + $arcadiaService->shouldReceive('fetchInco') + ->with(2001) + ->once() + ->andReturnUsing(static function () use (&$fetchTxLevel, $makeDto): ArcadiaIncoDataDto { + $fetchTxLevel = DB::transactionLevel(); + + return $makeDto(2001, '

Updated 2001

'); + }); + $arcadiaService->shouldReceive('fetchInco') + ->with(2002) + ->once() + ->andThrow(new \RuntimeException('Arcadia timeout on 2002')); + $arcadiaService->shouldReceive('fetchInco') + ->with(2003) + ->once() + ->andReturn($makeDto(2003, '

Updated 2003

')); + + $action = new SynchronizeProductIncosWithArcadiaApi($arcadiaService, $logger); + $executor = new ActionExecutorService( + new LaravelCacheLock(new CacheRepository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN + $synced = $executor->execute($action, new ActionInputEmpty()); + + // THEN + expect($synced)->toBe(2) + ->and($fetchTxLevel)->toBe($baseTxLevel) + ->and(ProductInco::query()->find($inco1->id)?->ingredients)->toBe('

Updated 2001

') + ->and(ProductInco::query()->find($inco2->id)?->ingredients)->toBe('Anciens ingrédients') + ->and(ProductInco::query()->find($inco3->id)?->ingredients)->toBe('

Updated 2003

'); + }); }); diff --git a/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php b/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php index d22b1201..7bce7931 100644 --- a/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php +++ b/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php @@ -10,6 +10,7 @@ use App\Services\EmployeeSyncService; use App\Services\EmployeeUpsertService; use App\Services\EmployeeUpsertServiceResult; use Carbon\CarbonImmutable; +use Carbon\CarbonInterface; use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; @@ -17,6 +18,7 @@ use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository as CacheRepository; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Carbon; use Psr\Log\NullLogger; uses(RefreshDatabase::class); @@ -127,4 +129,84 @@ describe('EmployeeSyncService', function (): void { // THEN expect($service->getLastSync())->not->toBeNull(); }); + + it('keeps per-site sync cursor when one site fails so failed site updates are not lost', function (): void { + // GIVEN + $setting = Setting::getSingleton(); + $setting->employee_sites = ['PA', 'LY']; + $setting->saveOrFail(); + + $logger = new NullLogger(); + $cache = new CacheRepository(new ArrayStore()); + $upsertService = \Mockery::mock(EmployeeUpsertService::class); + $upsertService->shouldReceive('upsertEmployees') + ->andReturn(new EmployeeUpsertServiceResult( + insertedCount: 0, + updatedCount: 0, + errors: [] + )); + + $arcadiaService = \Mockery::mock(ArcadiaEmployeeService::class); + + $firstRunTime = CarbonImmutable::parse('2026-11-16 08:00:00'); + Carbon::setTestNow($firstRunTime); + + // First run: PA succeeds, LY fails + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->once() + ->with( + \Mockery::on(static fn (ShopperSiteCode $code): bool => $code->value === 'PA'), + \Mockery::on(static fn (\DateTimeInterface $since): bool => $since->getTimestamp() === 0), + ) + ->andReturn([]); + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->once() + ->with( + \Mockery::on(static fn (ShopperSiteCode $code): bool => $code->value === 'LY'), + \Mockery::on(static fn (\DateTimeInterface $since): bool => $since->getTimestamp() === 0), + ) + ->andReturnFalse(); + + // Second run: PA uses T1 cursor, LY STILL uses epoch 0 cursor because LY previously failed + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->once() + ->with( + \Mockery::on(static fn (ShopperSiteCode $code): bool => $code->value === 'PA'), + \Mockery::on(static fn (\DateTimeInterface $since): bool => $since->getTimestamp() === $firstRunTime->getTimestamp()), + ) + ->andReturn([]); + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->once() + ->with( + \Mockery::on(static fn (ShopperSiteCode $code): bool => $code->value === 'LY'), + \Mockery::on(static fn (\DateTimeInterface $since): bool => $since->getTimestamp() === 0), + ) + ->andReturn([]); + + $service = new EmployeeSyncService( + $logger, + $cache, + $arcadiaService, + $upsertService, + new GetSettingsQuery() + ); + + // WHEN + $service->synchronize(); + + // THEN (after partial failure) + expect($service->getLastSync())->toBeNull() + ->and($service->getSiteLastSync(new ShopperSiteCode('PA')))->toBeInstanceOf(CarbonInterface::class) + ->and($service->getSiteLastSync(new ShopperSiteCode('LY')))->toBeNull(); + + // WHEN (second run succeeds for all sites) + $secondRunTime = CarbonImmutable::parse('2026-11-16 09:00:00'); + Carbon::setTestNow($secondRunTime); + $service->synchronize(); + Carbon::setTestNow(); + + // THEN + expect($service->getLastSync())->not->toBeNull() + ->and($service->getSiteLastSync(new ShopperSiteCode('LY')))->not->toBeNull(); + }); }); From 1e872f09d3ad0456e78df3e0b6a60f0a407cb8e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 10:05:46 +0100 Subject: [PATCH 106/183] refactor(logging): remove 'daily' channel from k8s logging configuration Simplifies the logging setup for Kubernetes by using only 'stdout'. --- config/logging.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/logging.php b/config/logging.php index 1d47522d..9a5dbbbb 100644 --- a/config/logging.php +++ b/config/logging.php @@ -149,7 +149,7 @@ return [ 'k8s' => [ 'driver' => 'stack', - 'channels' => ['daily', 'stdout'], + 'channels' => ['stdout'], 'ignore_exceptions' => false, ], From 0116d220d4df8b8ceb95be5085833d31422b2ff6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 10:35:40 +0100 Subject: [PATCH 107/183] feat(sitemap): implement sitemap generation and configuration - Added new sitemap generation configuration. - Removed deprecated refresh-sitemap configuration. - Updated Product model to implement Sitemapable interface. - Upgraded sitemap-generator dependency to version 8.1. --- app/Models/Product.php | 17 +++- composer.json | 2 +- composer.lock | 157 ++++++++++++++++------------------- config/refresh-sitemap.php | 118 -------------------------- config/sitemap-generator.php | 100 ++++++++++++++++++++++ public/sitemap.xml | 24 ------ 6 files changed, 188 insertions(+), 230 deletions(-) delete mode 100644 config/refresh-sitemap.php create mode 100644 config/sitemap-generator.php delete mode 100644 public/sitemap.xml diff --git a/app/Models/Product.php b/app/Models/Product.php index 2e99e54a..17830478 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -34,8 +34,10 @@ use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Facades\Date; use Illuminate\Support\Str; use Ramsey\Uuid\Uuid; +use Spatie\Sitemap\Tags\Url; use Uwil\Laravel\Redirections\Interfaces\RedirectableInterface; use Uwil\Laravel\Redirections\Traits\IsRedirectable; +use Uwil\SitemapGenerator\Contracts\Sitemapable; /** * @property string $id @@ -110,7 +112,7 @@ use Uwil\Laravel\Redirections\Traits\IsRedirectable; 'picture_large_title', 'picture_large', ])] -class Product extends Model implements ModelWithOrder, ModelWithStar, ModelWithStatus, RedirectableInterface +class Product extends Model implements ModelWithOrder, ModelWithStar, ModelWithStatus, RedirectableInterface, Sitemapable { use HasOrder; use HasStar; @@ -121,6 +123,19 @@ class Product extends Model implements ModelWithOrder, ModelWithStar, ModelWithS public const CREATED_AT = null; + #[\Override] + public function getLocalizedUrl(string $locale): string + { + return route('fo.products.show', ['productWithPricingPublished' => $this->slug]); + } + + /** @return Url|string|string[] */ + #[\Override] + public function toSitemapTag(): Url | string | array + { + return $this->getLocalizedUrl(app()->getLocale()); + } + public function getId(): ProductId { return new ProductId(Uuid::fromString($this->id)); diff --git a/composer.json b/composer.json index d946e3de..38fd9b2f 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,7 @@ "uwil/k8s-laravel": "^3.0", "uwil/laravel-admin-secure": "^6.0", "uwil/laravel-redirections": "^3.0", - "uwil/sitemap-generator": "^7.0", + "uwil/sitemap-generator": "^8.1", "uwil/storage-laravel": "*", "webmozart/assert": "^2.4" }, diff --git a/composer.lock b/composer.lock index db280ac1..29b821fb 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "4153b2dd831c9e7586484890903f713e", + "content-hash": "e234de4cf50bd7d34ad2b9914bd1660f", "packages": [ { "name": "aws/aws-crt-php", @@ -3604,82 +3604,6 @@ }, "time": "2022-12-02T22:17:43+00:00" }, - { - "name": "mcamara/laravel-localization", - "version": "v2.4.2", - "source": { - "type": "git", - "url": "https://github.com/mcamara/laravel-localization.git", - "reference": "dbfa563ea0ceb6d072adc280a8830999ade9ed74" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/mcamara/laravel-localization/zipball/dbfa563ea0ceb6d072adc280a8830999ade9ed74", - "reference": "dbfa563ea0ceb6d072adc280a8830999ade9ed74", - "shasum": "" - }, - "require": { - "laravel/framework": "^11.0|^12.0|^13.0", - "php": "^8.2" - }, - "require-dev": { - "orchestra/testbench": "^9.0|^10.0|^11.0", - "phpunit/phpunit": "^10.1|^11.0|^12.5.12" - }, - "suggest": { - "ext-intl": "*" - }, - "type": "library", - "extra": { - "laravel": { - "aliases": { - "LaravelLocalization": "Mcamara\\LaravelLocalization\\Facades\\LaravelLocalization" - }, - "providers": [ - "Mcamara\\LaravelLocalization\\LaravelLocalizationServiceProvider" - ] - } - }, - "autoload": { - "psr-0": { - "Mcamara\\LaravelLocalization": "src/" - }, - "classmap": [] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Marc Cámara", - "email": "mcamara88@gmail.com", - "role": "Developer" - } - ], - "description": "Easy localization for Laravel", - "homepage": "https://github.com/mcamara/laravel-localization", - "keywords": [ - "laravel", - "localization", - "php" - ], - "support": { - "issues": "https://github.com/mcamara/laravel-localization/issues", - "source": "https://github.com/mcamara/laravel-localization/tree/v2.4.2" - }, - "funding": [ - { - "url": "https://github.com/iwasherefirst2", - "type": "github" - }, - { - "url": "https://github.com/mcamara", - "type": "github" - } - ], - "time": "2026-08-24T08:07:04+00:00" - }, { "name": "mews/purifier", "version": "3.4.4", @@ -10508,27 +10432,38 @@ }, { "name": "uwil/sitemap-generator", - "version": "7.1.1", + "version": "8.1.1", "source": { "type": "git", "url": "git@lab.s-web.fr:ldc-web/projets/sitemap-generator.git", - "reference": "1f789eca239e9c064f9eab8acc1dc5fca3428b00" + "reference": "5ee3a5f748a186cd9aa2ab3c3959f1594d8c4949" }, "dist": { "type": "zip", - "url": "https://lab.s-web.fr/api/v4/projects/108/packages/composer/archives/uwil/sitemap-generator.zip?sha=1f789eca239e9c064f9eab8acc1dc5fca3428b00", - "reference": "1f789eca239e9c064f9eab8acc1dc5fca3428b00", + "url": "https://lab.s-web.fr/api/v4/projects/108/packages/composer/archives/uwil/sitemap-generator.zip?sha=5ee3a5f748a186cd9aa2ab3c3959f1594d8c4949", + "reference": "5ee3a5f748a186cd9aa2ab3c3959f1594d8c4949", "shasum": "" }, "require": { - "illuminate/support": "~11|~12|~13", - "laravel/framework": "~11|~12|~13", - "mcamara/laravel-localization": "^2.4", + "illuminate/support": "^13.0", + "laravel/framework": "^13.0", + "php": "^8.5", "spatie/laravel-sitemap": "^8.1" }, "require-dev": { + "ace-of-aces/intellipest": "^1.0", + "larastan/larastan": "^3.0", + "laravel/pint": "^1.32", + "mcamara/laravel-localization": "^2.4", + "orchestra/testbench": "^11.3", + "pestphp/pest": "^5.3", + "php-parallel-lint/php-parallel-lint": "^1.4", "slevomat/coding-standard": "^8.15" }, + "suggest": { + "league/flysystem-aws-s3-v3": "Required to store the sitemap on an Amazon S3 disk", + "mcamara/laravel-localization": "Required for localized route name translations" + }, "type": "library", "extra": { "laravel": { @@ -10542,7 +10477,57 @@ "Uwil\\SitemapGenerator\\": "src/" } }, - "description": "Create sitemap.xml" + "autoload-dev": { + "psr-4": { + "Uwil\\SitemapGenerator\\Tests\\": "tests/" + } + }, + "scripts": { + "lint": [ + "./vendor/bin/phpcs && ./vendor/bin/pint --test" + ], + "test": [ + "./vendor/bin/pest" + ], + "format": [ + "./vendor/bin/pint" + ], + "analyze": [ + "./vendor/bin/phpstan analyse" + ], + "lint:fix": [ + "./vendor/bin/phpcbf && ./vendor/bin/pint" + ], + "lint:php": [ + "./vendor/bin/parallel-lint --exclude vendor ." + ], + "lint:pint": [ + "./vendor/bin/pint --test" + ], + "lint:phpcs": [ + "./vendor/bin/phpcs" + ], + "lint:phpstan": [ + "./vendor/bin/phpstan analyse" + ], + "test:coverage": [ + "./vendor/bin/pest --log-junit=junit.xml --coverage --coverage-html=tests/coverage --coverage-clover=coverage.xml" + ] + }, + "license": [ + "proprietary" + ], + "authors": [ + { + "name": "LDC Digital", + "email": "digital@ldc.com" + } + ], + "description": "Create sitemap.xml", + "keywords": [ + "laravel", + "sitemap" + ] }, { "name": "uwil/storage-laravel", @@ -17503,5 +17488,5 @@ "php": "^8.5" }, "platform-dev": {}, - "plugin-api-version": "2.9.0" + "plugin-api-version": "2.11.0" } diff --git a/config/refresh-sitemap.php b/config/refresh-sitemap.php deleted file mode 100644 index 4e97a901..00000000 --- a/config/refresh-sitemap.php +++ /dev/null @@ -1,118 +0,0 @@ - [ - '/login', - '/bo', - '/activer', - '/reinitialiser-mdp', - '/gammes-de-produits', - '/gamme-de-produits', - // Hack ignore laravel debug bar. - '/_debugbar', - // Ignore ignition route. - '_ignition/health-check', - // Ignore ignition route. - '_ignition/scripts/{script}', - // Ignore ignition route. - '_ignition/styles/{style}', - ], - - /** - * This table is needed to resolve models matching - * routes - * - * it has to be filled like following - * - * 'products.meat-type' => [ - * 'slugMeatType' => [MeatTypes::class, 'slug'] - * ], - * 'kitchen-side.health-nutrition.balanced-menu.menu' => [ - * 'type' => [BalancedMenuType::class, 'type'] - * ] - * - * The index is the complete route name, the array content is an array - * within index is the argument name with its model class. - * This will allow the generator to generate a route for each of the models - * in this table - */ - 'routesBinder' => [], - - /** - * You can put route conditions here - * These will be used to decide whether the route should appear - * in the sitemap or not - * - * These are called in Eloquent where - * - * example - * - * 'queryConditions' => [ - * 'status' => true, - * 'ocbStatus' => EleveurOcbStatus::yes()->value, - * 'star_moment' => true - * ] - */ - 'queryConditions' => [], - - /** - * The default route frequency to use with sitemap generator - */ - 'routeDefaultFrequency' => Url::CHANGE_FREQUENCY_DAILY, - - /** - * The default route priority to use with sitemap generator - * - * priority should be a number between 0 and 1 - * https://www.sitemaps.org/protocol.html - */ - 'routeDefaultPriority' => 0.5, - - /** - * Frequencies for routes - * use the full or partial route name as index - * and a frequency within \Spatie\Sitemap\Tags\Url constants - */ - 'routeFrequencies' => [], - - /** - * Priorities for routes - * use the full or partial route name as index - * and a priority number between 0 and 1 - */ - 'routePriorities' => [], - - /** - * Enable or disable schedule for the job - * If set to true the sitemap generator will be run - * using the 'cron' instruction - */ - 'schedule' => true, - - /** - * If you want to set specific - * instruction for when to schedule job - * you can set this with a cron instruction - * You can generate one using https://crontab.guru/ - * https://laravel.com/docs/8.x/scheduling#schedule-frequency-options - * - * schedule must be set to true - * - * Default is every day at 15:45 - */ - 'cron' => '45 15 * * *', -]; diff --git a/config/sitemap-generator.php b/config/sitemap-generator.php new file mode 100644 index 00000000..8fcca003 --- /dev/null +++ b/config/sitemap-generator.php @@ -0,0 +1,100 @@ + [ + * 'homepage', + * ], + */ + 'single_pages' => [ + 'fo.pages.home', + 'fo.pages.terms', + 'fo.pages.contact', + 'fo.pages.privacy', + 'fo.pages.faq', + 'fo.pages.legal-notice', + 'fo.products.index', + ], + + /** + * Model namespaces with filters + * + * Ex: (model_filters & relation_filters are not necessaries) + * 'cruds' => [ + * [ + * 'model' => 'App\Models\Product', + * 'model_filters' => [ + * ['published', '=', true] + * ], + * 'relation_filters' => [ + * 'range' => fn(Builder $q) => $q->where('status', true), + * ], + * 'allow_null_relation' => ['range'], + * ], + * [ + * 'model' => 'App\Models\Article', + * ] + * ], + */ + 'cruds' => [ + [ + 'model' => Product::class, + 'model_filters' => [ + ['status', '=', true], + ], + 'relation_filters' => [ + 'range' => fn (Builder $q) => $q->where('status', true), + ], + ], + ], + + /** + * Enable or disable schedule for the job + * If set to true the sitemap generator will be run + * using the 'cron' instruction + */ + 'schedule' => true, + + /** + * If you want to set specific + * instruction for when to schedule job + * you can set this with a cron instruction + * You can generate one using https://crontab.guru/ + * + * schedule must be set to true + * + * Default is every day at 15:45 + */ + 'cron' => '45 15 * * *', + + /** + * All supported locales in the project. + * When used with mcamara/laravel-localization, you can get the values from the package config : + * 'supported_locales' => array_keys(config('laravellocalization.supportedLocales', ['fr' => "Fr"])) + */ + 'supported_locales' => ['fr'], + + /** + * The location where the sitemap file should be generated. + */ + 'output' => [ + 'storage_disk' => 's3-public', + 'path' => 'sitemap.xml', + ], + + /** + * The route localizer strategy to use. + * Supported: 'default', 'mcamara', or a custom class implementing RouteLocalizerInterface. + */ + 'localizer' => 'default', +]; diff --git a/public/sitemap.xml b/public/sitemap.xml deleted file mode 100644 index efc06382..00000000 --- a/public/sitemap.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - https://www.laboutiquedecocotte.fr/ - monthly - 1.0 - - - https://www.laboutiquedecocotte.fr/contactez-nous - - - https://www.laboutiquedecocotte.fr/mentions-legales - - - https://www.laboutiquedecocotte.fr/faq - - - https://www.laboutiquedecocotte.fr/cgv - - - https://www.laboutiquedecocotte.fr/charte-de-confidentialite - - \ No newline at end of file From 2d616ed3b4ace22c1fcb6e5a370554bc1dbcb93b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 10:39:39 +0100 Subject: [PATCH 108/183] fix(translations): add missing employee account message in fr.json Ensures consistency in employee account messages for French localization. --- app/Models/Order.php | 2 +- app/Models/Range.php | 2 ++ lang/en.json | 2 +- lang/fr.json | 2 +- 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/app/Models/Order.php b/app/Models/Order.php index d2650709..4c957457 100644 --- a/app/Models/Order.php +++ b/app/Models/Order.php @@ -31,8 +31,8 @@ use Ramsey\Uuid\Uuid; * @property \Money\Money $total * @property OrderStatus $status * @property \Illuminate\Support\Carbon|null $updated_at - * @property \Illuminate\Support\Carbon|null $reminded_at * @property string|null $employee_matricule + * @property \Illuminate\Support\Carbon $reminded_at * @property-read \Carbon\CarbonInterface|null $created_at * @property-read \Illuminate\Database\Eloquent\Collection $lines * @property-read \App\Models\Shop|null $shop diff --git a/app/Models/Range.php b/app/Models/Range.php index 24adc678..5384b87f 100644 --- a/app/Models/Range.php +++ b/app/Models/Range.php @@ -32,6 +32,8 @@ use Uwil\Laravel\Redirections\Traits\IsRedirectable; * @property \Illuminate\Support\Carbon|null $updated_at * @property-read \Illuminate\Database\Eloquent\Collection $products * + * @method static Builder|Range published() + * * @mixin \Eloquent */ #[Fillable([ diff --git a/lang/en.json b/lang/en.json index f9765592..7d667910 100644 --- a/lang/en.json +++ b/lang/en.json @@ -780,8 +780,8 @@ "The verification link is invalid or the customer account was not found.": "The verification link is invalid or the customer account was not found.", "This action is unauthorized.": "This action is unauthorized.", "This activation link is not valid": "This activation link is not valid", - "This employee already has an account.": "This employee already has an account.", "This employee account is no longer active.": "This employee account is no longer active.", + "This employee already has an account.": "This employee already has an account.", "This is not the page you are looking for...": "This is not the page you are looking for...", "This password reset link will expire in :count minutes.": "This password reset link will expire in :count minutes.", "to": "to", diff --git a/lang/fr.json b/lang/fr.json index 9be9c2a8..a65f0975 100644 --- a/lang/fr.json +++ b/lang/fr.json @@ -780,8 +780,8 @@ "The verification link is invalid or the customer account was not found.": "Le lien de vérification est invalide ou le compte client n'a pas été trouvé.", "This action is unauthorized.": "Cette action n'est pas autorisée.", "This activation link is not valid": "Ce lien d'activation n'est pas valide", - "This employee already has an account.": "Ce salarié possède déjà un compte.", "This employee account is no longer active.": "Ce compte salarié n'est plus actif.", + "This employee already has an account.": "Ce salarié possède déjà un compte.", "This is not the page you are looking for...": "Ce n'est pas la page que vous recherchez...", "This password reset link will expire in :count minutes.": "Ce lien de réinitialisation du mot de passe expirera dans :count minutes.", "to": "à", From c429697025582852e3dfea555915800ce13a88dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 11:08:01 +0100 Subject: [PATCH 109/183] chore(deps): upgrade uwil/laravel-k8s to ^4.0 and uwil/sitemap-generator to ^8.1 --- composer.json | 2 +- composer.lock | 136 +++++++++++++++++++++++++++----------------------- 2 files changed, 75 insertions(+), 63 deletions(-) diff --git a/composer.json b/composer.json index 38fd9b2f..5db772a4 100644 --- a/composer.json +++ b/composer.json @@ -26,8 +26,8 @@ "propaganistas/laravel-phone": "^6.0", "sentry/sentry-laravel": "^4.18", "uwil/arcadia-api-php-client": "^1.0", - "uwil/k8s-laravel": "^3.0", "uwil/laravel-admin-secure": "^6.0", + "uwil/laravel-k8s": "^4.0", "uwil/laravel-redirections": "^3.0", "uwil/sitemap-generator": "^8.1", "uwil/storage-laravel": "*", diff --git a/composer.lock b/composer.lock index 29b821fb..e1df036f 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "e234de4cf50bd7d34ad2b9914bd1660f", + "content-hash": "307a7c2e8f85c8f50ed609d5fdb475ff", "packages": [ { "name": "aws/aws-crt-php", @@ -10236,67 +10236,6 @@ ], "description": "Client generated with Kiota with Arcadia Api OpenApi specification" }, - { - "name": "uwil/k8s-laravel", - "version": "3.0.0", - "source": { - "type": "git", - "url": "git@lab.s-web.fr:ldc-web/projets/k8s-laravel.git", - "reference": "96f85bef45b1ee8d6c2f85e5af2aa6003fa357fd" - }, - "dist": { - "type": "zip", - "url": "https://lab.s-web.fr/api/v4/projects/90/packages/composer/archives/uwil/k8s-laravel.zip?sha=96f85bef45b1ee8d6c2f85e5af2aa6003fa357fd", - "reference": "96f85bef45b1ee8d6c2f85e5af2aa6003fa357fd", - "shasum": "" - }, - "require": { - "illuminate/support": "~8|~9|~10|~11|~12|~13", - "laravel/framework": "~8|~9|~10|~11|~12|~13", - "php": "~7.3|~7.4|~8" - }, - "require-dev": { - "orchestra/testbench": "^8.5", - "phpunit/php-code-coverage": "^9.2", - "phpunit/phpunit": "^9.6", - "slevomat/coding-standard": "^8.3", - "squizlabs/php_codesniffer": "^3.7" - }, - "type": "library", - "extra": { - "laravel": { - "providers": [ - "Uwil\\K8S\\Laravel\\K8SServiceProvider" - ] - } - }, - "autoload": { - "psr-4": { - "Uwil\\K8S\\Laravel\\": "src/" - } - }, - "autoload-dev": { - "psr-4": { - "Uwil\\K8S\\Laravel\\Tests\\": "tests" - } - }, - "scripts": { - "test": [ - "vendor/bin/phpunit" - ], - "post-autoload-dump": [ - "@php ./vendor/bin/testbench package:discover --ansi" - ] - }, - "license": [ - "MIT" - ], - "description": "Laravel requirements for k8s", - "support": { - "email": "equipe.web@ldc.fr", - "issues": "https://lab.s-web.fr/ldc-web/projets/k8s-laravel/-/issues" - } - }, { "name": "uwil/laravel-admin-secure", "version": "6.0.1", @@ -10372,6 +10311,79 @@ "issues": "https://lab.s-web.fr/ldc-web/projets/laravel-admin-secure/-/issues" } }, + { + "name": "uwil/laravel-k8s", + "version": "4.0.4", + "source": { + "type": "git", + "url": "git@lab.s-web.fr:ldc-web/projets/k8s-laravel.git", + "reference": "40ed74d246538e6cd60a7f2059780898323e5a7e" + }, + "dist": { + "type": "zip", + "url": "https://lab.s-web.fr/api/v4/projects/90/packages/composer/archives/uwil/laravel-k8s.zip?sha=40ed74d246538e6cd60a7f2059780898323e5a7e", + "reference": "40ed74d246538e6cd60a7f2059780898323e5a7e", + "shasum": "" + }, + "require": { + "illuminate/support": "~8|~9|~10|~11|~12|~13", + "laravel/framework": "~8|~9|~10|~11|~12|~13", + "php": "~7.3|~7.4|~8" + }, + "require-dev": { + "driftingly/rector-laravel": "^2.3", + "larastan/larastan": "^3.9", + "laravel/pint": "^1.29", + "orchestra/testbench": "^11.1", + "slevomat/coding-standard": "^8.3", + "squizlabs/php_codesniffer": "^3.7" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Uwil\\LaravelK8S\\K8SServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "Uwil\\LaravelK8S\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Uwil\\LaravelK8S\\Tests\\": "tests" + } + }, + "scripts": { + "phpcs": [ + "./vendor/bin/phpcs" + ], + "rector": [ + "./vendor/bin/rector" + ], + "phpstan": [ + "./vendor/bin/phpstan" + ], + "post-autoload-dump": [ + "@php ./vendor/bin/testbench package:discover --ansi" + ] + }, + "license": [ + "MIT" + ], + "description": "Laravel requirements for k8s.", + "keywords": [ + "k8s", + "laravel", + "uwil" + ], + "support": { + "email": "digital@ldc.fr", + "issues": "https://lab.s-web.fr/ldc-web/projets/laravel-k8s/-/issues" + } + }, { "name": "uwil/laravel-redirections", "version": "3.0.0", From 3916771f69e43a17f9b32b2531586d1323b9d831 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 11:22:47 +0100 Subject: [PATCH 110/183] test: update tests to remove schema creation and use factories Refactor tests to eliminate schema creation in beforeEach hooks and utilize model factories for data setup. --- .../Directories/EloquentCodeDirectoryTest.php | 15 +--- .../Directories/EloquentShopDirectoryTest.php | 25 +----- .../EloquentOrderRepositoryTest.php | 53 ++--------- .../EloquentPickupExceptionRepositoryTest.php | 48 +--------- .../EloquentProductRepositoryTest.php | 87 ++++++------------- .../EloquentShopRepositoryTest.php | 51 +---------- .../EloquentShopperRepositoryTest.php | 35 +------- ...oquentEmployeeImportStorageServiceTest.php | 25 +----- .../EloquentEmployeeStatisticsServiceTest.php | 30 ++----- 9 files changed, 51 insertions(+), 318 deletions(-) diff --git a/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentCodeDirectoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentCodeDirectoryTest.php index 300adb16..ee2e2a03 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentCodeDirectoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentCodeDirectoryTest.php @@ -7,24 +7,11 @@ namespace Tests\Integration\WithApp\Infra\Adapters\Directories; use App\Models\Employee; use Domain\Models\ValueObjects\Code; use Domain\Models\ValueObjects\Matricule; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; use Infrastructure\Adapters\Directories\EloquentCodeDirectory; -beforeEach(function () { - if (! Schema::hasTable('employees')) { - Schema::create('employees', function (Blueprint $table) { - $table->id(); - $table->string('code')->nullable(); - $table->timestamps(); - }); - } - Employee::query()->delete(); -}); - it('confirms the existence of a given code in the repository', function () { // GIVEN - Employee::forceCreate([ + Employee::query()->forceCreate([ 'code' => new Code('99999998'), 'matricule' => new Matricule('9999999'), 'nom' => 'N', diff --git a/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php index c11fe1b5..82f4a24e 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php @@ -4,30 +4,9 @@ declare(strict_types=1); use App\Models\Shop; use Domain\Models\ValueObjects\Entities\ShopId; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Schema; use Infrastructure\Adapters\Directories\EloquentShopDirectory; use Ramsey\Uuid\Uuid; -beforeEach(function () { - if (! Schema::hasTable('shops')) { - Schema::create('shops', function (Blueprint $table) { - $table->id(); - $table->string('name'); - $table->string('address'); - $table->string('postcode'); - $table->string('city'); - $table->string('phone')->nullable(); - $table->string('latitude')->nullable(); - $table->string('longitude')->nullable(); - $table->boolean('default')->default(false); - $table->timestamps(); - }); - } - DB::table('shops')->delete(); -}); - it('retrieves all available shops', function () { // GIVEN Shop::forceCreate([ @@ -71,8 +50,8 @@ it('finds a shop by its identifier', function () { // THEN expect($shop)->not->toBeNull() - ->and($shop->id->value->toString())->toBe($model->id) - ->and($shop->name)->toBe($model->name); + ->and($shop?->id->value->toString())->toBe($model->id) + ->and($shop?->name)->toBe($model->name); }); it('returns null if shop by id is not found', function () { diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php index d6c22341..0db61cef 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php @@ -3,55 +3,16 @@ declare(strict_types=1); use Domain\Enums\OrderStatus; +use Domain\Models\Entities\Order as DomainOrder; use Domain\Models\ValueObjects\Entities\OrderId; -use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Schema; use Infrastructure\Adapters\Repositories\EloquentOrderRepository; -use Money\Currency; use Ramsey\Uuid\Uuid; - -beforeEach(function () { - if (! Schema::hasTable('orders')) { - Schema::create('orders', function (Blueprint $table) { - $table->string('id')->primary(); - $table->uuid('shop_id'); - $table->string('reference'); - $table->json('employee'); - $table->json('delivery_address'); - $table->date('pickup_day'); - $table->string('status'); - $table->integer('total'); - $table->string('employee_matricule')->nullable(); - $table->timestamps(); - }); - } - - if (! Schema::hasTable('order_lines')) { - Schema::create('order_lines', function (Blueprint $table) { - $table->id(); - $table->string('order_id'); - $table->json('product'); - $table->integer('quantity'); - $table->integer('tax_rate'); - $table->integer('unit_price'); - $table->integer('unit_tax'); - $table->integer('unit_discount'); - $table->integer('total_discount'); - $table->integer('total_ht'); - $table->integer('total_tax'); - $table->integer('total_ttc'); - $table->timestamps(); - }); - } - - DB::table('orders')->delete(); - DB::table('order_lines')->delete(); -}); +use Webmozart\Assert\Assert; it('returns null when finding a non-existent order by id', function () { // GIVEN - $repo = new EloquentOrderRepository(new Currency('EUR')); + $repo = new EloquentOrderRepository(); $orderId = new OrderId(Uuid::fromString('018e4567-e89b-72d3-a456-426614174001')); // WHEN @@ -84,15 +45,17 @@ it('updates an existing order in the repository', function () { 'total' => 1000, ]); - $repo = new EloquentOrderRepository(new Currency('EUR')); + $repo = new EloquentOrderRepository(); - $domainOrder = $repo->find(new OrderId(Uuid::fromString('018e4567-e89b-72d3-a456-426614174002'))); + $domainOrder = $repo->find(new OrderId(Uuid::fromString('018e4567-e89b-72d3-a456-426614174002'))); + Assert::isInstanceOf($domainOrder, DomainOrder::class); $domainOrder->status = OrderStatus::VALIDATED; // WHEN $repo->persist($domainOrder); // THEN + /** @var object{status: int}|null $updatedOrder */ $updatedOrder = DB::table('orders')->where('id', '018e4567-e89b-72d3-a456-426614174002')->first(); - expect($updatedOrder->status)->toBe(OrderStatus::VALIDATED->value); + expect($updatedOrder?->status)->toBe(OrderStatus::VALIDATED->value); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php index 0718e9db..78455518 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php @@ -9,56 +9,10 @@ use Domain\Enums\RepeatFrequency; use Domain\Models\Entities\PickupExceptionOnDate; use Domain\Models\ValueObjects\Entities\ShopId; use Domain\Models\ValueObjects\ShopPickupOverride; -use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Schema; use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; use Ramsey\Uuid\Uuid; -beforeEach(function () { - if (! Schema::hasTable('shops')) { - Schema::create('shops', function (Blueprint $table) { - $table->id(); - $table->string('name')->nullable(); - $table->string('address')->nullable(); - $table->string('postcode')->nullable(); - $table->string('city')->nullable(); - $table->string('phone')->nullable(); - $table->string('latitude')->nullable(); - $table->string('longitude')->nullable(); - $table->boolean('default')->default(false); - $table->timestamps(); - }); - } - - if (! Schema::hasTable('pickup_exceptions')) { - Schema::create('pickup_exceptions', function (Blueprint $table) { - $table->id(); - $table->date('date'); - $table->string('label'); - $table->boolean('repeatable')->default(false); - $table->string('repeat_frequency')->default('Weekly'); - $table->boolean('auto_updated')->default(false); - $table->timestamps(); - }); - } - - if (! Schema::hasTable('shop_pickup_exception')) { - Schema::create('shop_pickup_exception', function (Blueprint $table) { - $table->id(); - $table->unsignedBigInteger('shop_id'); - $table->unsignedBigInteger('pickup_exception_id'); - $table->date('replacement_date')->nullable(); - $table->dateTime('order_deadline_at')->nullable(); - $table->timestamps(); - }); - } - - DB::table('shops')->delete(); - DB::table('pickup_exceptions')->delete(); - DB::table('shop_pickup_exception')->delete(); -}); - it('retrieves exceptions within a period for a shop', function () { // GIVEN $shopUuid = Uuid::uuid7(); @@ -153,5 +107,5 @@ it('retrieves exceptions associated with a shop', function () { expect($result)->toHaveCount(1) ->and($result[0])->toBeInstanceOf(ShopPickupOverride::class) ->and($result[0]->exception->id->value->toString())->toBe($exUuid->toString()) - ->and($result[0]->replacementDate->format('Y-m-d'))->toBe('2023-01-11'); + ->and($result[0]->replacementDate?->format('Y-m-d'))->toBe('2023-01-11'); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php index c3881c82..1bd0a45c 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php @@ -3,78 +3,37 @@ declare(strict_types=1); use App\Models\Product; +use App\Models\Range; use Domain\Enums\Units\OrderUnit; use Domain\Exceptions\OrderTunnel\UnorderableProductException; use Domain\Models\Entities\Product as DomainProduct; use Domain\Models\ValueObjects\BasketProduct; use Domain\Models\ValueObjects\Entities\ProductId; -use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Schema; use Infrastructure\Adapters\Repositories\EloquentProductRepository; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; -beforeEach(function () { - if (! Schema::hasTable('ranges')) { - Schema::create('ranges', function ($table) { - $table->id(); - $table->string('name'); - $table->string('slug'); - $table->timestamps(); - }); - } - DB::table('ranges')->insertOrIgnore(['id' => 1, 'name' => 'test', 'slug' => 'test']); +function createRepoTestProductRange(): int +{ + $range = new Range(); + $range->name = 'Gamme Test ' . uniqid(); + $range->status = true; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); - if (! Schema::hasTable('products')) { - Schema::create('products', function (Blueprint $table) { - $table->uuid('id')->primary(); - $table->string('name'); - $table->integer('tax_rate'); - $table->integer('weight'); - $table->string('brand')->nullable(); - $table->string('order_unit')->nullable(); - $table->string('slug'); - $table->string('picture')->nullable(); - $table->text('description')->nullable(); - $table->boolean('weight_variable')->default(false); - - // Required for toDomain - $table->string('invoicing_unit')->nullable(); - $table->string('sell_unit')->nullable(); - $table->unsignedBigInteger('range_id')->default(1); - $table->string('status')->nullable(); - $table->integer('price')->nullable(); - $table->integer('price_kg')->nullable(); - $table->string('origin_country')->nullable(); - $table->text('conservation')->nullable(); - $table->timestamp('orderable_start')->nullable(); - $table->timestamp('orderable_end')->nullable(); - - $table->timestamps(); - }); - } - - if (! Schema::hasTable('product_incos')) { - Schema::create('product_incos', function (Blueprint $table) { - $table->id(); - $table->uuid('product_id'); - $table->unsignedInteger('no_art'); - $table->timestamps(); - }); - } - - DB::table('product_incos')->delete(); - DB::table('products')->delete(); -}); + return $range->id; +} it('retrieves a basket product', function () { // GIVEN $uuid = Uuid::uuid7()->toString(); $currency = new Currency('EUR'); + $rangeId = createRepoTestProductRange(); - Product::forceCreate([ + Product::query()->forceCreate([ 'id' => $uuid, 'name' => 'Product Name', 'tax_rate' => 1, @@ -83,7 +42,7 @@ it('retrieves a basket product', function () { 'order_unit' => OrderUnit::PCE->value, 'invoicing_unit' => 'PCE', 'sell_unit' => 'PCE', - 'range_id' => 1, + 'range_id' => $rangeId, 'slug' => 'product-name', 'picture' => 'pic.jpg', 'picture_alt' => '', @@ -114,6 +73,7 @@ it('throws UnorderableProductException when retrieving a basket product without // GIVEN $uuid = Uuid::uuid7()->toString(); $currency = new Currency('EUR'); + $rangeId = createRepoTestProductRange(); Product::query()->forceCreate([ 'id' => $uuid, @@ -124,7 +84,7 @@ it('throws UnorderableProductException when retrieving a basket product without 'order_unit' => OrderUnit::PCE->value, 'invoicing_unit' => 'PCE', 'sell_unit' => 'PCE', - 'range_id' => 1, + 'range_id' => $rangeId, 'slug' => 'product-without-inco', 'picture' => 'pic.jpg', 'picture_alt' => '', @@ -151,6 +111,7 @@ it('throws UnorderableProductException when retrieving an unpublished basket pro // GIVEN $uuid = Uuid::uuid7()->toString(); $currency = new Currency('EUR'); + $rangeId = createRepoTestProductRange(); Product::query()->forceCreate([ 'id' => $uuid, @@ -161,7 +122,7 @@ it('throws UnorderableProductException when retrieving an unpublished basket pro 'order_unit' => OrderUnit::PCE->value, 'invoicing_unit' => 'PCE', 'sell_unit' => 'PCE', - 'range_id' => 1, + 'range_id' => $rangeId, 'slug' => 'unpublished-product', 'picture' => 'pic.jpg', 'picture_alt' => '', @@ -190,6 +151,7 @@ it('throws UnorderableProductException when retrieving a basket product outside $expiredUuid = Uuid::uuid7()->toString(); $futureUuid = Uuid::uuid7()->toString(); $currency = new Currency('EUR'); + $rangeId = createRepoTestProductRange(); Product::query()->forceCreate([ 'id' => $expiredUuid, @@ -200,7 +162,7 @@ it('throws UnorderableProductException when retrieving a basket product outside 'order_unit' => OrderUnit::PCE->value, 'invoicing_unit' => 'PCE', 'sell_unit' => 'PCE', - 'range_id' => 1, + 'range_id' => $rangeId, 'slug' => 'expired-product', 'picture' => 'pic.jpg', 'picture_alt' => '', @@ -224,7 +186,7 @@ it('throws UnorderableProductException when retrieving a basket product outside 'order_unit' => OrderUnit::PCE->value, 'invoicing_unit' => 'PCE', 'sell_unit' => 'PCE', - 'range_id' => 1, + 'range_id' => $rangeId, 'slug' => 'future-product', 'picture' => 'pic.jpg', 'picture_alt' => '', @@ -252,9 +214,10 @@ it('throws UnorderableProductException when retrieving a basket product outside it('finds a product by id', function () { // GIVEN - $uuid = Uuid::uuid7()->toString(); + $uuid = Uuid::uuid7()->toString(); + $rangeId = createRepoTestProductRange(); - Product::forceCreate([ + Product::query()->forceCreate([ 'id' => $uuid, 'name' => 'Product Name', 'tax_rate' => 1, @@ -263,7 +226,7 @@ it('finds a product by id', function () { 'slug' => 'product-name', 'invoicing_unit' => 'PCE', 'sell_unit' => 'PCE', - 'range_id' => 1, + 'range_id' => $rangeId, 'picture_alt' => '', 'picture_title' => '', 'picture_large_alt' => '', diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php index a3b7d31f..40337567 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php @@ -10,53 +10,10 @@ use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Database\Eloquent\ModelNotFoundException; -use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Schema; use Infrastructure\Adapters\Repositories\EloquentShopRepository; use Ramsey\Uuid\Uuid; -beforeEach(function () { - if (! Schema::hasTable('shops')) { - Schema::create('shops', function (Blueprint $table) { - $table->id(); - $table->string('name'); - $table->string('address'); - $table->string('postcode'); - $table->string('city'); - $table->string('phone')->nullable(); - $table->string('latitude')->nullable(); - $table->string('longitude')->nullable(); - $table->boolean('default')->default(false); - $table->timestamps(); - }); - } - - if (! Schema::hasTable('shop_employee_exception')) { - Schema::create('shop_employee_exception', function (Blueprint $table) { - $table->id(); - $table->string('matricule'); - $table->unsignedBigInteger('shop_id'); - $table->timestamps(); - }); - } - - if (! Schema::hasTable('shop_employees')) { - Schema::create('shop_employees', function (Blueprint $table) { - $table->id(); - $table->string('site_code'); - $table->string('service_code')->nullable(); - $table->unsignedBigInteger('shop_id'); - $table->timestamps(); - }); - } - - DB::table('shops')->delete(); - DB::table('employees')->delete(); - DB::table('shop_employee_exception')->delete(); - DB::table('shop_employees')->delete(); -}); - it('finds exception shop for a matricule', function () { // GIVEN $shop = Shop::forceCreate([ @@ -88,7 +45,7 @@ it('finds exception shop for a matricule', function () { // THEN expect($result)->not->toBeNull() - ->and($result->id->value->toString())->toBe($shop->id); + ->and($result?->id->value->toString())->toBe($shop->id); }); it('returns null if exception shop is not found', function () { @@ -125,7 +82,7 @@ it('finds shop for site and service', function () { // THEN expect($result)->not->toBeNull() - ->and($result->id->value->toString())->toBe($shop->id); + ->and($result?->id->value->toString())->toBe($shop->id); }); it('finds shop for site and null service', function () { @@ -151,7 +108,7 @@ it('finds shop for site and null service', function () { // THEN expect($result)->not->toBeNull() - ->and($result->id->value->toString())->toBe($shop->id); + ->and($result?->id->value->toString())->toBe($shop->id); }); it('returns null if shop for site and service is not found', function () { @@ -182,7 +139,7 @@ it('finds shop by id', function () { // THEN expect($result)->not->toBeNull() - ->and($result->id->value->toString())->toBe($shop->id); + ->and($result?->id->value->toString())->toBe($shop->id); }); it('returns null if shop by id is not found', function () { diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php index d527e4e7..911d2d25 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php @@ -13,42 +13,9 @@ use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Schema; use Infrastructure\Adapters\Repositories\EloquentShopperRepository; use Ramsey\Uuid\Uuid; -beforeEach(function () { - if (! Schema::hasTable('customers')) { - Schema::create('customers', function (Blueprint $table) { - $table->uuid('id')->primary(); - $table->string('email'); - $table->string('hashcode')->nullable(); - $table->timestamps(); - }); - } - - if (! Schema::hasTable('employees')) { - Schema::create('employees', function (Blueprint $table) { - $table->id(); - $table->uuid('customer_id')->nullable(); - $table->string('matricule'); - $table->string('nom')->nullable(); - $table->string('prenom')->nullable(); - $table->date('start_date')->nullable(); - $table->date('end_date')->nullable(); - $table->string('etablissement')->nullable(); - $table->string('site')->nullable(); - $table->string('service')->nullable(); - $table->timestamps(); - }); - } - - DB::table('customers')->delete(); - DB::table('employees')->delete(); -}); - it('retrieves shopper by id', function () { // GIVEN $uuid = Uuid::uuid7()->toString(); @@ -77,7 +44,7 @@ it('retrieves shopper by id', function () { // THEN expect($result)->toBeInstanceOf(Shopper::class) - ->and($result->email->value)->toBe('test@example.com'); + ->and($result?->email->value)->toBe('test@example.com'); }); it('returns null if shopper not found by id', function () { diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeImportStorageServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeImportStorageServiceTest.php index ee8fa769..c419bbd3 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeImportStorageServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeImportStorageServiceTest.php @@ -12,28 +12,8 @@ use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; use Infrastructure\Adapters\Services\EloquentEmployeeImportStorageService; -beforeEach(function () { - if (! Schema::hasTable('employees')) { - Schema::create('employees', function (Blueprint $table) { - $table->id(); - $table->string('matricule')->unique(); - $table->string('nom')->nullable(); - $table->string('prenom')->nullable(); - $table->string('etablissement')->nullable(); - $table->string('service')->nullable(); - $table->string('site')->nullable(); - $table->string('start_date')->nullable(); - $table->string('end_date')->nullable(); - $table->timestamps(); - }); - } - Employee::query()->delete(); -}); - it('upserts a large batch of employees in chunks', function () { // GIVEN $upsertData = []; @@ -108,7 +88,10 @@ it('retrieves correct import statistics based on a start time', function () { $repo = new EloquentEmployeeImportStorageService(); // WHEN - $result = $repo->getImportedAfter(['1234567', '1234568', '1234569'], $importStartTime); + $result = $repo->getImportedAfter( + [new Matricule('1234567'), new Matricule('1234568'), new Matricule('1234569')], + $importStartTime, + ); // THEN expect($result->insertedCount)->toBe(1) diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php index 15e7cef1..3295b24e 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php @@ -2,41 +2,21 @@ declare(strict_types=1); +use App\Models\Shop; use Carbon\CarbonImmutable; use Domain\Enums\OrderStatus; use Domain\Models\ValueObjects\Matricule; -use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Schema; use Infrastructure\Adapters\Services\EloquentEmployeeStatisticsService; use Ramsey\Uuid\Uuid; -beforeEach(function () { - if (! Schema::hasTable('orders')) { - Schema::create('orders', function (Blueprint $table) { - $table->string('id')->primary(); - $table->unsignedBigInteger('shop_id'); - $table->string('reference'); - $table->json('employee'); - $table->json('delivery_address'); - $table->date('pickup_day'); - $table->string('status'); - $table->integer('total'); - $table->string('employee_matricule')->nullable(); - $table->timestamps(); - }); - } - - DB::table('orders')->delete(); -}); - it('retrieves the weekly order total for a given employee', function () { // GIVEN - DB::table('shops')->insertOrIgnore(['id' => 1, 'name' => 'Shop 1', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); + $shop = Shop::factory()->create(); DB::table('orders')->insert([ 'id' => '018e4567-e89b-72d3-a456-426614174000', - 'shop_id' => 1, + 'shop_id' => $shop->id, 'reference' => Uuid::uuid7()->toString(), 'employee' => json_encode([ 'matricule' => '1234567', @@ -66,10 +46,10 @@ it('retrieves the weekly order total for a given employee', function () { it('includes WAITING orders and excludes CANCELED orders in weekly total', function (): void { // GIVEN - DB::table('shops')->insertOrIgnore(['id' => 1, 'name' => 'Shop 1', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); + $shop = Shop::factory()->create(); $baseRow = [ - 'shop_id' => 1, + 'shop_id' => $shop->id, 'employee' => json_encode([ 'matricule' => '1234567', 'firstname' => 'Jean', From d1f0b21ad59f810b3c6a795e68e499b0e77207fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 11:39:52 +0100 Subject: [PATCH 111/183] refactor(EntityId): move UUID validation to EntityId constructor Refactored the EntityId class to include UUID v7 validation in the constructor, ensuring all derived classes inherit this behavior. --- domain/Models/ValueObjects/CrmCustomer.php | 18 +++++++++++++++++- .../Models/ValueObjects/Entities/BasketId.php | 9 --------- .../Models/ValueObjects/Entities/OrderId.php | 9 --------- .../Entities/PickupExceptionId.php | 9 --------- .../Models/ValueObjects/Entities/ProductId.php | 9 --------- domain/Models/ValueObjects/Entities/ShopId.php | 9 --------- .../Models/ValueObjects/Entities/ShopperId.php | 9 --------- shared/DDD/EntityId.php | 9 ++++++++- 8 files changed, 25 insertions(+), 56 deletions(-) diff --git a/domain/Models/ValueObjects/CrmCustomer.php b/domain/Models/ValueObjects/CrmCustomer.php index 3f733846..beb93a57 100644 --- a/domain/Models/ValueObjects/CrmCustomer.php +++ b/domain/Models/ValueObjects/CrmCustomer.php @@ -7,7 +7,23 @@ namespace Domain\Models\ValueObjects; use Domain\Enums\Country; /** - * @phpstan-type CrmCustomerArray array{hashcode: ?string, email: ?string, password: ?string, firstname: ?string, lastname: ?string, birthDate: ?string, phone: ?string, address: ?string, address2: ?string, city: ?string, postcode: ?string, country: \Domain\Enums\Country, optIn: bool, status: bool, lastConnection: ?\DateTimeInterface} + * @phpstan-type CrmCustomerArray array{ + * hashcode: ?string, + * email: ?string, + * password: ?string, + * firstname: ?string, + * lastname: ?string, + * birthDate: ?string, + * phone: ?string, + * address: ?string, + * address2: ?string, + * city: ?string, + * postcode: ?string, + * country: \Domain\Enums\Country, + * optIn: bool, + * status: bool, + * lastConnection: ?\DateTimeInterface + * } */ final readonly class CrmCustomer { diff --git a/domain/Models/ValueObjects/Entities/BasketId.php b/domain/Models/ValueObjects/Entities/BasketId.php index d7985e9a..f3b055ed 100644 --- a/domain/Models/ValueObjects/Entities/BasketId.php +++ b/domain/Models/ValueObjects/Entities/BasketId.php @@ -4,17 +4,8 @@ declare(strict_types=1); namespace Domain\Models\ValueObjects\Entities; -use Ramsey\Uuid\UuidInterface; use Shared\DDD\EntityId; -use Shared\Helpers\UuidHelper; final readonly class BasketId extends EntityId { - public function __construct( - public UuidInterface $value - ) { - if (! UuidHelper::isV7($value)) { - throw new \DomainException('value must be a valid UUID v7'); - } - } } diff --git a/domain/Models/ValueObjects/Entities/OrderId.php b/domain/Models/ValueObjects/Entities/OrderId.php index 8d48e7f1..df3fb621 100644 --- a/domain/Models/ValueObjects/Entities/OrderId.php +++ b/domain/Models/ValueObjects/Entities/OrderId.php @@ -4,17 +4,8 @@ declare(strict_types=1); namespace Domain\Models\ValueObjects\Entities; -use Ramsey\Uuid\UuidInterface; use Shared\DDD\EntityId; -use Shared\Helpers\UuidHelper; final readonly class OrderId extends EntityId { - public function __construct( - public UuidInterface $value - ) { - if (! UuidHelper::isV7($value)) { - throw new \DomainException('value shall be a valid UUID v7'); - } - } } diff --git a/domain/Models/ValueObjects/Entities/PickupExceptionId.php b/domain/Models/ValueObjects/Entities/PickupExceptionId.php index 7436cb21..cc95d23f 100644 --- a/domain/Models/ValueObjects/Entities/PickupExceptionId.php +++ b/domain/Models/ValueObjects/Entities/PickupExceptionId.php @@ -4,17 +4,8 @@ declare(strict_types=1); namespace Domain\Models\ValueObjects\Entities; -use Ramsey\Uuid\UuidInterface; use Shared\DDD\EntityId; -use Shared\Helpers\UuidHelper; final readonly class PickupExceptionId extends EntityId { - public function __construct( - public UuidInterface $value - ) { - if (! UuidHelper::isV7($value)) { - throw new \DomainException('value shall be a valid UUID v7'); - } - } } diff --git a/domain/Models/ValueObjects/Entities/ProductId.php b/domain/Models/ValueObjects/Entities/ProductId.php index 3eca58c4..869a2ada 100644 --- a/domain/Models/ValueObjects/Entities/ProductId.php +++ b/domain/Models/ValueObjects/Entities/ProductId.php @@ -4,17 +4,8 @@ declare(strict_types=1); namespace Domain\Models\ValueObjects\Entities; -use Ramsey\Uuid\UuidInterface; use Shared\DDD\EntityId; -use Shared\Helpers\UuidHelper; final readonly class ProductId extends EntityId { - public function __construct( - public UuidInterface $value - ) { - if (! UuidHelper::isV7($value)) { - throw new \DomainException('value shall be a valid UUID v7'); - } - } } diff --git a/domain/Models/ValueObjects/Entities/ShopId.php b/domain/Models/ValueObjects/Entities/ShopId.php index acf75d67..9339ae89 100644 --- a/domain/Models/ValueObjects/Entities/ShopId.php +++ b/domain/Models/ValueObjects/Entities/ShopId.php @@ -4,17 +4,8 @@ declare(strict_types=1); namespace Domain\Models\ValueObjects\Entities; -use Ramsey\Uuid\UuidInterface; use Shared\DDD\EntityId; -use Shared\Helpers\UuidHelper; final readonly class ShopId extends EntityId { - public function __construct( - public UuidInterface $value - ) { - if (! UuidHelper::isV7($value)) { - throw new \DomainException('value shall be a valid UUID v7'); - } - } } diff --git a/domain/Models/ValueObjects/Entities/ShopperId.php b/domain/Models/ValueObjects/Entities/ShopperId.php index 9cae704c..8e54a21a 100644 --- a/domain/Models/ValueObjects/Entities/ShopperId.php +++ b/domain/Models/ValueObjects/Entities/ShopperId.php @@ -4,17 +4,8 @@ declare(strict_types=1); namespace Domain\Models\ValueObjects\Entities; -use Ramsey\Uuid\UuidInterface; use Shared\DDD\EntityId; -use Shared\Helpers\UuidHelper; final readonly class ShopperId extends EntityId { - public function __construct( - public UuidInterface $value - ) { - if (! UuidHelper::isV7($value)) { - throw new \DomainException('value must be a valid UUID v7'); - } - } } diff --git a/shared/DDD/EntityId.php b/shared/DDD/EntityId.php index fbcb0d18..c90bcc04 100644 --- a/shared/DDD/EntityId.php +++ b/shared/DDD/EntityId.php @@ -5,10 +5,17 @@ declare(strict_types=1); namespace Shared\DDD; use Ramsey\Uuid\UuidInterface; +use Shared\Helpers\UuidHelper; abstract readonly class EntityId implements \Stringable, Equatable { - public readonly UuidInterface $value; + public function __construct( + public UuidInterface $value, + ) { + if (! UuidHelper::isV7($this->value)) { + throw new \DomainException('value must be a valid UUID v7'); + } + } #[\Override] public function __toString(): string From f658dd4b6479f825e368389ac26a408198e14517 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 11:40:10 +0100 Subject: [PATCH 112/183] refactor(tests): remove unused imports in test files Cleaned up test files by removing unnecessary imports to improve readability. --- .../Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php | 2 -- tests/Feature/Bo/Settings/SettingsControllerTest.php | 1 - 2 files changed, 3 deletions(-) diff --git a/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php index e918f8f2..71b7ddae 100644 --- a/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php @@ -2,10 +2,8 @@ declare(strict_types=1); -use App\Jobs\FetchAndUpsertArcadiaEmployees; use App\Models\User; use Domain\Enums\UserRole; -use Illuminate\Support\Facades\Queue; describe('EmployeesController', function () { beforeEach(function () { diff --git a/tests/Feature/Bo/Settings/SettingsControllerTest.php b/tests/Feature/Bo/Settings/SettingsControllerTest.php index 3c9b2fba..a8ee0c2b 100644 --- a/tests/Feature/Bo/Settings/SettingsControllerTest.php +++ b/tests/Feature/Bo/Settings/SettingsControllerTest.php @@ -2,7 +2,6 @@ declare(strict_types=1); -use App\Models\Setting; use App\Models\User; describe('SettingsController', function (): void { From d45022d8a400c2483a56d79fbc98c7585e7403ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 11:40:24 +0100 Subject: [PATCH 113/183] fix(SessionBasketRepository): handle corrupted session payload correctly Ensure that corrupted session data is ignored and null is returned, improving robustness. --- infra/Adapters/Repositories/SessionBasketRepository.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/infra/Adapters/Repositories/SessionBasketRepository.php b/infra/Adapters/Repositories/SessionBasketRepository.php index 4754abec..8dd18651 100644 --- a/infra/Adapters/Repositories/SessionBasketRepository.php +++ b/infra/Adapters/Repositories/SessionBasketRepository.php @@ -45,8 +45,9 @@ class SessionBasketRepository implements BasketRepository if (is_array($decoded)) { return $this->serializer->fromArray($decoded); } - } catch (\Throwable $e) { - // Ignore and fall back to null + } catch (\Throwable) { + // Ignore corrupted session payload and fall back to null + return null; } } } From cbb1ed812beef786a6902eda2fb507703b6d52f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 11:41:51 +0100 Subject: [PATCH 114/183] test(UpsertEmployeesFormFile): assert result is PendingCommand --- .../App/Console/Commands/UpsertEmployeesFormFileTest.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/Feature/App/Console/Commands/UpsertEmployeesFormFileTest.php b/tests/Feature/App/Console/Commands/UpsertEmployeesFormFileTest.php index e3c0b898..fea882cb 100644 --- a/tests/Feature/App/Console/Commands/UpsertEmployeesFormFileTest.php +++ b/tests/Feature/App/Console/Commands/UpsertEmployeesFormFileTest.php @@ -3,6 +3,8 @@ declare(strict_types=1); use Illuminate\Console\Command; +use Illuminate\Testing\PendingCommand; +use Webmozart\Assert\Assert; afterEach(function (): void { \Mockery::close(); @@ -19,8 +21,9 @@ describe('UpsertEmployeesFormFile command', function (): void { 'file' => $filePath, ]); + Assert::isInstanceOf($result, PendingCommand::class); + // THEN $result->assertExitCode(Command::FAILURE); }); - }); From ea06b37a47492e27bf4c915397413c19aa108314 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 11:44:31 +0100 Subject: [PATCH 115/183] refactor(BaseEnum): improve cache handling and type annotations Enhanced type annotations for cache variables and improved readability of the toLabels, toValues, and getCustomDefinitions methods. --- shared/Enums/BaseEnum.php | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/shared/Enums/BaseEnum.php b/shared/Enums/BaseEnum.php index 453796bc..61ad7172 100644 --- a/shared/Enums/BaseEnum.php +++ b/shared/Enums/BaseEnum.php @@ -36,12 +36,14 @@ trait BaseEnum */ public static function toLabels(): array { + /** @var array|null $cache */ static $cache = null; if ($cache !== null) { return $cache; } + /** @var array|null $labels */ $labels = defined(self::class . '::' . self::LABELS_CONSTANT_NAME) ? constant(self::class . '::' . self::LABELS_CONSTANT_NAME) : null; @@ -62,17 +64,21 @@ trait BaseEnum */ public static function toValues(): array { + /** @var array|null $cache */ static $cache = null; if ($cache !== null) { return $cache; } - return $cache = array_column( + /** @var array $values */ + $values = array_column( self::cases(), 'value', 'name' ); + + return $cache = $values; } /** @@ -136,13 +142,15 @@ trait BaseEnum */ private static function getCustomDefinitions(): array { + /** @var array>|null $cache */ static $cache = null; if ($cache !== null) { return $cache; } - $names = array_column(self::cases(), 'name', 'name'); + $names = array_column(self::cases(), 'name', 'name'); + /** @var array> $filteredConstants */ $filteredConstants = []; foreach ((new \ReflectionClass(self::class))->getConstants() as $key => $constant) { @@ -151,6 +159,7 @@ trait BaseEnum } if (! empty(array_intersect_key($constant, $names))) { + /** @var array $constant */ $filteredConstants[$key] = $constant; } } From 50cef3b0cf0d0aac4482c72f666cefcb27c5a87b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 11:49:32 +0100 Subject: [PATCH 116/183] chore(dependencies): add phpstan-mockery for improved testing This addition enhances the testing capabilities by integrating the PHPStan Mockery extension. --- composer.json | 1 + composer.lock | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 5db772a4..5e691fec 100644 --- a/composer.json +++ b/composer.json @@ -49,6 +49,7 @@ "pestphp/pest-plugin-laravel": "^4.0", "pestphp/pest-plugin-type-coverage": "^4.0", "php-parallel-lint/php-parallel-lint": "^1.4", + "phpstan/phpstan-mockery": "^2.0", "phpunit/phpunit": "^12.5", "slevomat/coding-standard": "^8.30", "spatie/laravel-ignition": "^2.0" diff --git a/composer.lock b/composer.lock index e1df036f..fb6a68c9 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "307a7c2e8f85c8f50ed609d5fdb475ff", + "content-hash": "5a27a0a2588a9b83fa85e242925d5128", "packages": [ { "name": "aws/aws-crt-php", @@ -15153,6 +15153,56 @@ ], "time": "2026-11-03T12:14:22+00:00" }, + { + "name": "phpstan/phpstan-mockery", + "version": "2.0.0", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan-mockery.git", + "reference": "89a949d0ac64298e88b7c7fa00caee565c198394" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan-mockery/zipball/89a949d0ac64298e88b7c7fa00caee565c198394", + "reference": "89a949d0ac64298e88b7c7fa00caee565c198394", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0", + "phpstan/phpstan": "^2.0" + }, + "require-dev": { + "mockery/mockery": "^1.6.11", + "php-parallel-lint/php-parallel-lint": "^1.2", + "phpstan/phpstan-phpunit": "^2.0", + "phpstan/phpstan-strict-rules": "^2.0", + "phpunit/phpunit": "^9.6" + }, + "type": "phpstan-extension", + "extra": { + "phpstan": { + "includes": [ + "extension.neon" + ] + } + }, + "autoload": { + "psr-4": { + "PHPStan\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan Mockery extension", + "support": { + "issues": "https://github.com/phpstan/phpstan-mockery/issues", + "source": "https://github.com/phpstan/phpstan-mockery/tree/2.0.0" + }, + "time": "2024-10-14T03:18:12+00:00", + "published-time": "2024-11-11T07:42:39+00:00" + }, { "name": "phpunit/php-code-coverage", "version": "12.5.8", From 8a3d6a815612a17750bc79916b1c4273a0c20d37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 12:36:26 +0100 Subject: [PATCH 117/183] chore(phpstan): add phpstan-mockery extension for testing This addition enhances the testing capabilities by integrating phpstan-mockery. --- phpstan.neon | 1 + 1 file changed, 1 insertion(+) diff --git a/phpstan.neon b/phpstan.neon index fc32c1bd..4674f530 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -2,6 +2,7 @@ includes: - vendor/larastan/larastan/extension.neon - vendor/nesbot/carbon/extension.neon - vendor/pestphp/pest/phpstan-pest-extension.neon + - vendor/phpstan/phpstan-mockery/extension.neon parameters: paths: From 875d6dd01df64e346647cce1e2adfe05b755af1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 12:39:21 +0100 Subject: [PATCH 118/183] test(tests): apply step 1 hygiene, clock reset, and explicit Arcadia policy skips --- .../Bo/EmployeesControllerTest.php | 51 +++++++------ .../Bo/Employees/EmployeeSyncFeatureTest.php | 7 -- .../Bo/Settings/SettingsControllerTest.php | 71 ++++++++++++------- .../App/Services/IcsGeneratorServiceTest.php | 10 ++- .../Unit/Domain/Exceptions/ExceptionsTest.php | 3 +- .../Services/OrderTunnelServiceTest.php | 17 +++-- .../Services/ImageOptimizerServiceTest.php | 22 +++--- 7 files changed, 103 insertions(+), 78 deletions(-) diff --git a/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php index 71b7ddae..5d2c248f 100644 --- a/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php @@ -2,39 +2,48 @@ declare(strict_types=1); +use App\Jobs\FetchAndUpsertArcadiaEmployees; use App\Models\User; use Domain\Enums\UserRole; +use Illuminate\Support\Facades\Queue; -describe('EmployeesController', function () { - beforeEach(function () { +use function Pest\Laravel\actingAs; +use function Pest\Laravel\post; + +describe('EmployeesController', function (): void { + beforeEach(function (): void { // GIVEN - /** @var \Tests\TestCase $this */ - $user = User::factory()->create(['role' => UserRole::SuperAdmin]); - $this->actingAs($user, 'backend'); + $user = User::factory()->createOne(['role' => UserRole::SuperAdmin]); + actingAs($user, 'backend'); }); - // FIXME: The Arcadia refresh action is inhibited, uncomment this test when api acrcadia is up. - // it('can launch employee sync job', function () { - // // GIVEN - // /** @var \Tests\TestCase $this */ - // Queue::fake(); + it('forbids launching employee sync job while EmployeePolicy is disabled', function (): void { + // WHEN + $response = post('/bo/settings/employees/sync'); - // // WHEN - // $response = $this->post('/bo/settings/employees/sync'); + // THEN + $response->assertForbidden(); + }); - // // THEN - // $response->assertSessionHasNoErrors(); - // $response->assertRedirect(route('bo.dashboard')); - // Queue::assertPushed(FetchAndUpsertArcadiaEmployees::class); - // }); - - it('redirects unauthenticated users to login', function () { + it('can launch employee sync job', function (): void { + // GIVEN + Queue::fake(); + + // WHEN + $response = post('/bo/settings/employees/sync'); + + // THEN + $response->assertSessionHasNoErrors(); + $response->assertRedirect(route('bo.dashboard')); + Queue::assertPushed(FetchAndUpsertArcadiaEmployees::class); + })->skip('Arcadia API is offline; SettingPolicy and EmployeePolicy currently return false.'); + + it('redirects unauthenticated users to login', function (): void { // GIVEN - /** @var \Tests\TestCase $this */ auth()->guard('backend')->logout(); // WHEN - $response = $this->post('/bo/settings/employees/sync'); + $response = post('/bo/settings/employees/sync'); // THEN $response->assertRedirect('/bo/login'); diff --git a/tests/Feature/Bo/Employees/EmployeeSyncFeatureTest.php b/tests/Feature/Bo/Employees/EmployeeSyncFeatureTest.php index f5c519c1..3ed28e33 100644 --- a/tests/Feature/Bo/Employees/EmployeeSyncFeatureTest.php +++ b/tests/Feature/Bo/Employees/EmployeeSyncFeatureTest.php @@ -16,15 +16,8 @@ use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Contracts\Cache\Repository as CacheRepository; -use Illuminate\Foundation\Testing\RefreshDatabase; use Psr\Log\NullLogger; -uses(RefreshDatabase::class); - -afterEach(function (): void { - \Mockery::close(); -}); - describe('Employee Sync Feature E2E', function (): void { it('configures sites in back office and synchronizes employees from Arcadia API into database', function (): void { /** @var \Tests\TestCase $this */ diff --git a/tests/Feature/Bo/Settings/SettingsControllerTest.php b/tests/Feature/Bo/Settings/SettingsControllerTest.php index a8ee0c2b..f049d8a8 100644 --- a/tests/Feature/Bo/Settings/SettingsControllerTest.php +++ b/tests/Feature/Bo/Settings/SettingsControllerTest.php @@ -2,27 +2,25 @@ declare(strict_types=1); +use App\Models\Setting; use App\Models\User; +use function Pest\Laravel\actingAs; + describe('SettingsController', function (): void { - it('displays the employee sites edit form to an admin', function (): void { - /** @var \Tests\TestCase $this */ + it('forbids accessing the employee sites edit form while SettingPolicy is disabled', function (): void { // GIVEN $user = User::factory()->createOne(); $route = route('bo.settings.edit'); // WHEN - $response = $this->actingAs($user, 'backend')->get($route); + $response = actingAs($user, 'backend')->get($route); // THEN $response->assertForbidden(); - // $response->assertOk() - // ->assertViewIs('bo.settings.edit') - // ->assertViewHas('setting'); }); - it('updates employee sites with array input and redirects', function (): void { - /** @var \Tests\TestCase $this */ + it('forbids updating employee sites while SettingPolicy is disabled', function (): void { // GIVEN $user = User::factory()->createOne(); $route = route('bo.settings.update'); @@ -31,19 +29,46 @@ describe('SettingsController', function (): void { ]; // WHEN - $response = $this->actingAs($user, 'backend')->put($route, $formData); + $response = actingAs($user, 'backend')->put($route, $formData); // THEN $response->assertForbidden(); - // $response->assertRedirect(route('bo.settings.edit')) - // ->assertSessionHas('success'); - - // $setting = Setting::getSingleton(); - // expect($setting->employee_sites)->toBe(['PA', 'LY', 'NA']); }); + it('displays the employee sites edit form to an admin', function (): void { + // GIVEN + $user = User::factory()->createOne(); + $route = route('bo.settings.edit'); + + // WHEN + $response = actingAs($user, 'backend')->get($route); + + // THEN + $response->assertOk() + ->assertViewIs('bo.settings.edit') + ->assertViewHas('setting'); + })->skip('Arcadia API is offline; SettingPolicy and EmployeePolicy currently return false.'); + + it('updates employee sites with array input and redirects', function (): void { + // GIVEN + $user = User::factory()->createOne(); + $route = route('bo.settings.update'); + $formData = [ + 'employee_sites' => ['PA', 'LY', 'NA'], + ]; + + // WHEN + $response = actingAs($user, 'backend')->put($route, $formData); + + // THEN + $response->assertRedirect(route('bo.settings.edit')) + ->assertSessionHas('success'); + + $setting = Setting::getSingleton(); + expect($setting->employee_sites)->toBe(['PA', 'LY', 'NA']); + })->skip('Arcadia API is offline; SettingPolicy and EmployeePolicy currently return false.'); + it('updates employee sites with comma string input and redirects', function (): void { - /** @var \Tests\TestCase $this */ // GIVEN $user = User::factory()->createOne(); $route = route('bo.settings.update'); @@ -52,19 +77,17 @@ describe('SettingsController', function (): void { ]; // WHEN - $response = $this->actingAs($user, 'backend')->put($route, $formData); + $response = actingAs($user, 'backend')->put($route, $formData); // THEN - $response->assertForbidden(); - // $response->assertRedirect(route('bo.settings.edit')) - // ->assertSessionHas('success'); + $response->assertRedirect(route('bo.settings.edit')) + ->assertSessionHas('success'); - // $setting = Setting::getSingleton(); - // expect($setting->employee_sites)->toBe(['PA', 'LY', 'NA']); - }); + $setting = Setting::getSingleton(); + expect($setting->employee_sites)->toBe(['PA', 'LY', 'NA']); + })->skip('Arcadia API is offline; SettingPolicy and EmployeePolicy currently return false.'); it('rejects invalid site code formats', function (): void { - /** @var \Tests\TestCase $this */ // GIVEN $user = User::factory()->createOne(); $route = route('bo.settings.update'); @@ -73,7 +96,7 @@ describe('SettingsController', function (): void { ]; // WHEN - $response = $this->actingAs($user, 'backend')->put($route, $formData); + $response = actingAs($user, 'backend')->put($route, $formData); // THEN $response->assertSessionHasErrors(['employee_sites.1', 'employee_sites.2']); diff --git a/tests/Unit/App/Services/IcsGeneratorServiceTest.php b/tests/Unit/App/Services/IcsGeneratorServiceTest.php index 8e542884..448f6820 100644 --- a/tests/Unit/App/Services/IcsGeneratorServiceTest.php +++ b/tests/Unit/App/Services/IcsGeneratorServiceTest.php @@ -4,11 +4,17 @@ declare(strict_types=1); use App\Dto\IcsContentDto; use App\Services\IcsGeneratorService; +use Carbon\CarbonImmutable; use Domain\Models\ValueObjects\IcsContent; use Illuminate\Support\Carbon; covers(IcsGeneratorService::class); +afterEach(function (): void { + Carbon::setTestNow(); + CarbonImmutable::setTestNow(); +}); + describe('IcsGeneratorService', function (): void { it('throws exception if app name is empty', function (): void { // GIVEN @@ -49,9 +55,7 @@ describe('IcsGeneratorService', function (): void { ->toContain('DTEND:20260611T110000Z') ->toContain('SUMMARY:My Event\, with comma') ->toContain('DESCRIPTION:Line 1\nLine 2\;') - ->not->toContain('URL:'); - - Carbon::setTestNow(); + ->and($ics->value)->not->toContain('URL:'); }); it('generates ics format with url', function (): void { diff --git a/tests/Unit/Domain/Exceptions/ExceptionsTest.php b/tests/Unit/Domain/Exceptions/ExceptionsTest.php index 473e549e..86278bd7 100644 --- a/tests/Unit/Domain/Exceptions/ExceptionsTest.php +++ b/tests/Unit/Domain/Exceptions/ExceptionsTest.php @@ -9,7 +9,6 @@ use Domain\Exceptions\OrderTunnel\MissingOrderBuilderException; use Domain\Exceptions\OrderTunnel\OrderLimitExceededException; use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException; use Domain\Exceptions\UnknownCountryIsoCodeException; -use RuntimeException; describe('Exceptions', function () { it('creates MissingOrderBuilderException correctly', function () { @@ -27,7 +26,7 @@ describe('Exceptions', function () { // GIVEN $message = 'Custom error'; $code = 123; - $previous = new RuntimeException('Prev'); + $previous = new \RuntimeException('Prev'); // WHEN $e = new MissingOrderBuilderException($message, $code, $previous); diff --git a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php index da9864e7..2d37c881 100644 --- a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php +++ b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php @@ -6,7 +6,6 @@ namespace Tests\Unit\Domain\Services; use Carbon\CarbonImmutable; use Carbon\WeekDay; -use DateInterval; use Domain\Builders\OrderBuilder; use Domain\Builders\OrderBuilderCompleted; use Domain\Builders\OrderBuilderWithBasket; @@ -101,7 +100,7 @@ function createTestBuilder(bool $completed = false): OrderBuilderWithBasket if ($completed) { $shopId = new ShopId(Uuid::uuid7()); $nextFriday = CarbonImmutable::now('Europe/Paris')->next(WeekDay::Friday->value)->addWeek()->startOfDay(); - $timeSlot = new PickupTimeSlot($nextFriday, new DateInterval('PT1H')); + $timeSlot = new PickupTimeSlot($nextFriday, new \DateInterval('PT1H')); return $builder->withPickupTimeSlot($shopId, $timeSlot); } @@ -272,7 +271,7 @@ describe('OrderTunnelService', function (): void { // GIVEN $shopId = new ShopId(Uuid::uuid7()); $nextFriday = CarbonImmutable::now('Europe/Paris')->next(WeekDay::Friday->value)->addWeek()->startOfDay(); - $timeSlot = new PickupTimeSlot($nextFriday, new DateInterval('PT1H')); + $timeSlot = new PickupTimeSlot($nextFriday, new \DateInterval('PT1H')); $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(Uuid::uuid7()))->withPickupTimeSlot($shopId, $timeSlot); $orderBuilderRepository = mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn($builder); @@ -474,7 +473,7 @@ describe('OrderTunnelService', function (): void { // GIVEN $shopId = new ShopId(Uuid::uuid7()); $nextFriday = CarbonImmutable::now('Europe/Paris')->next(WeekDay::Friday->value)->addWeek()->startOfDay(); - $timeSlot = new PickupTimeSlot($nextFriday, new DateInterval('PT1H')); + $timeSlot = new PickupTimeSlot($nextFriday, new \DateInterval('PT1H')); $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(Uuid::uuid7()))->withPickupTimeSlot($shopId, $timeSlot); $orderBuilderRepo = mock(OrderBuilderSessionManager::class); @@ -494,8 +493,8 @@ describe('OrderTunnelService', function (): void { $builder = createTestBuilder(completed: false); $shop = new Shop(new ShopId(Uuid::uuid7()), 'Shop', 'Address', '75000', 'Paris'); $selectedDate = CarbonImmutable::create(2025, 1, 1); - $ts1 = new PickupTimeSlot($selectedDate, new DateInterval('PT1H')); - $ts2 = new PickupTimeSlot(CarbonImmutable::create(2025, 1, 2), new DateInterval('PT1H')); + $ts1 = new PickupTimeSlot($selectedDate, new \DateInterval('PT1H')); + $ts2 = new PickupTimeSlot(CarbonImmutable::create(2025, 1, 2), new \DateInterval('PT1H')); $availableSlots = [$ts1, $ts2]; $orderBuilderRepo = mock(OrderBuilderSessionManager::class); @@ -515,7 +514,7 @@ describe('OrderTunnelService', function (): void { $builder = createTestBuilder(completed: false); $shop = new Shop(new ShopId(Uuid::uuid7()), 'Shop', 'Address', '75000', 'Paris'); $selectedDate = CarbonImmutable::create(2025, 1, 1); - $ts1 = new PickupTimeSlot(CarbonImmutable::create(2025, 1, 2), new DateInterval('PT1H')); + $ts1 = new PickupTimeSlot(CarbonImmutable::create(2025, 1, 2), new \DateInterval('PT1H')); $availableSlots = [$ts1]; $service = createOrderTunnelService(); @@ -747,7 +746,7 @@ describe('OrderTunnelService', function (): void { $basket = createTestBasket(1); $shopperId = new ShopperId(Uuid::uuid7()); $shopId = new ShopId(Uuid::uuid7()); - $expiredSlot = new PickupTimeSlot(CarbonImmutable::create(2025, 1, 1), new DateInterval('PT1H')); + $expiredSlot = new PickupTimeSlot(CarbonImmutable::create(2025, 1, 1), new \DateInterval('PT1H')); $builder = OrderBuilder::fromBasket($basket, $shopperId)->withPickupTimeSlot($shopId, $expiredSlot); $shopper = new Shopper( @@ -984,7 +983,7 @@ describe('OrderTunnelService', function (): void { new OrderId(Uuid::uuid7()), new OrderReference(Uuid::uuid7()), $basket, - new PickupTimeSlot(CarbonImmutable::now()->next('Friday'), new DateInterval('PT1H')), + new PickupTimeSlot(CarbonImmutable::now()->next('Friday'), new \DateInterval('PT1H')), $shopper, $shop ); diff --git a/tests/Unit/Services/ImageOptimizerServiceTest.php b/tests/Unit/Services/ImageOptimizerServiceTest.php index e2ef6751..dc94c9d9 100644 --- a/tests/Unit/Services/ImageOptimizerServiceTest.php +++ b/tests/Unit/Services/ImageOptimizerServiceTest.php @@ -10,18 +10,15 @@ use Shared\Filesystem\TemporaryFileFactory; covers(ImageOptimizerService::class); describe('ImageOptimizerService', function (): void { - $service = \Mockery::mock(ImageOptimizerService::class); + $makeService = static fn (): ImageOptimizerService => new ImageOptimizerService( + new TemporaryFileFactory(), + new NullLogger(), + ); - beforeEach(function () use (&$service) { - $service = new ImageOptimizerService( - new TemporaryFileFactory(), - new NullLogger(), - ); - }); - - it('creates a real temp file for optimized images with the original extension', function () use (&$service): void { + it('creates a real temp file for optimized images with the original extension', function () use ($makeService): void { // GIVEN - $file = UploadedFile::fake()->image('picture.jpg', 800, 600); + $service = $makeService(); + $file = UploadedFile::fake()->image('picture.jpg', 800, 600); // WHEN $optimized = $service->optimize($file, quality: 70); @@ -37,9 +34,10 @@ describe('ImageOptimizerService', function (): void { ->and($content)->toBeString(); }); - it('creates a real temp file for non-image uploads with a readable path', function () use (&$service): void { + it('creates a real temp file for non-image uploads with a readable path', function () use ($makeService): void { // GIVEN - $pdf = UploadedFile::fake()->create('document.pdf', 250, 'application/pdf'); + $service = $makeService(); + $pdf = UploadedFile::fake()->create('document.pdf', 250, 'application/pdf'); // WHEN $result = $service->optimize($pdf); From 80d3478dbe133390ac6ce4dbb6f925ce764cf780 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 12:46:06 +0100 Subject: [PATCH 119/183] test(tests): merge unique assertions and remove strict duplicate test files (lot 2A) --- .../Controllers/Bo/SlidesControllerTest.php | 7 +- .../Controllers/Bo/TagsControllerTest.php | 16 +- tests/Feature/Bo/Slides/CrudSlideTest.php | 114 ------------- tests/Feature/Bo/Tags/CrudTagTest.php | 126 -------------- .../App/Casts/OrderLineProductCastTest.php | 7 +- .../Casts/OrderLineProductCastTest.php | 157 ------------------ .../App/Services/IcsGeneratorServiceTest.php | 29 ++++ .../LaravelDomainEventDispatcherTest.php | 27 --- .../LaravelTransactionManagerTest.php | 29 ---- .../Unit/Services/IcsGeneratorServiceTest.php | 45 ----- 10 files changed, 53 insertions(+), 504 deletions(-) delete mode 100644 tests/Feature/Bo/Slides/CrudSlideTest.php delete mode 100644 tests/Feature/Bo/Tags/CrudTagTest.php delete mode 100644 tests/Integration/WithApp/Casts/OrderLineProductCastTest.php delete mode 100644 tests/Unit/Infra/Adapters/Events/LaravelDomainEventDispatcherTest.php delete mode 100644 tests/Unit/Infra/Adapters/Services/LaravelTransactionManagerTest.php delete mode 100644 tests/Unit/Services/IcsGeneratorServiceTest.php diff --git a/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php index 3d416b74..9e53cdf5 100644 --- a/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php @@ -140,7 +140,12 @@ describe('SlidesController', function (): void { $response = $this->from('/bo/slides')->patch("/bo/slides/{$slide2->id}/up"); // THEN - expect($response->status())->toBe(302); + $slide1->refresh(); + $slide2->refresh(); + + expect($response->status())->toBe(302) + ->and($slide1->order)->toBe(2) + ->and($slide2->order)->toBe(1); $response->assertRedirect('/bo/slides'); }); }); diff --git a/tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php index 2e71e3dc..bac7574e 100644 --- a/tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php @@ -6,6 +6,8 @@ use App\Models\Tag; use App\Models\User; use Domain\Enums\UserRole; +use function Pest\Laravel\from; + describe('TagsController', function (): void { beforeEach(function (): void { /** @var \Tests\TestCase $this */ @@ -113,14 +115,20 @@ describe('TagsController', function (): void { }); it('can change order', function (): void { - /** @var \Tests\TestCase $this */ // GIVEN - $tag = Tag::factory()->create(); + $tag1 = Tag::factory()->createOne(['order' => 1]); + $tag2 = Tag::factory()->createOne(['order' => 2]); // WHEN - $response = $this->patch("/bo/tags/{$tag->id}/up"); + $response = from('/bo/tags')->patch("/bo/tags/{$tag1->id}/down"); // THEN - expect($response->status())->toBe(302); + $tag1->refresh(); + $tag2->refresh(); + + expect($response->status())->toBe(302) + ->and($tag1->order)->toBe(2) + ->and($tag2->order)->toBe(1); + $response->assertRedirect('/bo/tags'); }); }); diff --git a/tests/Feature/Bo/Slides/CrudSlideTest.php b/tests/Feature/Bo/Slides/CrudSlideTest.php deleted file mode 100644 index d63d8c49..00000000 --- a/tests/Feature/Bo/Slides/CrudSlideTest.php +++ /dev/null @@ -1,114 +0,0 @@ -withoutExceptionHandling(); - // GIVEN - $htmlDateInputFormat = 'Y-m-d\TH:i'; - $user = User::factory()->createOne(); - $route = route('bo.slides.store'); - $formData = [ - 'title' => '1rst Slide', - 'text' => 'Super slide content', - 'date_start' => Date::now()->format($htmlDateInputFormat), - 'date_end' => Date::now()->addDay()->format($htmlDateInputFormat), - 'client_timezone' => 'Europe/Paris', - ]; - - // WHEN - $reponse = $this->actingAs($user, 'backend')->post($route, $formData); - - // THEN - $reponse->assertRedirect( - route( - 'bo.slides.edit', - Slide::query()->latest()->firstOrFail() - ) - ); - }); - - it('Can edit a slide', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - $user = User::factory()->createOne(); - $slide = Slide::factory()->createOne(); - $route = route('bo.slides.edit', $slide); - - // WHEN - $reponse = $this->actingAs($user, 'backend')->get($route); - - // THEN - $reponse->assertOk(); - }); - - it('Can update a slide', function (): void { - /** @var \Tests\TestCase $this */ - $this->withoutExceptionHandling(); - // GIVEN - $user = User::factory()->createOne(); - $slide = Slide::factory()->createOne(); - $route = route('bo.slides.update', $slide); - $formData = [ - 'title' => 'Update Slide', - 'text' => 'Super slide content updated', - 'date_start' => Date::now()->format('Y-m-d\TH:i'), - 'date_end' => Date::now()->addDay()->format('Y-m-d\TH:i'), - 'client_timezone' => 'Europe/Paris', - ]; - - // WHEN - $reponse = $this->actingAs($user, 'backend')->put($route, $formData); - - // THEN - $reponse->assertRedirect( - route('bo.slides.edit', $slide) - ); - }); - - it('Can delete a slide', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - $user = User::factory()->createOne(); - $slide = Slide::factory()->createOne(); - $route = route('bo.slides.destroy', $slide); - - // WHEN - $reponse = $this->actingAs($user, 'backend')->delete($route); - - // THEN - $reponse->assertRedirect(route('bo.slides.index')); - }); - - it('Can update a slide order', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - $user = User::factory()->createOne(); - $slide = Slide::factory()->createOne(); - $slide2 = Slide::factory()->createOne(); - $route = route('bo.slides.change-order', [$slide, 'down']); - $fromRoute = route('bo.slides.index'); - - $slideOrder = $slide->order; - $slide2Order = $slide2->order; - - // WHEN - $this->actingAs($user, 'backend')->get($fromRoute); // * First Navigation - $reponse = $this->actingAs($user, 'backend')->patch($route); - - $slide->refresh(); - $slide2->refresh(); - - // THEN - $reponse->assertRedirect($fromRoute); - expect($slideOrder)->toBe($slide2->order); - expect($slide2Order)->toBe($slide->order); - }); -}); diff --git a/tests/Feature/Bo/Tags/CrudTagTest.php b/tests/Feature/Bo/Tags/CrudTagTest.php deleted file mode 100644 index fea4e100..00000000 --- a/tests/Feature/Bo/Tags/CrudTagTest.php +++ /dev/null @@ -1,126 +0,0 @@ -withoutExceptionHandling(); - // GIVEN - $user = User::factory()->createOne(); - $route = route('bo.tags.store'); - $formData = [ - 'label' => '1rst Tag', - 'status' => true, - ]; - - // WHEN - $reponse = $this->actingAs($user, 'backend')->post($route, $formData); - - // THEN - $reponse->assertRedirect( - route( - 'bo.tags.edit', - Tag::query()->latest('order')->firstOrFail() - ) - ); - }); - - it('Can edit a tag', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - $user = User::factory()->createOne(); - $tag = Tag::factory()->createOne(); - $route = route('bo.tags.edit', $tag); - - // WHEN - $reponse = $this->actingAs($user, 'backend')->get($route); - - // THEN - $reponse->assertOk(); - }); - - it('Can update a tag', function (): void { - /** @var \Tests\TestCase $this */ - $this->withoutExceptionHandling(); - // GIVEN - $user = User::factory()->createOne(); - $tag = Tag::factory()->createOne(); - $route = route('bo.tags.update', $tag); - $formData = [ - 'label' => 'Update Tag', - 'status' => false, - ]; - - // WHEN - $reponse = $this->actingAs($user, 'backend')->put($route, $formData); - - // THEN - $reponse->assertRedirect( - route('bo.tags.edit', $tag) - ); - }); - - it('Can delete a tag', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - $user = User::factory()->createOne(); - $tag = Tag::factory()->createOne(); - $route = route('bo.tags.destroy', $tag); - - // WHEN - $reponse = $this->actingAs($user, 'backend')->delete($route); - - // THEN - $reponse->assertRedirect(route('bo.tags.index')); - }); - - it('Can update a tag order', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - $user = User::factory()->createOne(); - $tag = Tag::factory()->createOne(); - $tag2 = Tag::factory()->createOne(); - $route = route('bo.tags.change-order', [$tag, 'down']); - $fromRoute = route('bo.tags.index'); - - $tagOrder = $tag->order; - $tag2Order = $tag2->order; - - // WHEN - $this->actingAs($user, 'backend')->get($fromRoute); // * First Navigation - $reponse = $this->actingAs($user, 'backend')->patch($route); - - $tag->refresh(); - $tag2->refresh(); - - // THEN - $reponse->assertRedirect($fromRoute); - expect($tagOrder)->toBe($tag2->order); - expect($tag2Order)->toBe($tag->order); - }); - - it('Can toggle a tag status', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - $user = User::factory()->createOne(); - $tag = Tag::factory()->createOne(); - $route = route('bo.tags.toggle-status', $tag); - $fromRoute = route('bo.tags.index'); - $tagStatus = $tag->status; - - // WHEN - $this->actingAs($user, 'backend')->get($fromRoute); // * First Navigation - $reponse = $this->actingAs($user, 'backend')->patch($route); - - $tag->refresh(); - - // THEN - $reponse->assertRedirect($fromRoute); - expect($tagStatus)->toBe(! $tag->status); - }); -}); diff --git a/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php b/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php index 2f4eece1..1757c4c3 100644 --- a/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php +++ b/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php @@ -11,6 +11,7 @@ use Domain\Models\ValueObjects\IncoId; use Domain\Models\ValueObjects\OrderLineProduct; use Domain\Models\ValueObjects\ProductWeight; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Arr; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; @@ -148,6 +149,10 @@ describe('OrderLineProductCast', function () { // THEN expect($value)->toBeJson() - ->and($data['picture'])->toBe('pic.jpg'); + ->and($data)->toBeArray() + ->toHaveKey('weight', 1000) + ->toHaveKey('weight_variable', false) + ->and($data)->not->toHaveKey('weight_unit') + ->and(Arr::get($data, 'picture'))->toBe('pic.jpg'); }); }); diff --git a/tests/Integration/WithApp/Casts/OrderLineProductCastTest.php b/tests/Integration/WithApp/Casts/OrderLineProductCastTest.php deleted file mode 100644 index 1a5a3eb1..00000000 --- a/tests/Integration/WithApp/Casts/OrderLineProductCastTest.php +++ /dev/null @@ -1,157 +0,0 @@ - 123456, - 'original_id' => Uuid::uuid7()->toString(), - 'name' => 'Poulet Fermier', - 'weight' => 1500, - 'weight_variable' => true, - 'brand' => ProductBrand::loue->value, - 'order_unit' => OrderUnit::PCE->value, - 'price' => 1050, - 'discounted_price' => 950, - 'price_kg_ttc' => 700, - 'tax_rate' => TaxRate::TVA_5_5->percent(), - 'picture' => 'poulet.jpg', - ]); - - // WHEN - $vo = $cast->get($model, 'product', $json, []); - - // THEN - expect($vo)->toBeInstanceOf(OrderLineProduct::class) - ->and($vo->incoId->value)->toBe(123456) - ->and($vo->name)->toBe('Poulet Fermier') - ->and($vo->weight->value)->toBe(1500) - ->and($vo->weight->isVariable)->toBeTrue() - ->and($vo->brand)->toBe(ProductBrand::loue) - ->and($vo->orderUnit)->toBe(OrderUnit::PCE) - ->and($vo->taxRate)->toBe(TaxRate::TVA_5_5) - ->and($vo->picture)->toBeInstanceOf(StorageFilePath::class) - ->and($vo->picture->value)->toBe('poulet.jpg'); - }); - - it('can cast JSON to OrderLineProduct with TVA 20% and null picture correctly', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = new class () extends Model - { - }; - - $json = json_encode([ - 'inco_id' => 123456, - 'original_id' => Uuid::uuid7()->toString(), - 'name' => 'Produit TVA 20', - 'weight' => 500, - 'weight_variable' => false, - 'brand' => ProductBrand::loue->value, - 'order_unit' => OrderUnit::PCE->value, - 'price' => 1050, - 'discounted_price' => 950, - 'price_kg_ttc' => 700, - 'tax_rate' => TaxRate::TVA_20->percent(), // json_encode encodes 20.0 as 20 - 'picture' => null, - ]); - - // WHEN - $vo = $cast->get($model, 'product', $json, []); - - // THEN - expect($vo)->toBeInstanceOf(OrderLineProduct::class) - ->and($vo->taxRate)->toBe(TaxRate::TVA_20) - ->and($vo->picture)->toBeNull(); - }); - - it('can set OrderLineProduct to JSON correctly', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = new class () extends Model - { - }; - - $vo = new OrderLineProduct( - incoId: new IncoId(123456), - originalId: new ProductId(Uuid::uuid7()), - name: 'Poulet Fermier', - weight: new ProductWeight(1500, true), - brand: ProductBrand::loue, - orderUnit: OrderUnit::PCE, - price: new Money(1050, new Currency('EUR')), - discountedPrice: new Money(950, new Currency('EUR')), - priceKgTtc: new Money(700, new Currency('EUR')), - taxRate: TaxRate::TVA_5_5, - picture: new StorageFilePath('poulet.jpg') - ); - - // WHEN - $json = $cast->set($model, 'product', $vo, []); - $data = json_decode($json, true); - - // THEN - expect($data) - ->toBeArray() - ->toHaveKey('weight', 1500) - ->toHaveKey('weight_variable', true) - ->not->toHaveKey('weight_unit'); - }); - - it('throws exception if value is null on get', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = new class () extends Model - { - }; - - // WHEN / THEN - $cast->get($model, 'product', null, []); - })->throws(\InvalidArgumentException::class); - - it('throws exception if value is not string on get', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = new class () extends Model - { - }; - - // WHEN / THEN - $cast->get($model, 'product', ['array' => 'invalid'], []); - })->throws(\InvalidArgumentException::class); - - it('throws exception if value is not an OrderLineProduct on set', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = new class () extends Model - { - }; - - // WHEN / THEN - $cast->set($model, 'product', 'not a VO', []); - })->throws(\InvalidArgumentException::class); -}); diff --git a/tests/Unit/App/Services/IcsGeneratorServiceTest.php b/tests/Unit/App/Services/IcsGeneratorServiceTest.php index 448f6820..2ce42ed0 100644 --- a/tests/Unit/App/Services/IcsGeneratorServiceTest.php +++ b/tests/Unit/App/Services/IcsGeneratorServiceTest.php @@ -77,4 +77,33 @@ describe('IcsGeneratorService', function (): void { expect($ics)->toBeInstanceOf(IcsContent::class) ->and($ics->value)->toContain('URL:http://example.com'); }); + + it('converts Europe/Paris winter timestamps to UTC correctly', function (): void { + // GIVEN + $service = new IcsGeneratorService('La Boutique de Cocotte'); + CarbonImmutable::setTestNow(CarbonImmutable::parse('2024-01-01 10:00:00', 'UTC')); + + $dto = new IcsContentDto( + uid: 'test-uid@laboutiquedecocotte.fr', + summary: 'Test Event', + description: 'Winter timezone check', + startsAt: CarbonImmutable::parse('2024-01-01 12:00:00', 'Europe/Paris'), + endsAt: CarbonImmutable::parse('2024-01-01 12:15:00', 'Europe/Paris'), + url: 'https://laboutiquedecocotte.fr', + ); + + // WHEN + $ics = $service->generate($dto); + + // THEN + // 12:00 Europe/Paris in winter (UTC+1) is 11:00 UTC + expect($ics)->toBeInstanceOf(IcsContent::class) + ->and($ics->value)->toContain('VERSION:2.0') + ->toContain('BEGIN:VEVENT') + ->toContain('DTSTAMP:20240101T100000Z') + ->toContain('DTSTART:20240101T110000Z') + ->toContain('DTEND:20240101T111500Z') + ->toContain('END:VEVENT') + ->toContain('END:VCALENDAR'); + }); }); diff --git a/tests/Unit/Infra/Adapters/Events/LaravelDomainEventDispatcherTest.php b/tests/Unit/Infra/Adapters/Events/LaravelDomainEventDispatcherTest.php deleted file mode 100644 index c5c39d29..00000000 --- a/tests/Unit/Infra/Adapters/Events/LaravelDomainEventDispatcherTest.php +++ /dev/null @@ -1,27 +0,0 @@ -dispatch($event); - - // THEN - Event::assertDispatched(get_class($event)); - }); -}); diff --git a/tests/Unit/Infra/Adapters/Services/LaravelTransactionManagerTest.php b/tests/Unit/Infra/Adapters/Services/LaravelTransactionManagerTest.php deleted file mode 100644 index 6f2d055b..00000000 --- a/tests/Unit/Infra/Adapters/Services/LaravelTransactionManagerTest.php +++ /dev/null @@ -1,29 +0,0 @@ - $expectedResult; - - DB::shouldReceive('transaction') - ->once() - ->andReturnUsing(function ($closure) { - return $closure(); - }); - - // WHEN - $result = $manager->execute($callback); - - // THEN - expect($result)->toBe($expectedResult); - }); -}); diff --git a/tests/Unit/Services/IcsGeneratorServiceTest.php b/tests/Unit/Services/IcsGeneratorServiceTest.php deleted file mode 100644 index f9eecca0..00000000 --- a/tests/Unit/Services/IcsGeneratorServiceTest.php +++ /dev/null @@ -1,45 +0,0 @@ -generate($event); - - // THEN - expect($ics)->toBeInstanceOf(IcsContent::class) - ->and($ics->value)->toContain('BEGIN:VCALENDAR') - ->toContain('VERSION:2.0') - ->toContain('PRODID:-//La Boutique de Cocotte//NONSGML v1.0//EN') - ->toContain('BEGIN:VEVENT') - ->toContain('UID:test-uid@laboutiquedecocotte.fr') - ->toContain('DTSTAMP:20240101T100000Z') - // 12:00 Europe/Paris in winter is 11:00 UTC - ->toContain('DTSTART:20240101T110000Z') - ->toContain('DTEND:20240101T111500Z') - ->toContain('SUMMARY:Test Event') - ->toContain('DESCRIPTION:This is a test description with a comma\, and a newline\n') - ->toContain('URL:https://laboutiquedecocotte.fr') - ->toContain('END:VEVENT') - ->toContain('END:VCALENDAR'); -}); From 712d42ed96e4f96d156760c22ac9c8f48293059b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 12:47:36 +0100 Subject: [PATCH 120/183] test(tests): remove generic enum, exception string, and invariant-free input tests (lot 2B) --- .../Common/ChangeModelOrderInputTest.php | 31 ------- .../Common/ToggleModelStarInputTest.php | 29 ------- .../Common/ToggleModelStatusInputTest.php | 29 ------- .../Discounts/DeleteDiscountInputTest.php | 21 ----- .../App/Actions/Faqs/DeleteFaqInputTest.php | 19 ----- .../Orders/ApplyPickTimeSlotInputTest.php | 26 ------ .../Orders/InitializeOrderTunnelInputTest.php | 27 ------ .../Orders/PlacePendingOrderInputTest.php | 28 ------ .../DeletePickupExceptionInputTest.php | 21 ----- .../Actions/Ranges/DeleteRangeInputTest.php | 19 ----- .../App/Actions/Shops/DeleteShopInputTest.php | 19 ----- .../Actions/Slides/DeleteSlideInputTest.php | 19 ----- .../App/Actions/Tags/DeleteTagInputTest.php | 19 ----- .../Queries/Shops/GetShopQueryInputTest.php | 20 ----- tests/Unit/Domain/Enums/GeneralEnumTest.php | 55 ------------ .../Unit/Domain/Exceptions/ExceptionsTest.php | 85 ------------------- 16 files changed, 467 deletions(-) delete mode 100644 tests/Unit/App/Actions/Common/ChangeModelOrderInputTest.php delete mode 100644 tests/Unit/App/Actions/Common/ToggleModelStarInputTest.php delete mode 100644 tests/Unit/App/Actions/Common/ToggleModelStatusInputTest.php delete mode 100644 tests/Unit/App/Actions/Discounts/DeleteDiscountInputTest.php delete mode 100644 tests/Unit/App/Actions/Faqs/DeleteFaqInputTest.php delete mode 100644 tests/Unit/App/Actions/Orders/ApplyPickTimeSlotInputTest.php delete mode 100644 tests/Unit/App/Actions/Orders/InitializeOrderTunnelInputTest.php delete mode 100644 tests/Unit/App/Actions/Orders/PlacePendingOrderInputTest.php delete mode 100644 tests/Unit/App/Actions/PickupExceptions/DeletePickupExceptionInputTest.php delete mode 100644 tests/Unit/App/Actions/Ranges/DeleteRangeInputTest.php delete mode 100644 tests/Unit/App/Actions/Shops/DeleteShopInputTest.php delete mode 100644 tests/Unit/App/Actions/Slides/DeleteSlideInputTest.php delete mode 100644 tests/Unit/App/Actions/Tags/DeleteTagInputTest.php delete mode 100644 tests/Unit/App/Queries/Shops/GetShopQueryInputTest.php delete mode 100644 tests/Unit/Domain/Enums/GeneralEnumTest.php delete mode 100644 tests/Unit/Domain/Exceptions/ExceptionsTest.php diff --git a/tests/Unit/App/Actions/Common/ChangeModelOrderInputTest.php b/tests/Unit/App/Actions/Common/ChangeModelOrderInputTest.php deleted file mode 100644 index 2e32b182..00000000 --- a/tests/Unit/App/Actions/Common/ChangeModelOrderInputTest.php +++ /dev/null @@ -1,31 +0,0 @@ -model)->toBe($mock) - ->and($input->direction)->toBe(\SortDirection::Ascending); - }); -}); diff --git a/tests/Unit/App/Actions/Common/ToggleModelStarInputTest.php b/tests/Unit/App/Actions/Common/ToggleModelStarInputTest.php deleted file mode 100644 index 9b30791f..00000000 --- a/tests/Unit/App/Actions/Common/ToggleModelStarInputTest.php +++ /dev/null @@ -1,29 +0,0 @@ -model)->toBe($mock); - }); -}); diff --git a/tests/Unit/App/Actions/Common/ToggleModelStatusInputTest.php b/tests/Unit/App/Actions/Common/ToggleModelStatusInputTest.php deleted file mode 100644 index 171e57ec..00000000 --- a/tests/Unit/App/Actions/Common/ToggleModelStatusInputTest.php +++ /dev/null @@ -1,29 +0,0 @@ -model)->toBe($mock); - }); -}); diff --git a/tests/Unit/App/Actions/Discounts/DeleteDiscountInputTest.php b/tests/Unit/App/Actions/Discounts/DeleteDiscountInputTest.php deleted file mode 100644 index d51fb269..00000000 --- a/tests/Unit/App/Actions/Discounts/DeleteDiscountInputTest.php +++ /dev/null @@ -1,21 +0,0 @@ -discount)->toBe($discount); - }); -}); diff --git a/tests/Unit/App/Actions/Faqs/DeleteFaqInputTest.php b/tests/Unit/App/Actions/Faqs/DeleteFaqInputTest.php deleted file mode 100644 index ae7ba13d..00000000 --- a/tests/Unit/App/Actions/Faqs/DeleteFaqInputTest.php +++ /dev/null @@ -1,19 +0,0 @@ -faq)->toBe($faq); - }); -}); diff --git a/tests/Unit/App/Actions/Orders/ApplyPickTimeSlotInputTest.php b/tests/Unit/App/Actions/Orders/ApplyPickTimeSlotInputTest.php deleted file mode 100644 index deaebdae..00000000 --- a/tests/Unit/App/Actions/Orders/ApplyPickTimeSlotInputTest.php +++ /dev/null @@ -1,26 +0,0 @@ -shopperId)->toBe($shopperId) - ->and($input->timeslot)->toBe($timeslot); - }); -}); diff --git a/tests/Unit/App/Actions/Orders/InitializeOrderTunnelInputTest.php b/tests/Unit/App/Actions/Orders/InitializeOrderTunnelInputTest.php deleted file mode 100644 index 0b415706..00000000 --- a/tests/Unit/App/Actions/Orders/InitializeOrderTunnelInputTest.php +++ /dev/null @@ -1,27 +0,0 @@ -basket)->toBe($basket) - ->and($input->shopperId)->toBe($shopperId); - }); -}); diff --git a/tests/Unit/App/Actions/Orders/PlacePendingOrderInputTest.php b/tests/Unit/App/Actions/Orders/PlacePendingOrderInputTest.php deleted file mode 100644 index 5b8f417e..00000000 --- a/tests/Unit/App/Actions/Orders/PlacePendingOrderInputTest.php +++ /dev/null @@ -1,28 +0,0 @@ -shopperId)->toBeNull(); - }); - - it('can be instantiated with valid shopperId', function (): void { - // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); - - // WHEN - $input = new PlacePendingOrderInput(shopperId: $shopperId); - - // THEN - expect($input->shopperId)->toBe($shopperId); - }); -}); diff --git a/tests/Unit/App/Actions/PickupExceptions/DeletePickupExceptionInputTest.php b/tests/Unit/App/Actions/PickupExceptions/DeletePickupExceptionInputTest.php deleted file mode 100644 index 13d66b94..00000000 --- a/tests/Unit/App/Actions/PickupExceptions/DeletePickupExceptionInputTest.php +++ /dev/null @@ -1,21 +0,0 @@ -pickupException)->toBe($pickupException); - }); -}); diff --git a/tests/Unit/App/Actions/Ranges/DeleteRangeInputTest.php b/tests/Unit/App/Actions/Ranges/DeleteRangeInputTest.php deleted file mode 100644 index 28a5ca6e..00000000 --- a/tests/Unit/App/Actions/Ranges/DeleteRangeInputTest.php +++ /dev/null @@ -1,19 +0,0 @@ -range)->toBe($range); - }); -}); diff --git a/tests/Unit/App/Actions/Shops/DeleteShopInputTest.php b/tests/Unit/App/Actions/Shops/DeleteShopInputTest.php deleted file mode 100644 index 3762173b..00000000 --- a/tests/Unit/App/Actions/Shops/DeleteShopInputTest.php +++ /dev/null @@ -1,19 +0,0 @@ -shop)->toBe($shop); - }); -}); diff --git a/tests/Unit/App/Actions/Slides/DeleteSlideInputTest.php b/tests/Unit/App/Actions/Slides/DeleteSlideInputTest.php deleted file mode 100644 index 93f0688b..00000000 --- a/tests/Unit/App/Actions/Slides/DeleteSlideInputTest.php +++ /dev/null @@ -1,19 +0,0 @@ -slide)->toBe($slide); - }); -}); diff --git a/tests/Unit/App/Actions/Tags/DeleteTagInputTest.php b/tests/Unit/App/Actions/Tags/DeleteTagInputTest.php deleted file mode 100644 index 63af0ae5..00000000 --- a/tests/Unit/App/Actions/Tags/DeleteTagInputTest.php +++ /dev/null @@ -1,19 +0,0 @@ -tag)->toBe($tag); - }); -}); diff --git a/tests/Unit/App/Queries/Shops/GetShopQueryInputTest.php b/tests/Unit/App/Queries/Shops/GetShopQueryInputTest.php deleted file mode 100644 index 891339f0..00000000 --- a/tests/Unit/App/Queries/Shops/GetShopQueryInputTest.php +++ /dev/null @@ -1,20 +0,0 @@ -toBeInstanceOf(GetShopQueryInput::class); - }); -}); diff --git a/tests/Unit/Domain/Enums/GeneralEnumTest.php b/tests/Unit/Domain/Enums/GeneralEnumTest.php deleted file mode 100644 index 67523bcf..00000000 --- a/tests/Unit/Domain/Enums/GeneralEnumTest.php +++ /dev/null @@ -1,55 +0,0 @@ -toBeArray(); - } else { - expect(true)->toBeTrue(); - } - })->with([ - DiscountType::class, - EmployeeSite::class, - Nutriscore::class, - OrderStatus::class, - OrderTunnelStep::class, - ItemsPerPaginationEnum::class, - PriceShowingMode::class, - ProductBrand::class, - RepeatFrequency::class, - SellUnit::class, - StaticPageSlug::class, - StatsCustomerType::class, - StatsShopType::class, - InvoicingUnit::class, - OrderUnit::class, - ]); -}); diff --git a/tests/Unit/Domain/Exceptions/ExceptionsTest.php b/tests/Unit/Domain/Exceptions/ExceptionsTest.php deleted file mode 100644 index 86278bd7..00000000 --- a/tests/Unit/Domain/Exceptions/ExceptionsTest.php +++ /dev/null @@ -1,85 +0,0 @@ -getMessage())->toBe($expectedMessage); - }); - - it('creates MissingOrderBuilderException with custom args', function () { - // GIVEN - $message = 'Custom error'; - $code = 123; - $previous = new \RuntimeException('Prev'); - - // WHEN - $e = new MissingOrderBuilderException($message, $code, $previous); - - // THEN - expect($e->getMessage())->toBe($message) - ->and($e->getCode())->toBe($code) - ->and($e->getPrevious())->toBe($previous); - }); - - it('creates OrderLimitExceededException correctly', function () { - // GIVEN - $expectedMessage = 'The total amount of this order has been exceeded. Please modify it to validate.'; - - // WHEN - $e = new OrderLimitExceededException(); - - // THEN - expect($e->getMessage())->toBe($expectedMessage); - }); - - it('creates WeeklyLimitExceededException correctly', function () { - // GIVEN - $expectedMessage = 'The total amount for this delivery date has been exceeded. Please modify it to validate.'; - - // WHEN - $e = new WeeklyLimitExceededException(); - - // THEN - expect($e->getMessage())->toBe($expectedMessage); - }); - - it('creates UnknownCountryIsoCodeException from iso code', function () { - // GIVEN - $isoCode = 'ZZ'; - $expectedMessage = "No country found for ISO code 'ZZ'"; - - // WHEN - $e = UnknownCountryIsoCodeException::fromIsoCode($isoCode); - - // THEN - expect($e->getMessage())->toBe($expectedMessage); - }); - - it('creates UnknownCountryIsoCodeException from country', function () { - // GIVEN - $country = Country::france; - $expectedMessage = "No ISO code found for country 'france'"; - - // WHEN - $e = UnknownCountryIsoCodeException::fromCountry($country); - - // THEN - expect($e->getMessage())->toBe($expectedMessage); - }); -}); From 4c8280d9321a9a8ad5d57ae621213cef44eba102 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 12:50:19 +0100 Subject: [PATCH 121/183] test(tests): prune constructor-only DTO tests and consolidate contracts (lot 2C) --- .../WithApp/App/Dto/OrderLineDtoTest.php | 23 +++- .../App/Dto/PickupExceptionDtoTest.php | 11 +- .../WithApp/App/Dto/RangeDtoTest.php | 14 ++- .../WithApp/App/Dto/ShopDtoTest.php | 14 ++- .../WithApp/App/Dto/SlideDtoTest.php | 28 ++++- tests/Unit/App/Dto/DiscountDtoTest.php | 8 +- tests/Unit/App/Dto/DiscountProductDtoTest.php | 12 +-- tests/Unit/App/Dto/IcsContentDtoTest.php | 52 --------- tests/Unit/App/Dto/OrderLineDtoTest.php | 101 ------------------ tests/Unit/App/Dto/OrderReminderDtoTest.php | 55 ---------- .../Unit/App/Dto/OrderReminderLineDtoTest.php | 29 ----- tests/Unit/App/Dto/PickupExceptionDtoTest.php | 47 -------- tests/Unit/App/Dto/ProductDtoTest.php | 71 ++++++------ tests/Unit/App/Dto/ProductIncoDtoTest.php | 21 +--- tests/Unit/App/Dto/RangeDtoTest.php | 43 -------- tests/Unit/App/Dto/SettingDtoTest.php | 4 +- tests/Unit/App/Dto/ShopDtoTest.php | 37 +------ tests/Unit/App/Dto/SlideDtoTest.php | 71 ------------ 18 files changed, 132 insertions(+), 509 deletions(-) delete mode 100644 tests/Unit/App/Dto/IcsContentDtoTest.php delete mode 100644 tests/Unit/App/Dto/OrderLineDtoTest.php delete mode 100644 tests/Unit/App/Dto/OrderReminderDtoTest.php delete mode 100644 tests/Unit/App/Dto/OrderReminderLineDtoTest.php delete mode 100644 tests/Unit/App/Dto/PickupExceptionDtoTest.php delete mode 100644 tests/Unit/App/Dto/RangeDtoTest.php delete mode 100644 tests/Unit/App/Dto/SlideDtoTest.php diff --git a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php index acfae274..92235e70 100644 --- a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php @@ -92,6 +92,27 @@ describe('OrderLineDto Integration', function (): void { ->and($dto->unitPriceTtc)->toEqual(Money::EUR(2077)) ->and($dto->total_ht)->toEqual(Money::EUR(3938)) ->and($dto->total_tax)->toEqual(Money::EUR(216)) - ->and($dto->total_ttc)->toEqual(Money::EUR(4154)); + ->and($dto->total_ttc)->toEqual(Money::EUR(4154)) + ->and($dto->toArray())->toBe([ + 'id' => (int) $line->id, + 'order_id' => (string) $line->order_id, + 'product_name' => 'Terrine de Foie Gras de Canard mi-cuit 500g', + 'product_inco_id' => '999', + 'product_brand_label' => ProductBrand::loue->label(), + 'is_variable_weight' => false, + 'price_kg_ttc' => '3938', + 'quantity' => 2, + 'unit_price' => '1969', + 'unit_tax' => '108', + 'unit_discount' => '0', + 'tax_rate' => TaxRate::TVA_5_5->value, + 'unit_price_ttc' => '2077', + 'unit_price_discounted_ht' => '1969', + 'total_ttc' => '4154', + 'total_ht' => '3938', + 'total_tax' => '216', + 'total_discount' => '0', + 'total_gross_ht' => '3938', + ]); }); }); diff --git a/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php b/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php index 8024198f..feb10552 100644 --- a/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php @@ -18,9 +18,18 @@ describe('PickupExceptionDto Integration', function () { $dto = PickupExceptionDto::fromModel($exception); // THEN + $array = $dto->toArray(); + expect($dto->id)->toBe($exception->id) ->and($dto->label)->toBe($exception->label) - ->and($dto->pivot)->toBeNull(); + ->and($dto->pivot)->toBeNull() + ->and($dto->getRouteKey())->toBe($exception->id) + ->and($dto->getRouteKeyName())->toBe('id') + ->and($dto->resolveRouteBinding('some-id'))->toBeNull() + ->and($dto->resolveChildRouteBinding('child', 'some-id', 'field'))->toBeNull() + ->and($array)->toHaveKey('id', $exception->id) + ->and($array)->toHaveKey('label', $exception->label) + ->and($array)->toHaveKey('repeat_frequency', $exception->repeat_frequency->value); }); test('fromModel works with pivot loaded from shop relationship', function () { diff --git a/tests/Integration/WithApp/App/Dto/RangeDtoTest.php b/tests/Integration/WithApp/App/Dto/RangeDtoTest.php index 472735f5..615cb889 100644 --- a/tests/Integration/WithApp/App/Dto/RangeDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/RangeDtoTest.php @@ -31,6 +31,18 @@ describe('RangeDto Integration', function () { ->and($dto->picture_title)->toBe('Titre image bio') ->and($dto->status)->toBeTrue() ->and($dto->order)->toBe($range->order) - ->and($dto->getRouteKey())->toBe($range->slug); + ->and($dto->getRouteKey())->toBe($range->slug) + ->and($dto->getRouteKeyName())->toBe('slug') + ->and($dto->toArray())->toBe([ + 'id' => $range->id, + 'name' => 'Gamme Bio', + 'slug' => $range->slug, + 'description' => 'Description de la gamme bio', + 'picture' => null, + 'picture_alt' => 'Image gamme bio', + 'picture_title' => 'Titre image bio', + 'order' => $range->order, + 'status' => true, + ]); }); }); diff --git a/tests/Integration/WithApp/App/Dto/ShopDtoTest.php b/tests/Integration/WithApp/App/Dto/ShopDtoTest.php index e5577b3c..49938fff 100644 --- a/tests/Integration/WithApp/App/Dto/ShopDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/ShopDtoTest.php @@ -32,7 +32,19 @@ describe('ShopDto Integration', function () { ->and($dto->city)->toBe('Lyon') ->and($dto->phone)->toBe('+33472000000') ->and($dto->default)->toBeTrue() - ->and($dto->getRouteKey())->toBe($shop->id); + ->and($dto->getRouteKey())->toBe($shop->id) + ->and($dto->getRouteKeyName())->toBe('id') + ->and($dto->toArray())->toBe([ + 'id' => $shop->id, + 'name' => 'Boutique Centre', + 'address' => '10 rue Centrale', + 'postcode' => '69002', + 'city' => 'Lyon', + 'phone' => '+33472000000', + 'latitude' => null, + 'longitude' => null, + 'default' => true, + ]); }); test('it maps loaded pickupExceptions relation correctly', function () { diff --git a/tests/Integration/WithApp/App/Dto/SlideDtoTest.php b/tests/Integration/WithApp/App/Dto/SlideDtoTest.php index 6f6a7eb5..90aa15ab 100644 --- a/tests/Integration/WithApp/App/Dto/SlideDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/SlideDtoTest.php @@ -10,11 +10,16 @@ use Illuminate\Support\Facades\Storage; describe('SlideDto integration', function (): void { beforeEach(function (): void { + Carbon::setTestNow('2026-11-01 12:00:00'); config(['filesystems.disks.s3.url' => 'https://cdn.test']); Storage::forgetDisk(['s3', 's3-public']); app()->forgetInstance(PublicS3Disk::class); }); + afterEach(function (): void { + Carbon::setTestNow(); + }); + it('creates a DTO from Slide model with booted application and resolves public S3 URL', function (): void { // GIVEN $dateStart = Carbon::parse('2026-06-01 10:00:00'); @@ -54,7 +59,28 @@ describe('SlideDto integration', function (): void { ->and($dto->date_end)->toEqual($dateEnd) ->and($dto->order)->toBe(3) ->and($dto->status)->toBeTrue() - ->and($dto->isVisible())->toBeFalse(); + ->and($dto->isVisible())->toBeFalse() + ->and($dto->getRouteKey())->toBe(42) + ->and($dto->getRouteKeyName())->toBe('id') + ->and($dto->resolveRouteBinding(42))->toBeNull() + ->and($dto->resolveChildRouteBinding('child', 'val', 'field'))->toBeNull() + ->and($dto->toArray())->toEqual([ + 'id' => 42, + 'title' => 'Bannière Été', + 'text' => '

Découvrez notre nouvelle collection

', + 'picture' => 'https://cdn.test/public/storage/modelfiles/slides/26/06/01/ab/summer.jpg', + 'picture_alt' => 'Collection Été', + 'picture_title' => 'Bannière promotionnelle été', + 'link' => 'https://example.com/ete', + 'link_label' => 'Voir les offres', + 'link_new_tab' => true, + 'connected' => false, + 'date_start' => $dateStart, + 'date_end' => $dateEnd, + 'order' => 3, + 'status' => true, + 'is_visible' => false, + ]); }); it('creates a DTO from Slide model when picture is null', function (): void { diff --git a/tests/Unit/App/Dto/DiscountDtoTest.php b/tests/Unit/App/Dto/DiscountDtoTest.php index 7a41406f..58c2a106 100644 --- a/tests/Unit/App/Dto/DiscountDtoTest.php +++ b/tests/Unit/App/Dto/DiscountDtoTest.php @@ -27,13 +27,7 @@ describe('DiscountDto', function (): void { ); // THEN - expect($dto->id)->toBe(42) - ->and($dto->type)->toBe(DiscountType::PERCENT) - ->and($dto->value)->toBe($value) - ->and($dto->is_old_price_displayed)->toBeTrue() - ->and($dto->date_start)->toEqual($dateStart) - ->and($dto->date_end)->toEqual($dateEnd) - ->and($dto->getRouteKey())->toBe(42) + expect($dto->getRouteKey())->toBe(42) ->and($dto->getRouteKeyName())->toBe('id') ->and($dto->resolveRouteBinding(42))->toBeNull() ->and($dto->resolveChildRouteBinding('child', 'val', 'field'))->toBeNull() diff --git a/tests/Unit/App/Dto/DiscountProductDtoTest.php b/tests/Unit/App/Dto/DiscountProductDtoTest.php index 130f410b..31d98461 100644 --- a/tests/Unit/App/Dto/DiscountProductDtoTest.php +++ b/tests/Unit/App/Dto/DiscountProductDtoTest.php @@ -21,13 +21,11 @@ describe('DiscountProductDto', function (): void { ); // THEN - expect($dto->id)->toBe($id) - ->and($dto->name)->toBe($name) - ->and($dto->toArray())->toBe([ - 'id' => $id, - 'name' => $name, - 'picture' => $picture, - ]) + expect($dto->toArray())->toBe([ + 'id' => $id, + 'name' => $name, + 'picture' => $picture, + ]) ->and($dto->jsonSerialize())->toBe([ 'id' => $id, 'name' => $name, diff --git a/tests/Unit/App/Dto/IcsContentDtoTest.php b/tests/Unit/App/Dto/IcsContentDtoTest.php deleted file mode 100644 index b4090dc4..00000000 --- a/tests/Unit/App/Dto/IcsContentDtoTest.php +++ /dev/null @@ -1,52 +0,0 @@ -uid)->toBe('uid-123') - ->and($dto->summary)->toBe('My Event') - ->and($dto->description)->toBe('Event Description') - ->and($dto->startsAt)->toBe($startsAt) - ->and($dto->endsAt)->toBe($endsAt) - ->and($dto->url)->toBe('https://example.com'); - }); - - it('can be instantiated without optional url property', function (): void { - // GIVEN - $startsAt = CarbonImmutable::parse('2024-01-01 10:00:00'); - $endsAt = CarbonImmutable::parse('2024-01-01 12:00:00'); - - // WHEN - $dto = new IcsContentDto( - uid: 'uid-456', - summary: 'My Event 2', - description: 'Event Description 2', - startsAt: $startsAt, - endsAt: $endsAt, - ); - - // THEN - expect($dto->url)->toBeNull(); - }); -}); diff --git a/tests/Unit/App/Dto/OrderLineDtoTest.php b/tests/Unit/App/Dto/OrderLineDtoTest.php deleted file mode 100644 index a7a908fc..00000000 --- a/tests/Unit/App/Dto/OrderLineDtoTest.php +++ /dev/null @@ -1,101 +0,0 @@ -id)->toBe($id) - ->and($dto->order_id)->toBe($orderId) - ->and($dto->product_name)->toBe($productName) - ->and($dto->product_inco_id)->toBe($productIncoId) - ->and($dto->product_brand_label)->toBe($productBrandLabel) - ->and($dto->is_variable_weight)->toBe($isVariableWeight) - ->and($dto->price_kg_ttc)->toBe($priceKgTtc) - ->and($dto->quantity)->toBe($quantity) - ->and($dto->unit_price)->toBe($unitPrice) - ->and($dto->unit_tax)->toBe($unitTax) - ->and($dto->unit_discount)->toBe($unitDiscount) - ->and($dto->tax_rate)->toBe($taxRate) - ->and($dto->unit_price_ttc)->toBe($unitPriceTtc) - ->and($dto->unitPriceTtc)->toBe($unitPriceTtc) - ->and($dto->unit_price_discounted_ht)->toBe($unitPriceDiscountedHt) - ->and($dto->unitPriceDiscountedHt)->toBe($unitPriceDiscountedHt) - ->and($dto->total_gross_ht)->toBe($totalGrossHt) - ->and($dto->totalGrossHt)->toBe($totalGrossHt) - ->and($dto->total_ht)->toBe($totalHt) - ->and($dto->total_tax)->toBe($totalTax) - ->and($dto->total_discount)->toBe($totalDiscount) - ->and($dto->total_ttc)->toBe($totalTtc); - - expect($dto->toArray())->toBe([ - 'id' => $id, - 'order_id' => $orderId, - 'product_name' => $productName, - 'product_inco_id' => $productIncoId, - 'product_brand_label' => $productBrandLabel, - 'is_variable_weight' => $isVariableWeight, - 'price_kg_ttc' => '3938', - 'quantity' => $quantity, - 'unit_price' => '1969', - 'unit_tax' => '108', - 'unit_discount' => '0', - 'tax_rate' => $taxRate->value, - 'unit_price_ttc' => '2077', - 'unit_price_discounted_ht' => '1969', - 'total_ttc' => '4154', - 'total_ht' => '3938', - 'total_tax' => '216', - 'total_discount' => '0', - 'total_gross_ht' => '3938', - ]); - }); -}); diff --git a/tests/Unit/App/Dto/OrderReminderDtoTest.php b/tests/Unit/App/Dto/OrderReminderDtoTest.php deleted file mode 100644 index 818714e0..00000000 --- a/tests/Unit/App/Dto/OrderReminderDtoTest.php +++ /dev/null @@ -1,55 +0,0 @@ -firstname)->toBe($firstname) - ->and($dto->lastname)->toBe($lastname) - ->and($dto->reference)->toBe($reference) - ->and($dto->total)->toBe($total) - ->and($dto->pickupDayFormatted)->toBe($pickupDayFormatted) - ->and($dto->lines)->toBe($lines) - ->and($dto->shopName)->toBe($shopName) - ->and($dto->shopAddress)->toBe($shopAddress) - ->and($dto->shopPostcode)->toBe($shopPostcode) - ->and($dto->shopCity)->toBe($shopCity); - }); -}); diff --git a/tests/Unit/App/Dto/OrderReminderLineDtoTest.php b/tests/Unit/App/Dto/OrderReminderLineDtoTest.php deleted file mode 100644 index becbd5fb..00000000 --- a/tests/Unit/App/Dto/OrderReminderLineDtoTest.php +++ /dev/null @@ -1,29 +0,0 @@ -name)->toBe($name) - ->and($dto->quantity)->toBe($quantity) - ->and($dto->priceKgTtc)->toBe($priceKgTtc) - ->and($dto->totalTtc)->toBe($totalTtc); - }); -}); diff --git a/tests/Unit/App/Dto/PickupExceptionDtoTest.php b/tests/Unit/App/Dto/PickupExceptionDtoTest.php deleted file mode 100644 index 7e211f76..00000000 --- a/tests/Unit/App/Dto/PickupExceptionDtoTest.php +++ /dev/null @@ -1,47 +0,0 @@ -id)->toBe('018f6c40-1234-7123-8123-123456789012') - ->and($dto->label)->toBe('1er Mai') - ->and($dto->repeatable)->toBeTrue() - ->and($dto->repeat_frequency)->toBe(RepeatFrequency::YEARLY) - ->and($dto->auto_updated)->toBeFalse() - ->and($dto->pivot)->not->toBeNull() - ->and($dto->getRouteKey())->toBe('018f6c40-1234-7123-8123-123456789012') - ->and($dto->getRouteKeyName())->toBe('id') - ->and($dto->resolveRouteBinding('some-id'))->toBeNull() - ->and($dto->resolveChildRouteBinding('child', 'some-id', 'field'))->toBeNull(); - - $array = $dto->toArray(); - expect($array)->toHaveKey('id', '018f6c40-1234-7123-8123-123456789012') - ->and($array)->toHaveKey('label', '1er Mai') - ->and($array)->toHaveKey('repeat_frequency', RepeatFrequency::YEARLY->value); - }); -}); diff --git a/tests/Unit/App/Dto/ProductDtoTest.php b/tests/Unit/App/Dto/ProductDtoTest.php index b97b3356..547e3884 100644 --- a/tests/Unit/App/Dto/ProductDtoTest.php +++ b/tests/Unit/App/Dto/ProductDtoTest.php @@ -19,45 +19,40 @@ describe('ProductDto', function () { ); // THEN - expect($dto->id)->toBe($id) - ->and($dto->name)->toBe($name) - ->and($dto->slug)->toBe($slug) - ->and($dto->getRouteKey())->toBe($slug) + expect($dto->getRouteKey())->toBe($slug) ->and($dto->getRouteKeyName())->toBe('slug') ->and($dto->resolveRouteBinding('some-id'))->toBeNull() - ->and($dto->resolveChildRouteBinding('child', 'some-id', 'field'))->toBeNull(); - - $array = $dto->toArray(); - expect($array)->toBe([ - 'id' => $id, - 'name' => $name, - 'slug' => $slug, - 'brand' => null, - 'inco' => null, - 'picture' => null, - 'picture_alt' => null, - 'picture_title' => null, - 'picture_large' => null, - 'picture_large_alt' => null, - 'picture_large_title' => null, - 'price' => null, - 'discount' => null, - 'tax_rate' => null, - 'invoicing_unit' => null, - 'stock' => 0, - 'sell_unit' => null, - 'order_unit' => null, - 'range' => null, - 'tags' => [], - 'order' => 0, - 'product_weight' => null, - 'weight_variable' => false, - 'status' => false, - 'star' => false, - 'orderable_start' => null, - 'orderable_end' => null, - 'short_description' => null, - 'description' => null, - ]); + ->and($dto->resolveChildRouteBinding('child', 'some-id', 'field'))->toBeNull() + ->and($dto->toArray())->toBe([ + 'id' => $id, + 'name' => $name, + 'slug' => $slug, + 'brand' => null, + 'inco' => null, + 'picture' => null, + 'picture_alt' => null, + 'picture_title' => null, + 'picture_large' => null, + 'picture_large_alt' => null, + 'picture_large_title' => null, + 'price' => null, + 'discount' => null, + 'tax_rate' => null, + 'invoicing_unit' => null, + 'stock' => 0, + 'sell_unit' => null, + 'order_unit' => null, + 'range' => null, + 'tags' => [], + 'order' => 0, + 'product_weight' => null, + 'weight_variable' => false, + 'status' => false, + 'star' => false, + 'orderable_start' => null, + 'orderable_end' => null, + 'short_description' => null, + 'description' => null, + ]); }); }); diff --git a/tests/Unit/App/Dto/ProductIncoDtoTest.php b/tests/Unit/App/Dto/ProductIncoDtoTest.php index 755e6401..e43bc134 100644 --- a/tests/Unit/App/Dto/ProductIncoDtoTest.php +++ b/tests/Unit/App/Dto/ProductIncoDtoTest.php @@ -27,24 +27,13 @@ describe('ProductIncoDto', function () { ); // THEN - expect($dto->id)->toBe(42) - ->and($dto->no_art)->toBe(105) - ->and($dto->product_id)->toBe('018f6c40-1234-7123-8123-123456789012') - ->and($dto->ingredients)->toBe('Volaille, sel') - ->and($dto->preparation)->toBe('Au four 30min') - ->and($dto->servings)->toBe('4 personnes') - ->and($dto->allergens)->toBe('Aucun') - ->and($dto->selling_argument)->toBe('Origine France') - ->and($dto->nutriscore)->toBe(Nutriscore::A) - ->and($dto->nutriscore_args)->toBe('Faible en gras') - ->and($dto->nutrition)->toBe($nutrition) - ->and($dto->getRouteKey())->toBe(42) + $array = $dto->toArray(); + + expect($dto->getRouteKey())->toBe(42) ->and($dto->getRouteKeyName())->toBe('id') ->and($dto->resolveRouteBinding('some-id'))->toBeNull() - ->and($dto->resolveChildRouteBinding('child', 'some-id', 'field'))->toBeNull(); - - $array = $dto->toArray(); - expect($array)->toHaveKey('id', 42) + ->and($dto->resolveChildRouteBinding('child', 'some-id', 'field'))->toBeNull() + ->and($array)->toHaveKey('id', 42) ->and($array)->toHaveKey('no_art', 105) ->and($array)->toHaveKey('nutriscore', Nutriscore::A->value) ->and($array['nutrition'])->toHaveKey('nv_ref_weight_g', 100.0); diff --git a/tests/Unit/App/Dto/RangeDtoTest.php b/tests/Unit/App/Dto/RangeDtoTest.php deleted file mode 100644 index 83440bed..00000000 --- a/tests/Unit/App/Dto/RangeDtoTest.php +++ /dev/null @@ -1,43 +0,0 @@ - 1, - 'name' => 'Gamme Découverte', - 'slug' => 'gamme-decouverte', - 'description' => '

Description

', - 'picture' => 'ranges/pic.jpg', - 'picture_alt' => 'Alt text', - 'picture_title' => 'Title text', - 'order' => 2, - 'status' => true, - ]; - - // WHEN - $dto = new RangeDto(...$data); - - // THEN - expect($dto->id)->toBe(1) - ->and($dto->name)->toBe('Gamme Découverte') - ->and($dto->slug)->toBe('gamme-decouverte') - ->and($dto->getRouteKey())->toBe('gamme-decouverte') - ->and($dto->getRouteKeyName())->toBe('slug') - ->and($dto->toArray())->toBe([ - 'id' => 1, - 'name' => 'Gamme Découverte', - 'slug' => 'gamme-decouverte', - 'description' => '

Description

', - 'picture' => 'ranges/pic.jpg', - 'picture_alt' => 'Alt text', - 'picture_title' => 'Title text', - 'order' => 2, - 'status' => true, - ]); - }); -}); diff --git a/tests/Unit/App/Dto/SettingDtoTest.php b/tests/Unit/App/Dto/SettingDtoTest.php index f7d35f6e..e241786b 100644 --- a/tests/Unit/App/Dto/SettingDtoTest.php +++ b/tests/Unit/App/Dto/SettingDtoTest.php @@ -15,9 +15,7 @@ describe('SettingDto', function (): void { $dto = new SettingDto(id: $id, employeeSites: $sites); // THEN - expect($dto->id)->toBe(1) - ->and($dto->employeeSites)->toBe(['PA', 'LY']) - ->and($dto->employeeSitesAsString())->toBe('PA, LY') + expect($dto->employeeSitesAsString())->toBe('PA, LY') ->and($dto->getShopperSiteCodes())->toHaveCount(2) ->and($dto->getShopperSiteCodes()[0])->toBeInstanceOf(ShopperSiteCode::class) ->and($dto->getShopperSiteCodes()[0]->value)->toBe('PA') diff --git a/tests/Unit/App/Dto/ShopDtoTest.php b/tests/Unit/App/Dto/ShopDtoTest.php index a35702d0..0b8b782b 100644 --- a/tests/Unit/App/Dto/ShopDtoTest.php +++ b/tests/Unit/App/Dto/ShopDtoTest.php @@ -7,41 +7,8 @@ use Domain\Models\Entities\Shop; use Domain\Models\ValueObjects\Entities\ShopId; use Ramsey\Uuid\Uuid; -describe('ShopDto', function () { - test('it can be instantiated directly and converts to array', function () { - // GIVEN & WHEN - $dto = new ShopDto( - id: '018f4a2b-3c4d-7e8f-9a0b-1c2d3e4f5a6b', - name: 'Boutique Principale', - address: '1 rue de Paris', - postcode: '75001', - city: 'Paris', - phone: '+33102030405', - latitude: '48.8566', - longitude: '2.3522', - default: true, - ); - - // THEN - expect($dto->id)->toBe('018f4a2b-3c4d-7e8f-9a0b-1c2d3e4f5a6b') - ->and($dto->name)->toBe('Boutique Principale') - ->and($dto->getRouteKey())->toBe('018f4a2b-3c4d-7e8f-9a0b-1c2d3e4f5a6b') - ->and($dto->getRouteKeyName())->toBe('id') - ->and($dto->default)->toBeTrue() - ->and($dto->toArray())->toBe([ - 'id' => '018f4a2b-3c4d-7e8f-9a0b-1c2d3e4f5a6b', - 'name' => 'Boutique Principale', - 'address' => '1 rue de Paris', - 'postcode' => '75001', - 'city' => 'Paris', - 'phone' => '+33102030405', - 'latitude' => '48.8566', - 'longitude' => '2.3522', - 'default' => true, - ]); - }); - - test('it can be created from domain Shop entity', function () { +describe('ShopDto', function (): void { + it('creates a DTO from domain Shop entity', function (): void { // GIVEN $uuid = Uuid::uuid7(); $shopId = new ShopId($uuid); diff --git a/tests/Unit/App/Dto/SlideDtoTest.php b/tests/Unit/App/Dto/SlideDtoTest.php deleted file mode 100644 index 46d8eec2..00000000 --- a/tests/Unit/App/Dto/SlideDtoTest.php +++ /dev/null @@ -1,71 +0,0 @@ -Découvrez notre nouvelle collection

', - picture: 'storage/modelfiles/slides/26/06/01/ab/summer.jpg', - picture_alt: 'Collection Été', - picture_title: 'Bannière promotionnelle été', - link: 'https://example.com/ete', - link_label: 'Voir les offres', - link_new_tab: true, - connected: false, - date_start: $dateStart, - date_end: $dateEnd, - order: 3, - status: true, - isVisible: true, - ); - - // THEN - expect($dto->id)->toBe(42) - ->and($dto->title)->toBe('Bannière Été') - ->and($dto->text)->toBe('

Découvrez notre nouvelle collection

') - ->and($dto->picture)->toBe('storage/modelfiles/slides/26/06/01/ab/summer.jpg') - ->and($dto->picture_alt)->toBe('Collection Été') - ->and($dto->picture_title)->toBe('Bannière promotionnelle été') - ->and($dto->link)->toBe('https://example.com/ete') - ->and($dto->link_label)->toBe('Voir les offres') - ->and($dto->link_new_tab)->toBeTrue() - ->and($dto->connected)->toBeFalse() - ->and($dto->date_start)->toEqual($dateStart) - ->and($dto->date_end)->toEqual($dateEnd) - ->and($dto->order)->toBe(3) - ->and($dto->status)->toBeTrue() - ->and($dto->isVisible())->toBeTrue() - ->and($dto->getRouteKey())->toBe(42) - ->and($dto->getRouteKeyName())->toBe('id') - ->and($dto->resolveRouteBinding(42))->toBeNull() - ->and($dto->resolveChildRouteBinding('child', 'val', 'field'))->toBeNull() - ->and($dto->toArray())->toBe([ - 'id' => 42, - 'title' => 'Bannière Été', - 'text' => '

Découvrez notre nouvelle collection

', - 'picture' => 'storage/modelfiles/slides/26/06/01/ab/summer.jpg', - 'picture_alt' => 'Collection Été', - 'picture_title' => 'Bannière promotionnelle été', - 'link' => 'https://example.com/ete', - 'link_label' => 'Voir les offres', - 'link_new_tab' => true, - 'connected' => false, - 'date_start' => $dateStart, - 'date_end' => $dateEnd, - 'order' => 3, - 'status' => true, - 'is_visible' => true, - ]); - }); -}); From a2fd84339860f919a1512e620df445a7c48b7037 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 12:53:27 +0100 Subject: [PATCH 122/183] test(tests): add unit tests for session-based basket repository Added tests for the SessionBasketRepository to ensure correct behavior when finding, persisting, and deleting baskets in the session. --- .../Standalones/App/Cqs}/Actions/Ranges/CreateRangeInputTest.php | 0 .../Standalones/App/Cqs}/Actions/Ranges/UpdateRangeInputTest.php | 0 .../Standalones/App/Cqs}/Actions/Slides/CreateSlideInputTest.php | 0 .../Standalones/App}/Services/DataTableServiceTest.php | 0 .../Standalones/App}/Services/ImageOptimizerServiceTest.php | 0 .../Standalones}/Infra/Adapters/Locks/LaravelCacheLockTest.php | 0 .../Infra/Adapters/Repositories/SessionBasketRepositoryTest.php | 0 .../Infra/Adapters/Services/SessionOrderBuilderManagerTest.php | 0 8 files changed, 0 insertions(+), 0 deletions(-) rename tests/{Unit/App => Integration/Standalones/App/Cqs}/Actions/Ranges/CreateRangeInputTest.php (100%) rename tests/{Unit/App => Integration/Standalones/App/Cqs}/Actions/Ranges/UpdateRangeInputTest.php (100%) rename tests/{Unit/App => Integration/Standalones/App/Cqs}/Actions/Slides/CreateSlideInputTest.php (100%) rename tests/{Unit => Integration/Standalones/App}/Services/DataTableServiceTest.php (100%) rename tests/{Unit => Integration/Standalones/App}/Services/ImageOptimizerServiceTest.php (100%) rename tests/{Unit => Integration/Standalones}/Infra/Adapters/Locks/LaravelCacheLockTest.php (100%) rename tests/{Unit => Integration/Standalones}/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php (100%) rename tests/{Unit => Integration/Standalones}/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php (100%) diff --git a/tests/Unit/App/Actions/Ranges/CreateRangeInputTest.php b/tests/Integration/Standalones/App/Cqs/Actions/Ranges/CreateRangeInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Ranges/CreateRangeInputTest.php rename to tests/Integration/Standalones/App/Cqs/Actions/Ranges/CreateRangeInputTest.php diff --git a/tests/Unit/App/Actions/Ranges/UpdateRangeInputTest.php b/tests/Integration/Standalones/App/Cqs/Actions/Ranges/UpdateRangeInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Ranges/UpdateRangeInputTest.php rename to tests/Integration/Standalones/App/Cqs/Actions/Ranges/UpdateRangeInputTest.php diff --git a/tests/Unit/App/Actions/Slides/CreateSlideInputTest.php b/tests/Integration/Standalones/App/Cqs/Actions/Slides/CreateSlideInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Slides/CreateSlideInputTest.php rename to tests/Integration/Standalones/App/Cqs/Actions/Slides/CreateSlideInputTest.php diff --git a/tests/Unit/Services/DataTableServiceTest.php b/tests/Integration/Standalones/App/Services/DataTableServiceTest.php similarity index 100% rename from tests/Unit/Services/DataTableServiceTest.php rename to tests/Integration/Standalones/App/Services/DataTableServiceTest.php diff --git a/tests/Unit/Services/ImageOptimizerServiceTest.php b/tests/Integration/Standalones/App/Services/ImageOptimizerServiceTest.php similarity index 100% rename from tests/Unit/Services/ImageOptimizerServiceTest.php rename to tests/Integration/Standalones/App/Services/ImageOptimizerServiceTest.php diff --git a/tests/Unit/Infra/Adapters/Locks/LaravelCacheLockTest.php b/tests/Integration/Standalones/Infra/Adapters/Locks/LaravelCacheLockTest.php similarity index 100% rename from tests/Unit/Infra/Adapters/Locks/LaravelCacheLockTest.php rename to tests/Integration/Standalones/Infra/Adapters/Locks/LaravelCacheLockTest.php diff --git a/tests/Unit/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php b/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php similarity index 100% rename from tests/Unit/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php rename to tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php diff --git a/tests/Unit/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php b/tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php similarity index 100% rename from tests/Unit/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php rename to tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php From 7698821501ad7ecd5ab7aa559a11e138178976de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 12:54:16 +0100 Subject: [PATCH 123/183] test(tests): add namespace declarations to test files --- .../Standalones/App/Cqs/Actions/Ranges/CreateRangeInputTest.php | 2 ++ .../Standalones/App/Cqs/Actions/Ranges/UpdateRangeInputTest.php | 2 ++ .../Standalones/App/Cqs/Actions/Slides/CreateSlideInputTest.php | 2 ++ .../Standalones/App/Services/ImageOptimizerServiceTest.php | 2 ++ .../Standalones/Infra/Adapters/Locks/LaravelCacheLockTest.php | 2 ++ .../Infra/Adapters/Repositories/SessionBasketRepositoryTest.php | 2 ++ .../Infra/Adapters/Services/SessionOrderBuilderManagerTest.php | 2 ++ 7 files changed, 14 insertions(+) diff --git a/tests/Integration/Standalones/App/Cqs/Actions/Ranges/CreateRangeInputTest.php b/tests/Integration/Standalones/App/Cqs/Actions/Ranges/CreateRangeInputTest.php index 1bb18171..05a5a31e 100644 --- a/tests/Integration/Standalones/App/Cqs/Actions/Ranges/CreateRangeInputTest.php +++ b/tests/Integration/Standalones/App/Cqs/Actions/Ranges/CreateRangeInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\Standalones\App\Cqs\Actions\Ranges; + use App\Cqs\Actions\Ranges\CreateRangeInput; use Domain\Models\ValueObjects\PictureMetadata; use Illuminate\Http\UploadedFile; diff --git a/tests/Integration/Standalones/App/Cqs/Actions/Ranges/UpdateRangeInputTest.php b/tests/Integration/Standalones/App/Cqs/Actions/Ranges/UpdateRangeInputTest.php index 2ebb21d5..b959034b 100644 --- a/tests/Integration/Standalones/App/Cqs/Actions/Ranges/UpdateRangeInputTest.php +++ b/tests/Integration/Standalones/App/Cqs/Actions/Ranges/UpdateRangeInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\Standalones\App\Cqs\Actions\Ranges; + use App\Cqs\Actions\Ranges\UpdateRangeInput; use App\Models\Range; use Domain\Models\ValueObjects\PictureMetadata; diff --git a/tests/Integration/Standalones/App/Cqs/Actions/Slides/CreateSlideInputTest.php b/tests/Integration/Standalones/App/Cqs/Actions/Slides/CreateSlideInputTest.php index 67694eb0..bf512c1e 100644 --- a/tests/Integration/Standalones/App/Cqs/Actions/Slides/CreateSlideInputTest.php +++ b/tests/Integration/Standalones/App/Cqs/Actions/Slides/CreateSlideInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\Standalones\App\Cqs\Actions\Slides; + use App\Cqs\Actions\Slides\CreateSlideInput; use Domain\Models\ValueObjects\DatePeriod; use Illuminate\Http\UploadedFile; diff --git a/tests/Integration/Standalones/App/Services/ImageOptimizerServiceTest.php b/tests/Integration/Standalones/App/Services/ImageOptimizerServiceTest.php index dc94c9d9..8f089dec 100644 --- a/tests/Integration/Standalones/App/Services/ImageOptimizerServiceTest.php +++ b/tests/Integration/Standalones/App/Services/ImageOptimizerServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\Standalones\App\Services; + use App\Services\ImageOptimizerService; use Illuminate\Http\UploadedFile; use Psr\Log\NullLogger; diff --git a/tests/Integration/Standalones/Infra/Adapters/Locks/LaravelCacheLockTest.php b/tests/Integration/Standalones/Infra/Adapters/Locks/LaravelCacheLockTest.php index 78915117..3c309327 100644 --- a/tests/Integration/Standalones/Infra/Adapters/Locks/LaravelCacheLockTest.php +++ b/tests/Integration/Standalones/Infra/Adapters/Locks/LaravelCacheLockTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\Standalones\Infra\Adapters\Locks; + use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository; use Illuminate\Contracts\Cache\Lock; diff --git a/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php b/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php index 538d8640..460679af 100644 --- a/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php +++ b/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\Standalones\Infra\Adapters\Repositories; + use Domain\Models\Entities\Basket; use Domain\Models\ValueObjects\Entities\BasketId; use Illuminate\Contracts\Session\Session; diff --git a/tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php b/tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php index c9537c6c..60b8d8e1 100644 --- a/tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php +++ b/tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\Standalones\Infra\Adapters\Services; + use Domain\Builders\OrderBuilderWithBasket; use Illuminate\Contracts\Session\Session; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; From ec6e220138e7444f131dd2ce4cf0bf6c5074d3fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 12:54:30 +0100 Subject: [PATCH 124/183] test(tests): update Carbon usage in GetPickTimeSlotQueryTest and IcsGeneratorServiceTest Refactor date handling to use CarbonImmutable for consistency in tests. --- tests/Unit/App/Queries/Orders/GetPickTimeSlotQueryTest.php | 3 ++- tests/Unit/App/Services/IcsGeneratorServiceTest.php | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/Unit/App/Queries/Orders/GetPickTimeSlotQueryTest.php b/tests/Unit/App/Queries/Orders/GetPickTimeSlotQueryTest.php index 1b6b2c55..d0ce32bb 100644 --- a/tests/Unit/App/Queries/Orders/GetPickTimeSlotQueryTest.php +++ b/tests/Unit/App/Queries/Orders/GetPickTimeSlotQueryTest.php @@ -7,6 +7,7 @@ use App\Cqs\Queries\Orders\GetPickTimeSlotQueryInput; use App\Cqs\Queries\Orders\GetPickTimeSlotQueryOutput; use App\Dto\ShopDto; use App\Services\MapUrlService; +use Carbon\CarbonImmutable; use Domain\Enums\OrderTunnelStep; use Domain\Models\Entities\Shop; use Domain\Models\ValueObjects\Entities\ShopId; @@ -28,7 +29,7 @@ describe('GetPickTimeSlotQuery', function (): void { postcode: '75001', city: 'Paris', ); - $slot = new PickupTimeSlot(now(), new \DateInterval('PT1H')); + $slot = new PickupTimeSlot(CarbonImmutable::parse('2026-10-15 10:00:00'), new \DateInterval('PT1H')); $timeSlots = [$slot]; $orderTunnelService = \Mockery::mock(OrderTunnelService::class); diff --git a/tests/Unit/App/Services/IcsGeneratorServiceTest.php b/tests/Unit/App/Services/IcsGeneratorServiceTest.php index 2ce42ed0..33f6b43d 100644 --- a/tests/Unit/App/Services/IcsGeneratorServiceTest.php +++ b/tests/Unit/App/Services/IcsGeneratorServiceTest.php @@ -4,9 +4,9 @@ declare(strict_types=1); use App\Dto\IcsContentDto; use App\Services\IcsGeneratorService; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Domain\Models\ValueObjects\IcsContent; -use Illuminate\Support\Carbon; covers(IcsGeneratorService::class); From 29b9a87d78ea099e2341c84e7a203746279b34d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 12:54:52 +0100 Subject: [PATCH 125/183] test(tests): update mock usage in DataTableServiceTest Refactor mock creation to use \Mockery::mock for consistency. --- .../App/Services/DataTableServiceTest.php | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/tests/Integration/Standalones/App/Services/DataTableServiceTest.php b/tests/Integration/Standalones/App/Services/DataTableServiceTest.php index 1ed54d24..101b8442 100644 --- a/tests/Integration/Standalones/App/Services/DataTableServiceTest.php +++ b/tests/Integration/Standalones/App/Services/DataTableServiceTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Tests\Unit\Services; +namespace Tests\Integration\Standalones\App\Services; use App\Models\Order; use App\Models\Product; @@ -22,7 +22,7 @@ describe('DataTableService', function () { 'sort_col' => 'name', 'sort_way' => 'desc', ]); - $session = mock(Session::class); + $session = \Mockery::mock(Session::class); $session->shouldReceive('get')->andReturn(null); $service = new DataTableService($request, $session, static fn (string $table): array => []); @@ -38,7 +38,7 @@ describe('DataTableService', function () { it('falls back to session when sort request input is not provided', function () { // GIVEN $request = Request::create('/bo/products', 'GET'); - $session = mock(Session::class); + $session = \Mockery::mock(Session::class); $session->shouldReceive('get')->with('noroute.sort_col', 'undefined')->andReturn('name'); $session->shouldReceive('get')->with('noroute.sort_way')->andReturn('asc'); @@ -55,7 +55,7 @@ describe('DataTableService', function () { it('resets sort session when rst parameter is present', function () { // GIVEN $request = Request::create('/bo/products', 'GET', ['rst' => '1']); - $session = mock(Session::class); + $session = \Mockery::mock(Session::class); $session->shouldReceive('forget')->with([ 'noroute.sort_col', 'noroute.sort_way', @@ -78,7 +78,7 @@ describe('DataTableService', function () { 'sort_col' => 'name', 'sort_way' => 'asc', ]); - $session = mock(Session::class); + $session = \Mockery::mock(Session::class); $session->shouldReceive('get')->andReturn(null); $session->shouldReceive('put')->times(4); @@ -89,10 +89,10 @@ describe('DataTableService', function () { return ['id', 'name', 'order', 'created_at']; }; - $query = mock(Builder::class); + $query = \Mockery::mock(Builder::class); $query->shouldReceive('orderBy')->once()->with('products.name', 'asc'); - $query2 = mock(Builder::class); + $query2 = \Mockery::mock(Builder::class); $query2->shouldReceive('orderBy')->once()->with('products.name', 'asc'); $service = new DataTableService($request, $session, $columnResolver); @@ -111,7 +111,7 @@ describe('DataTableService', function () { it('sorts by default order column if model has order attribute and no sort column is specified', function () { // GIVEN $request = Request::create('/bo/products', 'GET'); - $session = mock(Session::class); + $session = \Mockery::mock(Session::class); $session->shouldReceive('get')->andReturn(null); $schemaCalls = []; @@ -121,7 +121,7 @@ describe('DataTableService', function () { return ['id', 'name', 'order', 'created_at']; }; - $query = mock(Builder::class); + $query = \Mockery::mock(Builder::class); $query->shouldReceive('orderBy')->once()->with('order', 'asc'); $service = new DataTableService($request, $session, $columnResolver); @@ -136,7 +136,7 @@ describe('DataTableService', function () { it('sorts by custom default column and way when no sort column is specified', function () { // GIVEN $request = Request::create('/bo/orders', 'GET'); - $session = mock(Session::class); + $session = \Mockery::mock(Session::class); $session->shouldReceive('get')->andReturn(null); $schemaCalls = []; @@ -146,7 +146,7 @@ describe('DataTableService', function () { return ['id', 'reference', 'status', 'total']; }; - $query = mock(Builder::class); + $query = \Mockery::mock(Builder::class); $query->shouldReceive('orderBy')->once()->with('orders.id', 'desc'); $service = new DataTableService($request, $session, $columnResolver); @@ -170,7 +170,7 @@ describe('DataTableService', function () { 'sort_col' => 'date', 'sort_way' => 'asc', ]); - $session = mock(Session::class); + $session = \Mockery::mock(Session::class); $session->shouldReceive('get')->andReturn(null); $session->shouldReceive('put')->twice(); @@ -181,7 +181,7 @@ describe('DataTableService', function () { return ['id', 'reference', 'status', 'total']; }; - $query = mock(Builder::class); + $query = \Mockery::mock(Builder::class); $query->shouldReceive('orderBy')->once()->with('orders.id', 'asc'); $service = new DataTableService($request, $session, $columnResolver); From 7b27f532ee88cca5cb42679e1e44d1565f45e37a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 13:00:47 +0100 Subject: [PATCH 126/183] test(tests): fix PHPStan level 10 errors in OrderTunnelServiceTest and PickupSchedulingServiceTest --- .../Services/OrderTunnelServiceTest.php | 140 +++++++++--------- .../Services/PickupSchedulingServiceTest.php | 61 ++++---- 2 files changed, 103 insertions(+), 98 deletions(-) diff --git a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php index 2d37c881..12ba95e9 100644 --- a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php +++ b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php @@ -119,8 +119,8 @@ function createOrderTunnelService( ?RegateService $regateService = null, ): OrderTunnelService { if ($productRepository === null) { - $productRepository = mock(ProductRepository::class); - $productRepository->shouldReceive('getBasketProduct')->andReturnUsing(function ($id, $qty) { + $productRepository = \Mockery::mock(ProductRepository::class); + $productRepository->shouldReceive('getBasketProduct')->andReturnUsing(function (ProductId $id, int $qty): BasketProduct { return new BasketProduct( id: $id, name: 'Test Product', @@ -141,16 +141,16 @@ function createOrderTunnelService( ); })->byDefault(); } - $shopRepository ??= mock(ShopRepository::class); - $shopperRepository ??= mock(ShopperRepository::class); + $shopRepository ??= \Mockery::mock(ShopRepository::class); + $shopperRepository ??= \Mockery::mock(ShopperRepository::class); if ($pickupExceptionRepository === null) { - $pickupExceptionRepository = mock(PickupExceptionRepository::class); + $pickupExceptionRepository = \Mockery::mock(PickupExceptionRepository::class); $pickupExceptionRepository->shouldReceive('getExceptionsForShop')->andReturn([])->byDefault(); } - $orderBuilderSessionManager ??= mock(OrderBuilderSessionManager::class); - $orderRepository ??= mock(OrderRepository::class); + $orderBuilderSessionManager ??= \Mockery::mock(OrderBuilderSessionManager::class); + $orderRepository ??= \Mockery::mock(OrderRepository::class); - $eventDispatcher ??= mock(DomainEventDispatcher::class); + $eventDispatcher ??= \Mockery::mock(DomainEventDispatcher::class); $employeeStatisticsService = \Mockery::mock(EmployeeStatisticsService::class); $employeeStatisticsService->shouldReceive('getWeeklyTotalForEmployee')->andReturn(Money::EUR(0))->byDefault(); @@ -186,7 +186,7 @@ describe('OrderTunnelService', function (): void { it('allows access to BOOKING step when builder is from basket and has items', function (): void { // GIVEN $builder = createTestBuilder(); - $orderBuilderRepository = mock(OrderBuilderSessionManager::class); + $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn($builder); $service = createOrderTunnelService( @@ -203,7 +203,7 @@ describe('OrderTunnelService', function (): void { it('denies access to BOOKING step when builder has an empty basket', function (): void { // GIVEN $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(Uuid::uuid7())); - $orderBuilderRepository = mock(OrderBuilderSessionManager::class); + $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn($builder); $service = createOrderTunnelService( @@ -219,7 +219,7 @@ describe('OrderTunnelService', function (): void { it('denies access to BOOKING step when builder is missing', function (): void { // GIVEN - $orderBuilderRepository = mock(OrderBuilderSessionManager::class); + $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn(null); $service = createOrderTunnelService( @@ -236,7 +236,7 @@ describe('OrderTunnelService', function (): void { it('allows access to CONFIRMATION step when builder is completed and has items', function (): void { // GIVEN $builder = createTestBuilder(completed: true); - $orderBuilderRepository = mock(OrderBuilderSessionManager::class); + $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn($builder); $service = createOrderTunnelService( @@ -253,7 +253,7 @@ describe('OrderTunnelService', function (): void { it('denies access to CONFIRMATION step when builder is not completed', function (): void { // GIVEN $builder = createTestBuilder(completed: false); - $orderBuilderRepository = mock(OrderBuilderSessionManager::class); + $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn($builder); $service = createOrderTunnelService( @@ -273,7 +273,7 @@ describe('OrderTunnelService', function (): void { $nextFriday = CarbonImmutable::now('Europe/Paris')->next(WeekDay::Friday->value)->addWeek()->startOfDay(); $timeSlot = new PickupTimeSlot($nextFriday, new \DateInterval('PT1H')); $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(Uuid::uuid7()))->withPickupTimeSlot($shopId, $timeSlot); - $orderBuilderRepository = mock(OrderBuilderSessionManager::class); + $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn($builder); $service = createOrderTunnelService( @@ -289,7 +289,7 @@ describe('OrderTunnelService', function (): void { it('denies access to CONFIRMATION step when builder is missing', function (): void { // GIVEN - $orderBuilderRepository = mock(OrderBuilderSessionManager::class); + $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn(null); $service = createOrderTunnelService( @@ -328,10 +328,10 @@ describe('OrderTunnelService', function (): void { city: 'Paris' ); - $shopperRepo = mock(ShopperRepository::class); + $shopperRepo = \Mockery::mock(ShopperRepository::class); $shopperRepo->shouldReceive('find')->with($shopperId)->andReturn($shopper); - $shopRepo = mock(ShopRepository::class); + $shopRepo = \Mockery::mock(ShopRepository::class); $shopRepo->shouldReceive('findExceptionShopFor')->with($shopper->matricule)->andReturn(null); $shopRepo->shouldReceive('findShopForSiteAndService')->with($shopper->site, $shopper->service)->andReturn(null); $shopRepo->shouldReceive('findShopForSiteAndService')->with($shopper->site, null)->andReturn(null); @@ -352,7 +352,7 @@ describe('OrderTunnelService', function (): void { it('throws exception when get shop for customer fails', function (): void { // GIVEN $shopperId = new ShopperId(Uuid::uuid7()); - $shopperRepo = mock(ShopperRepository::class); + $shopperRepo = \Mockery::mock(ShopperRepository::class); $shopperRepo->shouldReceive('find')->with($shopperId)->andReturn(null); $service = createOrderTunnelService(shopperRepository: $shopperRepo); @@ -368,7 +368,7 @@ describe('OrderTunnelService', function (): void { $shopId = new ShopId(Uuid::uuid7()); $shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris'); - $pickupExceptionRepo = mock(PickupExceptionRepository::class); + $pickupExceptionRepo = \Mockery::mock(PickupExceptionRepository::class); $pickupExceptionRepo->shouldReceive('getExceptionsForShop')->andReturn([]); $service = createOrderTunnelService(pickupExceptionRepository: $pickupExceptionRepo); @@ -385,7 +385,7 @@ describe('OrderTunnelService', function (): void { $basket = createTestBasket(1); $customerId = new ShopperId(Uuid::uuid7()); - $orderBuilderRepo = mock(OrderBuilderSessionManager::class); + $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepo->shouldReceive('save')->once(); $service = createOrderTunnelService(orderBuilderSessionManager: $orderBuilderRepo); @@ -400,7 +400,7 @@ describe('OrderTunnelService', function (): void { it('gets builder from basket or fail', function (): void { // GIVEN $builder = createTestBuilder(); - $orderBuilderRepo = mock(OrderBuilderSessionManager::class); + $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepo->shouldReceive('get')->once()->andReturn($builder); $service = createOrderTunnelService(orderBuilderSessionManager: $orderBuilderRepo); @@ -414,7 +414,7 @@ describe('OrderTunnelService', function (): void { it('throws exception if builder not from basket', function (): void { // GIVEN - $orderBuilderRepo = mock(OrderBuilderSessionManager::class); + $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepo->shouldReceive('get')->once()->andReturn(null); $service = createOrderTunnelService(orderBuilderSessionManager: $orderBuilderRepo); @@ -428,7 +428,7 @@ describe('OrderTunnelService', function (): void { it('throws exception in getBuilderFromBasketOrFail when builder has an empty basket', function (): void { // GIVEN $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(Uuid::uuid7())); - $orderBuilderRepo = mock(OrderBuilderSessionManager::class); + $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepo->shouldReceive('get')->once()->andReturn($builder); $service = createOrderTunnelService(orderBuilderSessionManager: $orderBuilderRepo); @@ -443,7 +443,7 @@ describe('OrderTunnelService', function (): void { it('gets completed builder or fail', function (): void { // GIVEN $builder = createTestBuilder(completed: true); - $orderBuilderRepo = mock(OrderBuilderSessionManager::class); + $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepo->shouldReceive('get')->once()->andReturn($builder); $service = createOrderTunnelService(orderBuilderSessionManager: $orderBuilderRepo); @@ -458,7 +458,7 @@ describe('OrderTunnelService', function (): void { it('throws exception if builder not completed', function (): void { // GIVEN $builder = createTestBuilder(completed: false); - $orderBuilderRepo = mock(OrderBuilderSessionManager::class); + $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepo->shouldReceive('get')->once()->andReturn($builder); $service = createOrderTunnelService(orderBuilderSessionManager: $orderBuilderRepo); @@ -476,7 +476,7 @@ describe('OrderTunnelService', function (): void { $timeSlot = new PickupTimeSlot($nextFriday, new \DateInterval('PT1H')); $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(Uuid::uuid7()))->withPickupTimeSlot($shopId, $timeSlot); - $orderBuilderRepo = mock(OrderBuilderSessionManager::class); + $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepo->shouldReceive('get')->once()->andReturn($builder); $service = createOrderTunnelService(orderBuilderSessionManager: $orderBuilderRepo); @@ -492,12 +492,12 @@ describe('OrderTunnelService', function (): void { // GIVEN $builder = createTestBuilder(completed: false); $shop = new Shop(new ShopId(Uuid::uuid7()), 'Shop', 'Address', '75000', 'Paris'); - $selectedDate = CarbonImmutable::create(2025, 1, 1); + $selectedDate = CarbonImmutable::parse('2025-01-01'); $ts1 = new PickupTimeSlot($selectedDate, new \DateInterval('PT1H')); - $ts2 = new PickupTimeSlot(CarbonImmutable::create(2025, 1, 2), new \DateInterval('PT1H')); + $ts2 = new PickupTimeSlot(CarbonImmutable::parse('2025-01-02'), new \DateInterval('PT1H')); $availableSlots = [$ts1, $ts2]; - $orderBuilderRepo = mock(OrderBuilderSessionManager::class); + $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepo->shouldReceive('save')->once(); $service = createOrderTunnelService(orderBuilderSessionManager: $orderBuilderRepo); @@ -513,8 +513,8 @@ describe('OrderTunnelService', function (): void { // GIVEN $builder = createTestBuilder(completed: false); $shop = new Shop(new ShopId(Uuid::uuid7()), 'Shop', 'Address', '75000', 'Paris'); - $selectedDate = CarbonImmutable::create(2025, 1, 1); - $ts1 = new PickupTimeSlot(CarbonImmutable::create(2025, 1, 2), new \DateInterval('PT1H')); + $selectedDate = CarbonImmutable::parse('2025-01-01'); + $ts1 = new PickupTimeSlot(CarbonImmutable::parse('2025-01-02'), new \DateInterval('PT1H')); $availableSlots = [$ts1]; $service = createOrderTunnelService(); @@ -542,22 +542,22 @@ describe('OrderTunnelService', function (): void { site: new ShopperSiteCode('SITEA'), service: new ShopperServiceCode('101') ); - $shopperRepo = mock(ShopperRepository::class); + $shopperRepo = \Mockery::mock(ShopperRepository::class); $shopperRepo->shouldReceive('getByIdOrFail')->with(\Mockery::type(ShopperId::class))->andReturn($shopper); $shopId = clone clone $builder->getShopId(); $shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris'); - $shopRepo = mock(ShopRepository::class); + $shopRepo = \Mockery::mock(ShopRepository::class); $shopRepo->shouldReceive('find')->andReturn($shop); // any with shopId is fine - $orderRepo = mock(OrderRepository::class); + $orderRepo = \Mockery::mock(OrderRepository::class); $orderRepo->shouldReceive('getWeeklyTotalForEmployee')->andReturn(Money::EUR(5000)); $orderRepo->shouldReceive('persist')->once(); - $eventDispatcher = mock(DomainEventDispatcher::class); + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); $eventDispatcher->shouldReceive('dispatch')->once(); - $builderRepo = mock(OrderBuilderSessionManager::class); + $builderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $builderRepo->shouldNotReceive('clear'); $service = createOrderTunnelService( @@ -593,13 +593,13 @@ describe('OrderTunnelService', function (): void { site: new ShopperSiteCode('SITEA'), service: new ShopperServiceCode('101') ); - $shopperRepo = mock(ShopperRepository::class); + $shopperRepo = \Mockery::mock(ShopperRepository::class); $shopperRepo->shouldReceive('getByIdOrFail')->with(\Mockery::type(ShopperId::class))->andReturn($shopper); - $shopRepo = mock(ShopRepository::class); + $shopRepo = \Mockery::mock(ShopRepository::class); $shopRepo->shouldReceive('find')->andReturn(null); - $orderRepo = mock(OrderRepository::class); + $orderRepo = \Mockery::mock(OrderRepository::class); $orderRepo->shouldReceive('getWeeklyTotalForEmployee')->andReturn(Money::EUR(5000)); $service = createOrderTunnelService( @@ -630,26 +630,26 @@ describe('OrderTunnelService', function (): void { site: new ShopperSiteCode('SITEA'), service: new ShopperServiceCode('101') ); - $shopperRepo = mock(ShopperRepository::class); + $shopperRepo = \Mockery::mock(ShopperRepository::class); $shopperRepo->shouldReceive('getByIdOrFail')->with(\Mockery::type(ShopperId::class))->andReturn($shopper); $shopId = clone $builder->getShopId(); $shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris'); - $shopRepo = mock(ShopRepository::class); + $shopRepo = \Mockery::mock(ShopRepository::class); $shopRepo->shouldReceive('find')->andReturn($shop); - $orderRepo = mock(OrderRepository::class); + $orderRepo = \Mockery::mock(OrderRepository::class); $orderRepo->shouldReceive('getWeeklyTotalForEmployee')->andReturn(Money::EUR(5000)); $orderRepo->shouldReceive('persist')->once(); - $eventDispatcher = mock(DomainEventDispatcher::class); + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); $eventDispatcher->shouldReceive('dispatch')->once(); - $builderRepo = mock(OrderBuilderSessionManager::class); + $builderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $builderRepo->shouldNotReceive('clear'); - $productRepo = mock(ProductRepository::class); - $productRepo->shouldReceive('getBasketProduct')->once()->andReturnUsing(function ($id, $qty) { + $productRepo = \Mockery::mock(ProductRepository::class); + $productRepo->shouldReceive('getBasketProduct')->once()->andReturnUsing(function (ProductId $id, int $qty): BasketProduct { return new BasketProduct( id: $id, name: 'Updated Product Name', @@ -689,17 +689,17 @@ describe('OrderTunnelService', function (): void { it('throws BasketPriceChangedException with refreshed basket when product price changes before finalization', function (): void { // GIVEN $builder = createTestBuilder(completed: true); - $shopperRepo = mock(ShopperRepository::class); + $shopperRepo = \Mockery::mock(ShopperRepository::class); $shopperRepo->shouldNotReceive('getByIdOrFail'); - $orderRepo = mock(OrderRepository::class); + $orderRepo = \Mockery::mock(OrderRepository::class); $orderRepo->shouldNotReceive('persist'); - $eventDispatcher = mock(DomainEventDispatcher::class); + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); $eventDispatcher->shouldNotReceive('dispatch'); - $productRepo = mock(ProductRepository::class); - $productRepo->shouldReceive('getBasketProduct')->once()->andReturnUsing(function ($id, $qty) { + $productRepo = \Mockery::mock(ProductRepository::class); + $productRepo->shouldReceive('getBasketProduct')->once()->andReturnUsing(function (ProductId $id, int $qty): BasketProduct { return new BasketProduct( id: $id, name: 'Updated Price Product', @@ -746,7 +746,7 @@ describe('OrderTunnelService', function (): void { $basket = createTestBasket(1); $shopperId = new ShopperId(Uuid::uuid7()); $shopId = new ShopId(Uuid::uuid7()); - $expiredSlot = new PickupTimeSlot(CarbonImmutable::create(2025, 1, 1), new \DateInterval('PT1H')); + $expiredSlot = new PickupTimeSlot(CarbonImmutable::parse('2025-01-01'), new \DateInterval('PT1H')); $builder = OrderBuilder::fromBasket($basket, $shopperId)->withPickupTimeSlot($shopId, $expiredSlot); $shopper = new Shopper( @@ -761,20 +761,20 @@ describe('OrderTunnelService', function (): void { site: new ShopperSiteCode('SITEA'), service: new ShopperServiceCode('101') ); - $shopperRepo = mock(ShopperRepository::class); + $shopperRepo = \Mockery::mock(ShopperRepository::class); $shopperRepo->shouldReceive('getByIdOrFail')->with(\Mockery::type(ShopperId::class))->andReturn($shopper); $shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris'); - $shopRepo = mock(ShopRepository::class); + $shopRepo = \Mockery::mock(ShopRepository::class); $shopRepo->shouldReceive('find')->andReturn($shop); - $orderRepo = mock(OrderRepository::class); + $orderRepo = \Mockery::mock(OrderRepository::class); $orderRepo->shouldNotReceive('persist'); - $eventDispatcher = mock(DomainEventDispatcher::class); + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); $eventDispatcher->shouldNotReceive('dispatch'); - $builderRepo = mock(OrderBuilderSessionManager::class); + $builderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $builderRepo->shouldNotReceive('clear'); $service = createOrderTunnelService( @@ -796,18 +796,18 @@ describe('OrderTunnelService', function (): void { // GIVEN $builder = createTestBuilder(completed: true); - $productRepo = mock(ProductRepository::class); + $productRepo = \Mockery::mock(ProductRepository::class); $productRepo->shouldReceive('getBasketProduct') ->once() ->andThrow(new UnorderableProductException()); - $orderRepo = mock(OrderRepository::class); + $orderRepo = \Mockery::mock(OrderRepository::class); $orderRepo->shouldNotReceive('persist'); - $eventDispatcher = mock(DomainEventDispatcher::class); + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); $eventDispatcher->shouldNotReceive('dispatch'); - $builderRepo = mock(OrderBuilderSessionManager::class); + $builderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $builderRepo->shouldNotReceive('clear'); $service = createOrderTunnelService( @@ -840,24 +840,24 @@ describe('OrderTunnelService', function (): void { site: new ShopperSiteCode('SITEA'), service: new ShopperServiceCode('101') ); - $shopperRepo = mock(ShopperRepository::class); + $shopperRepo = \Mockery::mock(ShopperRepository::class); $shopperRepo->shouldReceive('getByIdOrFail')->with(\Mockery::type(ShopperId::class))->andReturn($shopper); $shopId = clone $builder->getShopId(); $shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris'); - $shopRepo = mock(ShopRepository::class); + $shopRepo = \Mockery::mock(ShopRepository::class); $shopRepo->shouldReceive('find')->andReturn($shop); - $orderRepo = mock(OrderRepository::class); + $orderRepo = \Mockery::mock(OrderRepository::class); $orderRepo->shouldReceive('persist')->once(); - $eventDispatcher = mock(DomainEventDispatcher::class); + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); $eventDispatcher->shouldNotReceive('dispatch'); - $builderRepo = mock(OrderBuilderSessionManager::class); + $builderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $builderRepo->shouldNotReceive('clear'); - $regateService = mock(RegateService::class); + $regateService = \Mockery::mock(RegateService::class); $regateService->shouldReceive('processOrder')->once()->andThrow(new RegateExportFailedException('SMTP failed')); $service = createOrderTunnelService( @@ -892,13 +892,13 @@ describe('OrderTunnelService', function (): void { site: new ShopperSiteCode('SITEA'), service: new ShopperServiceCode('101') ); - $shopperRepo = mock(ShopperRepository::class); + $shopperRepo = \Mockery::mock(ShopperRepository::class); $shopperRepo->shouldReceive('getByIdOrFail')->with(\Mockery::type(ShopperId::class))->andReturn($inactiveShopper); - $orderRepo = mock(OrderRepository::class); + $orderRepo = \Mockery::mock(OrderRepository::class); $orderRepo->shouldNotReceive('persist'); - $eventDispatcher = mock(DomainEventDispatcher::class); + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); $eventDispatcher->shouldNotReceive('dispatch'); $service = createOrderTunnelService( diff --git a/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php b/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php index 544351e1..66a821ce 100644 --- a/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php +++ b/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php @@ -14,7 +14,6 @@ use Domain\Models\ValueObjects\PickupWindow; use Domain\Models\ValueObjects\ShopPickupOverride; use Domain\Ports\Repositories\PickupExceptionRepository; use Domain\Services\PickupSchedulingService; -use Illuminate\Support\Facades\Date; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; @@ -78,9 +77,10 @@ describe('Pickup Scheduling Service', function (): void { // THEN $targetFriday = '2026-05-15'; - $hasFridaySlot = collect($results) - ->contains(fn (PickupTimeSlot $slot) => Date::createFromInterface($slot->getAt()) - ->isSameDay($targetFriday)); + $hasFridaySlot = array_any( + $results, + static fn (PickupTimeSlot $slot): bool => CarbonImmutable::instance($slot->getAt())->isSameDay($targetFriday) + ); // THEN @@ -126,9 +126,10 @@ describe('Pickup Scheduling Service', function (): void { // THEN $targetReplacementDay = '2026-05-07'; - $hasThursdaySlot = collect($results) - ->contains(fn (PickupTimeSlot $slot) => Date::createFromInterface($slot->getAt()) - ->isSameDay($targetReplacementDay)); + $hasThursdaySlot = array_any( + $results, + static fn (PickupTimeSlot $slot): bool => CarbonImmutable::instance($slot->getAt())->isSameDay($targetReplacementDay) + ); // THEN @@ -155,9 +156,10 @@ describe('Pickup Scheduling Service', function (): void { // THEN $targetReplacementDay = '2026-05-05'; - $hasTuesdaySlot = collect($results) - ->contains(fn (PickupTimeSlot $slot) => Date::createFromInterface($slot->getAt()) - ->isSameDay($targetReplacementDay)); + $hasTuesdaySlot = array_any( + $results, + static fn (PickupTimeSlot $slot): bool => CarbonImmutable::instance($slot->getAt())->isSameDay($targetReplacementDay) + ); // THEN @@ -191,13 +193,10 @@ describe('Pickup Scheduling Service', function (): void { $results = $service->getTimeSlotsFor($shop, $until); // THEN - expect($results)->toHaveCount(3); - // THEN - expect(Date::createFromInterface($results[0]->getAt())->isSameDay('2026-05-15'))->toBeTrue(); - // THEN - expect(Date::createFromInterface($results[1]->getAt())->isSameDay('2026-05-22'))->toBeTrue(); - // THEN - expect(Date::createFromInterface($results[2]->getAt())->isSameDay('2026-05-29'))->toBeTrue(); + expect($results)->toHaveCount(3) + ->and(CarbonImmutable::instance($results[0]->getAt())->isSameDay('2026-05-15'))->toBeTrue() + ->and(CarbonImmutable::instance($results[1]->getAt())->isSameDay('2026-05-22'))->toBeTrue() + ->and(CarbonImmutable::instance($results[2]->getAt())->isSameDay('2026-05-29'))->toBeTrue(); }); it('ignores pickup exceptions that do not fall on a Friday', function (): void { @@ -220,9 +219,8 @@ describe('Pickup Scheduling Service', function (): void { $results = $service->getTimeSlotsFor($shop, $until); // THEN - expect($results)->toHaveCount(1); - // THEN - expect(Date::createFromInterface($results[0]->getAt())->isSameDay('2026-05-15'))->toBeTrue(); + expect($results)->toHaveCount(1) + ->and(CarbonImmutable::instance($results[0]->getAt())->isSameDay('2026-05-15'))->toBeTrue(); }); it('excludes the current day if the order is placed on pickup day morning', function (): void { @@ -237,9 +235,10 @@ describe('Pickup Scheduling Service', function (): void { $results = $service->getTimeSlotsFor($shop, $until); // THEN - $hasTodaySlot = collect($results) - ->contains(fn (PickupTimeSlot $slot) => Date::createFromInterface($slot->getAt()) - ->isSameDay('2026-05-15')); + $hasTodaySlot = array_any( + $results, + static fn (PickupTimeSlot $slot): bool => CarbonImmutable::instance($slot->getAt())->isSameDay('2026-05-15') + ); // THEN @@ -293,7 +292,7 @@ describe('Pickup Scheduling Service', function (): void { // THEN expect($period->getStartDate()->format('Y-m-d H:i:s'))->toBe('2026-05-04 14:00:00') - ->and($period->getEndDate()->format('Y-m-d H:i:s'))->toBe('2026-05-08 23:59:59'); + ->and($period->getEndDate()?->format('Y-m-d H:i:s'))->toBe('2026-05-08 23:59:59'); }); it('gets period for pickup date', function (): void { @@ -306,7 +305,7 @@ describe('Pickup Scheduling Service', function (): void { // THEN expect($period->getStartDate()->format('Y-m-d H:i:s'))->toBe('2026-05-11 14:00:00') - ->and($period->getEndDate()->format('Y-m-d H:i:s'))->toBe('2026-05-15 23:59:59'); + ->and($period->getEndDate()?->format('Y-m-d H:i:s'))->toBe('2026-05-15 23:59:59'); }); it('gets editable pickup exceptions for shop', function (): void { @@ -397,8 +396,14 @@ describe('Pickup Scheduling Service', function (): void { // THEN $targetFriday = '2026-11-06'; - $hasFridayAtCutoff = collect($slotsAtCutoff)->contains(fn (PickupTimeSlot $slot) => Date::createFromInterface($slot->getAt())->isSameDay($targetFriday)); - $hasFridayPastCutoff = collect($slotsPastCutoff)->contains(fn (PickupTimeSlot $slot) => Date::createFromInterface($slot->getAt())->isSameDay($targetFriday)); + $hasFridayAtCutoff = array_any( + $slotsAtCutoff, + static fn (PickupTimeSlot $slot): bool => CarbonImmutable::instance($slot->getAt())->isSameDay($targetFriday) + ); + $hasFridayPastCutoff = array_any( + $slotsPastCutoff, + static fn (PickupTimeSlot $slot): bool => CarbonImmutable::instance($slot->getAt())->isSameDay($targetFriday) + ); expect($hasFridayAtCutoff)->toBeTrue() ->and($hasFridayPastCutoff)->toBeFalse(); @@ -467,7 +472,7 @@ describe('Pickup Scheduling Service', function (): void { ->and($slots)->toHaveCount(1) ->and($slots[0]->getAt()->format('Y-m-d'))->toBe('2026-05-15') ->and($period->getStartDate()->setTimezone('Europe/Paris')->format('Y-m-d H:i'))->toBe('2026-05-11 14:00') - ->and($period->getEndDate()->setTimezone('Europe/Paris')->format('Y-m-d H:i'))->toBe('2026-05-15 23:59'); + ->and($period->getEndDate()?->setTimezone('Europe/Paris')->format('Y-m-d H:i'))->toBe('2026-05-15 23:59'); }); it('allows ordering for Friday even when Monday (CUTOFF_DAY) is a public holiday', function (): void { From 3f4856efa2e9420efd0e2d551ee1257b416d0a7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 13:02:15 +0100 Subject: [PATCH 127/183] test(tests): move Laravel-bound tests out of Unit and group Unit Cqs tests (lot 3B) --- .../Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php | 5 ++--- tests/{Unit => Integration/WithApp}/App/Dto/PageDtoTest.php | 2 ++ .../Infra/Adapters/Services/AppAdminAuthServiceTest.php | 2 ++ .../Infra/Adapters/Services/AppCustomerAuthServiceTest.php | 5 +---- .../Actions/Common/ChangeModelOrderPositionInputTest.php | 0 .../{ => Cqs}/Actions/Common/ExecuteMassActionInputTest.php | 0 .../Actions/Customers/RegisterCustomerInputTest.php | 0 .../{ => Cqs}/Actions/Discounts/CreateDiscountInputTest.php | 0 .../{ => Cqs}/Actions/Discounts/UpdateDiscountInputTest.php | 0 tests/Unit/App/{ => Cqs}/Actions/Faqs/CreateFaqInputTest.php | 0 tests/Unit/App/{ => Cqs}/Actions/Faqs/UpdateFaqInputTest.php | 0 .../App/{ => Cqs}/Actions/Orders/ApplyPickTimeSlotTest.php | 0 tests/Unit/App/{ => Cqs}/Actions/Orders/CancelOrderTest.php | 0 .../{ => Cqs}/Actions/Orders/InitializeOrderTunnelTest.php | 0 .../App/{ => Cqs}/Actions/Orders/PlacePendingOrderTest.php | 0 .../Unit/App/{ => Cqs}/Actions/Pages/UpdatePageInputTest.php | 0 .../PickupExceptions/CreatePickupExceptionInputTest.php | 0 .../PickupExceptions/UpdatePickupExceptionInputTest.php | 0 .../Actions/ProductIncos/AssociateProductIncoInputTest.php | 0 .../{ => Cqs}/Actions/Settings/UpdateSettingsInputTest.php | 0 .../Unit/App/{ => Cqs}/Actions/Shops/CreateShopInputTest.php | 0 .../Unit/App/{ => Cqs}/Actions/Shops/UpdateShopInputTest.php | 0 .../Actions/Shops/UpdateShopPickupExceptionsInputTest.php | 0 .../App/{ => Cqs}/Actions/Slides/UpdateSlideInputTest.php | 0 tests/Unit/App/{ => Cqs}/Actions/Tags/CreateTagInputTest.php | 0 tests/Unit/App/{ => Cqs}/Actions/Tags/UpdateTagInputTest.php | 0 .../{ => Cqs}/Queries/Orders/GetBasketSummaryQueryTest.php | 0 .../Queries/Orders/GetOrderConfirmationQueryTest.php | 0 .../{ => Cqs}/Queries/Orders/GetPickTimeSlotQueryTest.php | 0 .../Queries/ProductIncos/GetArcadiaIncoPreviewQueryTest.php | 0 30 files changed, 7 insertions(+), 7 deletions(-) rename tests/{Unit => Feature}/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php (98%) rename tests/{Unit => Integration/WithApp}/App/Dto/PageDtoTest.php (97%) rename tests/{Unit => Integration/WithApp}/Infra/Adapters/Services/AppAdminAuthServiceTest.php (98%) rename tests/{Unit => Integration/WithApp}/Infra/Adapters/Services/AppCustomerAuthServiceTest.php (98%) rename tests/Unit/App/{ => Cqs}/Actions/Common/ChangeModelOrderPositionInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Common/ExecuteMassActionInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Customers/RegisterCustomerInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Discounts/CreateDiscountInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Discounts/UpdateDiscountInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Faqs/CreateFaqInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Faqs/UpdateFaqInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Orders/ApplyPickTimeSlotTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Orders/CancelOrderTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Orders/InitializeOrderTunnelTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Orders/PlacePendingOrderTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Pages/UpdatePageInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/PickupExceptions/CreatePickupExceptionInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/PickupExceptions/UpdatePickupExceptionInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/ProductIncos/AssociateProductIncoInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Settings/UpdateSettingsInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Shops/CreateShopInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Shops/UpdateShopInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Shops/UpdateShopPickupExceptionsInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Slides/UpdateSlideInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Tags/CreateTagInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Actions/Tags/UpdateTagInputTest.php (100%) rename tests/Unit/App/{ => Cqs}/Queries/Orders/GetBasketSummaryQueryTest.php (100%) rename tests/Unit/App/{ => Cqs}/Queries/Orders/GetOrderConfirmationQueryTest.php (100%) rename tests/Unit/App/{ => Cqs}/Queries/Orders/GetPickTimeSlotQueryTest.php (100%) rename tests/Unit/App/{ => Cqs}/Queries/ProductIncos/GetArcadiaIncoPreviewQueryTest.php (100%) diff --git a/tests/Unit/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php b/tests/Feature/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php similarity index 98% rename from tests/Unit/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php rename to tests/Feature/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php index e36c3031..6e4494d8 100644 --- a/tests/Unit/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php +++ b/tests/Feature/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Middleware; + use App\Http\Middleware\EnsureCustomerEmailIsVerified; use App\Models\Customer; use Illuminate\Http\RedirectResponse; @@ -11,9 +13,6 @@ use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\URL; use Infrastructure\Adapters\Services\AppCustomerAuthService; use Symfony\Component\HttpKernel\Exception\HttpException; -use Tests\TestCase; - -uses(TestCase::class); describe('EnsureCustomerEmailIsVerified', function () { it('redirects to fo.auth.verification.notice if customer is not verified', function () { diff --git a/tests/Unit/App/Dto/PageDtoTest.php b/tests/Integration/WithApp/App/Dto/PageDtoTest.php similarity index 97% rename from tests/Unit/App/Dto/PageDtoTest.php rename to tests/Integration/WithApp/App/Dto/PageDtoTest.php index 3cdf6b9f..d567676e 100644 --- a/tests/Unit/App/Dto/PageDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/PageDtoTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Dto; + use App\Dto\PageDto; use App\Models\Page; use Domain\Enums\StaticPageSlug; diff --git a/tests/Unit/Infra/Adapters/Services/AppAdminAuthServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/AppAdminAuthServiceTest.php similarity index 98% rename from tests/Unit/Infra/Adapters/Services/AppAdminAuthServiceTest.php rename to tests/Integration/WithApp/Infra/Adapters/Services/AppAdminAuthServiceTest.php index 0721233d..9fbd43ee 100644 --- a/tests/Unit/Infra/Adapters/Services/AppAdminAuthServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/AppAdminAuthServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Infra\Adapters\Services; + use App\Models\User; use Domain\Exceptions\AuthServiceException; use Illuminate\Contracts\Auth\StatefulGuard; diff --git a/tests/Unit/Infra/Adapters/Services/AppCustomerAuthServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php similarity index 98% rename from tests/Unit/Infra/Adapters/Services/AppCustomerAuthServiceTest.php rename to tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php index 2513ab63..5ec42471 100644 --- a/tests/Unit/Infra/Adapters/Services/AppCustomerAuthServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Tests\Unit\Infra\Adapters\Services; +namespace Tests\Integration\WithApp\Infra\Adapters\Services; use App\Exceptions\CrmServiceException; use App\Models\Customer; @@ -15,7 +15,6 @@ use Domain\Models\ValueObjects\Email; use Domain\Services\ShopperService; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\StatefulGuard; -use Illuminate\Contracts\Debug\ExceptionHandler; use Infrastructure\Adapters\Services\AppCustomerAuthService; use Mockery; use Ramsey\Uuid\Uuid; @@ -388,8 +387,6 @@ describe('AppCustomerAuthService', function (): void { $hashcode = new CrmHashcode(Uuid::uuid4()); $customer->hashcode = $hashcode; - app()->instance(ExceptionHandler::class, Mockery::mock(ExceptionHandler::class)->shouldIgnoreMissing()); - $exception = new CrmServiceException('Crm Error'); $crmService->shouldReceive('getCustomerFromHashCode')->with($customer->hashcode)->andReturn($exception); diff --git a/tests/Unit/App/Actions/Common/ChangeModelOrderPositionInputTest.php b/tests/Unit/App/Cqs/Actions/Common/ChangeModelOrderPositionInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Common/ChangeModelOrderPositionInputTest.php rename to tests/Unit/App/Cqs/Actions/Common/ChangeModelOrderPositionInputTest.php diff --git a/tests/Unit/App/Actions/Common/ExecuteMassActionInputTest.php b/tests/Unit/App/Cqs/Actions/Common/ExecuteMassActionInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Common/ExecuteMassActionInputTest.php rename to tests/Unit/App/Cqs/Actions/Common/ExecuteMassActionInputTest.php diff --git a/tests/Unit/App/Actions/Customers/RegisterCustomerInputTest.php b/tests/Unit/App/Cqs/Actions/Customers/RegisterCustomerInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Customers/RegisterCustomerInputTest.php rename to tests/Unit/App/Cqs/Actions/Customers/RegisterCustomerInputTest.php diff --git a/tests/Unit/App/Actions/Discounts/CreateDiscountInputTest.php b/tests/Unit/App/Cqs/Actions/Discounts/CreateDiscountInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Discounts/CreateDiscountInputTest.php rename to tests/Unit/App/Cqs/Actions/Discounts/CreateDiscountInputTest.php diff --git a/tests/Unit/App/Actions/Discounts/UpdateDiscountInputTest.php b/tests/Unit/App/Cqs/Actions/Discounts/UpdateDiscountInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Discounts/UpdateDiscountInputTest.php rename to tests/Unit/App/Cqs/Actions/Discounts/UpdateDiscountInputTest.php diff --git a/tests/Unit/App/Actions/Faqs/CreateFaqInputTest.php b/tests/Unit/App/Cqs/Actions/Faqs/CreateFaqInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Faqs/CreateFaqInputTest.php rename to tests/Unit/App/Cqs/Actions/Faqs/CreateFaqInputTest.php diff --git a/tests/Unit/App/Actions/Faqs/UpdateFaqInputTest.php b/tests/Unit/App/Cqs/Actions/Faqs/UpdateFaqInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Faqs/UpdateFaqInputTest.php rename to tests/Unit/App/Cqs/Actions/Faqs/UpdateFaqInputTest.php diff --git a/tests/Unit/App/Actions/Orders/ApplyPickTimeSlotTest.php b/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php similarity index 100% rename from tests/Unit/App/Actions/Orders/ApplyPickTimeSlotTest.php rename to tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php diff --git a/tests/Unit/App/Actions/Orders/CancelOrderTest.php b/tests/Unit/App/Cqs/Actions/Orders/CancelOrderTest.php similarity index 100% rename from tests/Unit/App/Actions/Orders/CancelOrderTest.php rename to tests/Unit/App/Cqs/Actions/Orders/CancelOrderTest.php diff --git a/tests/Unit/App/Actions/Orders/InitializeOrderTunnelTest.php b/tests/Unit/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php similarity index 100% rename from tests/Unit/App/Actions/Orders/InitializeOrderTunnelTest.php rename to tests/Unit/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php diff --git a/tests/Unit/App/Actions/Orders/PlacePendingOrderTest.php b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php similarity index 100% rename from tests/Unit/App/Actions/Orders/PlacePendingOrderTest.php rename to tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php diff --git a/tests/Unit/App/Actions/Pages/UpdatePageInputTest.php b/tests/Unit/App/Cqs/Actions/Pages/UpdatePageInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Pages/UpdatePageInputTest.php rename to tests/Unit/App/Cqs/Actions/Pages/UpdatePageInputTest.php diff --git a/tests/Unit/App/Actions/PickupExceptions/CreatePickupExceptionInputTest.php b/tests/Unit/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionInputTest.php similarity index 100% rename from tests/Unit/App/Actions/PickupExceptions/CreatePickupExceptionInputTest.php rename to tests/Unit/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionInputTest.php diff --git a/tests/Unit/App/Actions/PickupExceptions/UpdatePickupExceptionInputTest.php b/tests/Unit/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionInputTest.php similarity index 100% rename from tests/Unit/App/Actions/PickupExceptions/UpdatePickupExceptionInputTest.php rename to tests/Unit/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionInputTest.php diff --git a/tests/Unit/App/Actions/ProductIncos/AssociateProductIncoInputTest.php b/tests/Unit/App/Cqs/Actions/ProductIncos/AssociateProductIncoInputTest.php similarity index 100% rename from tests/Unit/App/Actions/ProductIncos/AssociateProductIncoInputTest.php rename to tests/Unit/App/Cqs/Actions/ProductIncos/AssociateProductIncoInputTest.php diff --git a/tests/Unit/App/Actions/Settings/UpdateSettingsInputTest.php b/tests/Unit/App/Cqs/Actions/Settings/UpdateSettingsInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Settings/UpdateSettingsInputTest.php rename to tests/Unit/App/Cqs/Actions/Settings/UpdateSettingsInputTest.php diff --git a/tests/Unit/App/Actions/Shops/CreateShopInputTest.php b/tests/Unit/App/Cqs/Actions/Shops/CreateShopInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Shops/CreateShopInputTest.php rename to tests/Unit/App/Cqs/Actions/Shops/CreateShopInputTest.php diff --git a/tests/Unit/App/Actions/Shops/UpdateShopInputTest.php b/tests/Unit/App/Cqs/Actions/Shops/UpdateShopInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Shops/UpdateShopInputTest.php rename to tests/Unit/App/Cqs/Actions/Shops/UpdateShopInputTest.php diff --git a/tests/Unit/App/Actions/Shops/UpdateShopPickupExceptionsInputTest.php b/tests/Unit/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Shops/UpdateShopPickupExceptionsInputTest.php rename to tests/Unit/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsInputTest.php diff --git a/tests/Unit/App/Actions/Slides/UpdateSlideInputTest.php b/tests/Unit/App/Cqs/Actions/Slides/UpdateSlideInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Slides/UpdateSlideInputTest.php rename to tests/Unit/App/Cqs/Actions/Slides/UpdateSlideInputTest.php diff --git a/tests/Unit/App/Actions/Tags/CreateTagInputTest.php b/tests/Unit/App/Cqs/Actions/Tags/CreateTagInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Tags/CreateTagInputTest.php rename to tests/Unit/App/Cqs/Actions/Tags/CreateTagInputTest.php diff --git a/tests/Unit/App/Actions/Tags/UpdateTagInputTest.php b/tests/Unit/App/Cqs/Actions/Tags/UpdateTagInputTest.php similarity index 100% rename from tests/Unit/App/Actions/Tags/UpdateTagInputTest.php rename to tests/Unit/App/Cqs/Actions/Tags/UpdateTagInputTest.php diff --git a/tests/Unit/App/Queries/Orders/GetBasketSummaryQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php similarity index 100% rename from tests/Unit/App/Queries/Orders/GetBasketSummaryQueryTest.php rename to tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php diff --git a/tests/Unit/App/Queries/Orders/GetOrderConfirmationQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php similarity index 100% rename from tests/Unit/App/Queries/Orders/GetOrderConfirmationQueryTest.php rename to tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php diff --git a/tests/Unit/App/Queries/Orders/GetPickTimeSlotQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php similarity index 100% rename from tests/Unit/App/Queries/Orders/GetPickTimeSlotQueryTest.php rename to tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php diff --git a/tests/Unit/App/Queries/ProductIncos/GetArcadiaIncoPreviewQueryTest.php b/tests/Unit/App/Cqs/Queries/ProductIncos/GetArcadiaIncoPreviewQueryTest.php similarity index 100% rename from tests/Unit/App/Queries/ProductIncos/GetArcadiaIncoPreviewQueryTest.php rename to tests/Unit/App/Cqs/Queries/ProductIncos/GetArcadiaIncoPreviewQueryTest.php From 348119ec7c4a7023e9e15762b259a92a2a1f8173 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 13:09:00 +0100 Subject: [PATCH 128/183] test(tests): normalize Integration Cqs and Feature App directories (lot 3C) --- tests/Feature/{ => App/Http/Controllers}/Bo/AuthTest.php | 0 .../Http/Controllers/Bo}/EmployeeSyncFeatureTest.php | 0 .../Http/Controllers/Bo}/SettingsControllerTest.php | 0 tests/Feature/{ => App/Http/Controllers}/Fo/AuthTest.php | 0 tests/Feature/{ => App}/Jobs/DeleteOldResetTokensTest.php | 0 .../{ => App}/Jobs/EnsurePublicHolidaysSyncedJobTest.php | 0 tests/Feature/{ => App}/Jobs/SendContactMailJobTest.php | 2 +- .../Feature/{ => App}/Jobs/SendMissingOrderReminderJobTest.php | 0 tests/Feature/{ => App}/Jobs/SendReminderMailTest.php | 0 tests/Feature/{ => App}/Jobs/UpdateSlidesStatusTest.php | 0 .../Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php | 0 .../Feature/{Bo/Modules => App/Views}/ChangeOrderBladeTest.php | 0 .../App/{ => Cqs}/Actions/Auth/DeleteOldResetTokensTest.php | 0 .../App/{ => Cqs}/Actions/Auth/ResetCustomerPasswordTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Basket/AddToBasketTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Basket/EmptyBasketTest.php | 0 .../App/{ => Cqs}/Actions/Basket/RemoveFromBasketTest.php | 0 .../{ => Cqs}/Actions/Common/ChangeModelOrderPositionTest.php | 0 .../App/{ => Cqs}/Actions/Common/ChangeModelOrderTest.php | 0 .../App/{ => Cqs}/Actions/Common/ExecuteMassActionTest.php | 0 .../App/{ => Cqs}/Actions/Common/ToggleModelStarTest.php | 0 .../App/{ => Cqs}/Actions/Common/ToggleModelStatusTest.php | 0 .../App/{ => Cqs}/Actions/Contact/SubmitContactFormTest.php | 0 .../App/{ => Cqs}/Actions/Crm/UnsubscribeFromNewsletterTest.php | 0 .../App/{ => Cqs}/Actions/Crm/UpdateCustomerPasswordTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Crm/UpdateCustomerTest.php | 0 .../App/{ => Cqs}/Actions/Customers/RegisterCustomerTest.php | 0 .../{ => Cqs}/Actions/Customers/UpdateCustomerLastLoginTest.php | 0 .../App/{ => Cqs}/Actions/Discounts/CreateDiscountTest.php | 0 .../App/{ => Cqs}/Actions/Discounts/DeleteDiscountTest.php | 0 .../App/{ => Cqs}/Actions/Discounts/UpdateDiscountTest.php | 0 .../Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Faqs/CreateFaqTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Faqs/DeleteFaqTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Faqs/UpdateFaqTest.php | 0 .../App/{ => Cqs}/Actions/Orders/ApplyPickTimeSlotTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Orders/CancelOrderTest.php | 0 .../{ => Cqs}/Actions/Orders/ClaimTodayOrderReminderTest.php | 0 .../App/{ => Cqs}/Actions/Orders/InitializeOrderTunnelTest.php | 0 .../App/{ => Cqs}/Actions/Orders/PlacePendingOrderTest.php | 0 .../{ => Cqs}/Actions/Orders/ReleaseTodayOrderReminderTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Pages/UpdatePageTest.php | 0 .../Actions/PickupExceptions/CreatePickupExceptionTest.php | 0 .../Actions/PickupExceptions/DeletePickupExceptionTest.php | 0 .../Actions/PickupExceptions/UpdatePickupExceptionTest.php | 0 .../PickupExceptions/UpsertShopsPickupExceptionsForYearTest.php | 0 .../{ => Cqs}/Actions/ProductIncos/AssociateProductIncoTest.php | 0 .../App/{ => Cqs}/Actions/ProductIncos/SyncProductIncoTest.php | 0 .../ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php | 0 .../App/{ => Cqs}/Actions/Products/CreateProductTest.php | 0 .../App/{ => Cqs}/Actions/Products/DeleteProductTest.php | 0 .../App/{ => Cqs}/Actions/Products/UpdateProductTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Ranges/CreateRangeTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Ranges/DeleteRangeTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Ranges/UpdateRangeTest.php | 0 .../App/{ => Cqs}/Actions/Settings/UpdateSettingsTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Shops/CreateShopTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Shops/DeleteShopTest.php | 0 .../{ => Cqs}/Actions/Shops/UpdateShopPickupExceptionsTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Shops/UpdateShopTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Slides/CreateSlideTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Slides/DeleteSlideTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Slides/UpdateSlideTest.php | 0 .../App/{ => Cqs}/Actions/Slides/UpdateSlidesStatusTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Tags/CreateTagTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Tags/DeleteTagTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Tags/UpdateTagTest.php | 0 .../WithApp/App/{ => Cqs}/Actions/Users/CreateUserTest.php | 0 .../{ => Cqs}/Queries/Customers/GetCustomerByEmailQueryTest.php | 0 .../Queries/Discounts/GetDiscountFormDataQueryTest.php | 0 .../Queries/Discounts/GetPaginatedDiscountsQueryTest.php | 0 .../WithApp/App/{ => Cqs}/Queries/Faqs/GetFaqsQueryTest.php | 0 .../App/{ => Cqs}/Queries/Faqs/GetPaginatedFaqsQueryTest.php | 0 .../Queries/Orders/GetTunnelOrderConfirmedQueryTest.php | 0 .../App/{ => Cqs}/Queries/Pages/GetPageBySlugQueryTest.php | 0 .../PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php | 0 .../HasAutoUpdatedPickupExceptionsForYearQueryTest.php | 0 .../Queries/ProductIncos/GetProductIncoForEditQueryTest.php | 0 .../Queries/Products/GetBoPaginatedProductsQueryTest.php | 0 .../Queries/Products/GetFoProductIndexPageQueryTest.php | 0 .../{ => Cqs}/Queries/Products/GetProductFormDataQueryTest.php | 0 .../{ => Cqs}/Queries/Ranges/GetPaginatedRangesQueryTest.php | 0 .../App/{ => Cqs}/Queries/Settings/GetSettingsQueryTest.php | 0 .../App/{ => Cqs}/Queries/Shops/GetPaginatedShopsQueryTest.php | 0 .../Queries/Shops/GetShopPickupExceptionsQueryTest.php | 0 .../WithApp/App/{ => Cqs}/Queries/Shops/GetShopQueryTest.php | 0 .../{ => Cqs}/Queries/Slides/GetPaginatedSlidesQueryTest.php | 0 87 files changed, 1 insertion(+), 1 deletion(-) rename tests/Feature/{ => App/Http/Controllers}/Bo/AuthTest.php (100%) rename tests/Feature/{Bo/Employees => App/Http/Controllers/Bo}/EmployeeSyncFeatureTest.php (100%) rename tests/Feature/{Bo/Settings => App/Http/Controllers/Bo}/SettingsControllerTest.php (100%) rename tests/Feature/{ => App/Http/Controllers}/Fo/AuthTest.php (100%) rename tests/Feature/{ => App}/Jobs/DeleteOldResetTokensTest.php (100%) rename tests/Feature/{ => App}/Jobs/EnsurePublicHolidaysSyncedJobTest.php (100%) rename tests/Feature/{ => App}/Jobs/SendContactMailJobTest.php (99%) rename tests/Feature/{ => App}/Jobs/SendMissingOrderReminderJobTest.php (100%) rename tests/Feature/{ => App}/Jobs/SendReminderMailTest.php (100%) rename tests/Feature/{ => App}/Jobs/UpdateSlidesStatusTest.php (100%) rename tests/Feature/{ => App}/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php (100%) rename tests/Feature/{Bo/Modules => App/Views}/ChangeOrderBladeTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Auth/DeleteOldResetTokensTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Auth/ResetCustomerPasswordTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Basket/AddToBasketTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Basket/EmptyBasketTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Basket/RemoveFromBasketTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Common/ChangeModelOrderPositionTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Common/ChangeModelOrderTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Common/ExecuteMassActionTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Common/ToggleModelStarTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Common/ToggleModelStatusTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Contact/SubmitContactFormTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Crm/UnsubscribeFromNewsletterTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Crm/UpdateCustomerPasswordTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Crm/UpdateCustomerTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Customers/RegisterCustomerTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Customers/UpdateCustomerLastLoginTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Discounts/CreateDiscountTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Discounts/DeleteDiscountTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Discounts/UpdateDiscountTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Faqs/CreateFaqTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Faqs/DeleteFaqTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Faqs/UpdateFaqTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Orders/ApplyPickTimeSlotTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Orders/CancelOrderTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Orders/ClaimTodayOrderReminderTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Orders/InitializeOrderTunnelTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Orders/PlacePendingOrderTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Orders/ReleaseTodayOrderReminderTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Pages/UpdatePageTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/PickupExceptions/CreatePickupExceptionTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/PickupExceptions/DeletePickupExceptionTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/PickupExceptions/UpdatePickupExceptionTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/PickupExceptions/UpsertShopsPickupExceptionsForYearTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/ProductIncos/AssociateProductIncoTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/ProductIncos/SyncProductIncoTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Products/CreateProductTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Products/DeleteProductTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Products/UpdateProductTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Ranges/CreateRangeTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Ranges/DeleteRangeTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Ranges/UpdateRangeTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Settings/UpdateSettingsTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Shops/CreateShopTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Shops/DeleteShopTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Shops/UpdateShopPickupExceptionsTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Shops/UpdateShopTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Slides/CreateSlideTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Slides/DeleteSlideTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Slides/UpdateSlideTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Slides/UpdateSlidesStatusTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Tags/CreateTagTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Tags/DeleteTagTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Tags/UpdateTagTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Actions/Users/CreateUserTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Customers/GetCustomerByEmailQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Discounts/GetDiscountFormDataQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Discounts/GetPaginatedDiscountsQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Faqs/GetFaqsQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Faqs/GetPaginatedFaqsQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Pages/GetPageBySlugQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/ProductIncos/GetProductIncoForEditQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Products/GetBoPaginatedProductsQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Products/GetFoProductIndexPageQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Products/GetProductFormDataQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Ranges/GetPaginatedRangesQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Settings/GetSettingsQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Shops/GetPaginatedShopsQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Shops/GetShopPickupExceptionsQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Shops/GetShopQueryTest.php (100%) rename tests/Integration/WithApp/App/{ => Cqs}/Queries/Slides/GetPaginatedSlidesQueryTest.php (100%) diff --git a/tests/Feature/Bo/AuthTest.php b/tests/Feature/App/Http/Controllers/Bo/AuthTest.php similarity index 100% rename from tests/Feature/Bo/AuthTest.php rename to tests/Feature/App/Http/Controllers/Bo/AuthTest.php diff --git a/tests/Feature/Bo/Employees/EmployeeSyncFeatureTest.php b/tests/Feature/App/Http/Controllers/Bo/EmployeeSyncFeatureTest.php similarity index 100% rename from tests/Feature/Bo/Employees/EmployeeSyncFeatureTest.php rename to tests/Feature/App/Http/Controllers/Bo/EmployeeSyncFeatureTest.php diff --git a/tests/Feature/Bo/Settings/SettingsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/SettingsControllerTest.php similarity index 100% rename from tests/Feature/Bo/Settings/SettingsControllerTest.php rename to tests/Feature/App/Http/Controllers/Bo/SettingsControllerTest.php diff --git a/tests/Feature/Fo/AuthTest.php b/tests/Feature/App/Http/Controllers/Fo/AuthTest.php similarity index 100% rename from tests/Feature/Fo/AuthTest.php rename to tests/Feature/App/Http/Controllers/Fo/AuthTest.php diff --git a/tests/Feature/Jobs/DeleteOldResetTokensTest.php b/tests/Feature/App/Jobs/DeleteOldResetTokensTest.php similarity index 100% rename from tests/Feature/Jobs/DeleteOldResetTokensTest.php rename to tests/Feature/App/Jobs/DeleteOldResetTokensTest.php diff --git a/tests/Feature/Jobs/EnsurePublicHolidaysSyncedJobTest.php b/tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php similarity index 100% rename from tests/Feature/Jobs/EnsurePublicHolidaysSyncedJobTest.php rename to tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php diff --git a/tests/Feature/Jobs/SendContactMailJobTest.php b/tests/Feature/App/Jobs/SendContactMailJobTest.php similarity index 99% rename from tests/Feature/Jobs/SendContactMailJobTest.php rename to tests/Feature/App/Jobs/SendContactMailJobTest.php index 19ecbfcf..3778f4b4 100644 --- a/tests/Feature/Jobs/SendContactMailJobTest.php +++ b/tests/Feature/App/Jobs/SendContactMailJobTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Tests\Feature\Jobs; +namespace Tests\Feature\App\Jobs; use App\Jobs\SendContactMailJob; use App\Lib\PrivateS3Disk; diff --git a/tests/Feature/Jobs/SendMissingOrderReminderJobTest.php b/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php similarity index 100% rename from tests/Feature/Jobs/SendMissingOrderReminderJobTest.php rename to tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php diff --git a/tests/Feature/Jobs/SendReminderMailTest.php b/tests/Feature/App/Jobs/SendReminderMailTest.php similarity index 100% rename from tests/Feature/Jobs/SendReminderMailTest.php rename to tests/Feature/App/Jobs/SendReminderMailTest.php diff --git a/tests/Feature/Jobs/UpdateSlidesStatusTest.php b/tests/Feature/App/Jobs/UpdateSlidesStatusTest.php similarity index 100% rename from tests/Feature/Jobs/UpdateSlidesStatusTest.php rename to tests/Feature/App/Jobs/UpdateSlidesStatusTest.php diff --git a/tests/Feature/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php b/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php similarity index 100% rename from tests/Feature/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php rename to tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php diff --git a/tests/Feature/Bo/Modules/ChangeOrderBladeTest.php b/tests/Feature/App/Views/ChangeOrderBladeTest.php similarity index 100% rename from tests/Feature/Bo/Modules/ChangeOrderBladeTest.php rename to tests/Feature/App/Views/ChangeOrderBladeTest.php diff --git a/tests/Integration/WithApp/App/Actions/Auth/DeleteOldResetTokensTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Auth/DeleteOldResetTokensTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Auth/DeleteOldResetTokensTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Auth/DeleteOldResetTokensTest.php diff --git a/tests/Integration/WithApp/App/Actions/Auth/ResetCustomerPasswordTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Auth/ResetCustomerPasswordTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php diff --git a/tests/Integration/WithApp/App/Actions/Basket/AddToBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Basket/AddToBasketTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php diff --git a/tests/Integration/WithApp/App/Actions/Basket/EmptyBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Basket/EmptyBasketTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php diff --git a/tests/Integration/WithApp/App/Actions/Basket/RemoveFromBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Basket/RemoveFromBasketTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php diff --git a/tests/Integration/WithApp/App/Actions/Common/ChangeModelOrderPositionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderPositionTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Common/ChangeModelOrderPositionTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderPositionTest.php diff --git a/tests/Integration/WithApp/App/Actions/Common/ChangeModelOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Common/ChangeModelOrderTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderTest.php diff --git a/tests/Integration/WithApp/App/Actions/Common/ExecuteMassActionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ExecuteMassActionTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Common/ExecuteMassActionTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Common/ExecuteMassActionTest.php diff --git a/tests/Integration/WithApp/App/Actions/Common/ToggleModelStarTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStarTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Common/ToggleModelStarTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStarTest.php diff --git a/tests/Integration/WithApp/App/Actions/Common/ToggleModelStatusTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStatusTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Common/ToggleModelStatusTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStatusTest.php diff --git a/tests/Integration/WithApp/App/Actions/Contact/SubmitContactFormTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Contact/SubmitContactFormTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php diff --git a/tests/Integration/WithApp/App/Actions/Crm/UnsubscribeFromNewsletterTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UnsubscribeFromNewsletterTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Crm/UnsubscribeFromNewsletterTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Crm/UnsubscribeFromNewsletterTest.php diff --git a/tests/Integration/WithApp/App/Actions/Crm/UpdateCustomerPasswordTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Crm/UpdateCustomerPasswordTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php diff --git a/tests/Integration/WithApp/App/Actions/Crm/UpdateCustomerTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Crm/UpdateCustomerTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php diff --git a/tests/Integration/WithApp/App/Actions/Customers/RegisterCustomerTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Customers/RegisterCustomerTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php diff --git a/tests/Integration/WithApp/App/Actions/Customers/UpdateCustomerLastLoginTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Customers/UpdateCustomerLastLoginTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Customers/UpdateCustomerLastLoginTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Customers/UpdateCustomerLastLoginTest.php diff --git a/tests/Integration/WithApp/App/Actions/Discounts/CreateDiscountTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Discounts/CreateDiscountTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Discounts/CreateDiscountTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Discounts/CreateDiscountTest.php diff --git a/tests/Integration/WithApp/App/Actions/Discounts/DeleteDiscountTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Discounts/DeleteDiscountTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Discounts/DeleteDiscountTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Discounts/DeleteDiscountTest.php diff --git a/tests/Integration/WithApp/App/Actions/Discounts/UpdateDiscountTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Discounts/UpdateDiscountTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Discounts/UpdateDiscountTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Discounts/UpdateDiscountTest.php diff --git a/tests/Integration/WithApp/App/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php diff --git a/tests/Integration/WithApp/App/Actions/Faqs/CreateFaqTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Faqs/CreateFaqTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Faqs/CreateFaqTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Faqs/CreateFaqTest.php diff --git a/tests/Integration/WithApp/App/Actions/Faqs/DeleteFaqTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Faqs/DeleteFaqTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Faqs/DeleteFaqTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Faqs/DeleteFaqTest.php diff --git a/tests/Integration/WithApp/App/Actions/Faqs/UpdateFaqTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Faqs/UpdateFaqTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Faqs/UpdateFaqTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Faqs/UpdateFaqTest.php diff --git a/tests/Integration/WithApp/App/Actions/Orders/ApplyPickTimeSlotTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Orders/ApplyPickTimeSlotTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php diff --git a/tests/Integration/WithApp/App/Actions/Orders/CancelOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Orders/CancelOrderTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php diff --git a/tests/Integration/WithApp/App/Actions/Orders/ClaimTodayOrderReminderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Orders/ClaimTodayOrderReminderTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php diff --git a/tests/Integration/WithApp/App/Actions/Orders/InitializeOrderTunnelTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Orders/InitializeOrderTunnelTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php diff --git a/tests/Integration/WithApp/App/Actions/Orders/PlacePendingOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Orders/PlacePendingOrderTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php diff --git a/tests/Integration/WithApp/App/Actions/Orders/ReleaseTodayOrderReminderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Orders/ReleaseTodayOrderReminderTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php diff --git a/tests/Integration/WithApp/App/Actions/Pages/UpdatePageTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Pages/UpdatePageTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Pages/UpdatePageTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Pages/UpdatePageTest.php diff --git a/tests/Integration/WithApp/App/Actions/PickupExceptions/CreatePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/PickupExceptions/CreatePickupExceptionTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php diff --git a/tests/Integration/WithApp/App/Actions/PickupExceptions/DeletePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/PickupExceptions/DeletePickupExceptionTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php diff --git a/tests/Integration/WithApp/App/Actions/PickupExceptions/UpdatePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/PickupExceptions/UpdatePickupExceptionTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php diff --git a/tests/Integration/WithApp/App/Actions/PickupExceptions/UpsertShopsPickupExceptionsForYearTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpsertShopsPickupExceptionsForYearTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/PickupExceptions/UpsertShopsPickupExceptionsForYearTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpsertShopsPickupExceptionsForYearTest.php diff --git a/tests/Integration/WithApp/App/Actions/ProductIncos/AssociateProductIncoTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/ProductIncos/AssociateProductIncoTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php diff --git a/tests/Integration/WithApp/App/Actions/ProductIncos/SyncProductIncoTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/ProductIncos/SyncProductIncoTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php diff --git a/tests/Integration/WithApp/App/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php diff --git a/tests/Integration/WithApp/App/Actions/Products/CreateProductTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Products/CreateProductTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php diff --git a/tests/Integration/WithApp/App/Actions/Products/DeleteProductTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Products/DeleteProductTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Products/DeleteProductTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Products/DeleteProductTest.php diff --git a/tests/Integration/WithApp/App/Actions/Products/UpdateProductTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Products/UpdateProductTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Products/UpdateProductTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Products/UpdateProductTest.php diff --git a/tests/Integration/WithApp/App/Actions/Ranges/CreateRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Ranges/CreateRangeTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php diff --git a/tests/Integration/WithApp/App/Actions/Ranges/DeleteRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Ranges/DeleteRangeTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php diff --git a/tests/Integration/WithApp/App/Actions/Ranges/UpdateRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Ranges/UpdateRangeTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php diff --git a/tests/Integration/WithApp/App/Actions/Settings/UpdateSettingsTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Settings/UpdateSettingsTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php diff --git a/tests/Integration/WithApp/App/Actions/Shops/CreateShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Shops/CreateShopTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php diff --git a/tests/Integration/WithApp/App/Actions/Shops/DeleteShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Shops/DeleteShopTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php diff --git a/tests/Integration/WithApp/App/Actions/Shops/UpdateShopPickupExceptionsTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Shops/UpdateShopPickupExceptionsTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php diff --git a/tests/Integration/WithApp/App/Actions/Shops/UpdateShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Shops/UpdateShopTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php diff --git a/tests/Integration/WithApp/App/Actions/Slides/CreateSlideTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Slides/CreateSlideTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Slides/CreateSlideTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Slides/CreateSlideTest.php diff --git a/tests/Integration/WithApp/App/Actions/Slides/DeleteSlideTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Slides/DeleteSlideTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Slides/DeleteSlideTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Slides/DeleteSlideTest.php diff --git a/tests/Integration/WithApp/App/Actions/Slides/UpdateSlideTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlideTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Slides/UpdateSlideTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlideTest.php diff --git a/tests/Integration/WithApp/App/Actions/Slides/UpdateSlidesStatusTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlidesStatusTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Slides/UpdateSlidesStatusTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlidesStatusTest.php diff --git a/tests/Integration/WithApp/App/Actions/Tags/CreateTagTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Tags/CreateTagTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Tags/CreateTagTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Tags/CreateTagTest.php diff --git a/tests/Integration/WithApp/App/Actions/Tags/DeleteTagTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Tags/DeleteTagTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Tags/DeleteTagTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Tags/DeleteTagTest.php diff --git a/tests/Integration/WithApp/App/Actions/Tags/UpdateTagTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Tags/UpdateTagTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Tags/UpdateTagTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Tags/UpdateTagTest.php diff --git a/tests/Integration/WithApp/App/Actions/Users/CreateUserTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Users/CreateUserTest.php similarity index 100% rename from tests/Integration/WithApp/App/Actions/Users/CreateUserTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Users/CreateUserTest.php diff --git a/tests/Integration/WithApp/App/Queries/Customers/GetCustomerByEmailQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Customers/GetCustomerByEmailQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Discounts/GetDiscountFormDataQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Discounts/GetDiscountFormDataQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Discounts/GetDiscountFormDataQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Discounts/GetDiscountFormDataQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Discounts/GetPaginatedDiscountsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Discounts/GetPaginatedDiscountsQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Discounts/GetPaginatedDiscountsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Discounts/GetPaginatedDiscountsQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Faqs/GetFaqsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Faqs/GetFaqsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Faqs/GetPaginatedFaqsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Faqs/GetPaginatedFaqsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Pages/GetPageBySlugQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Pages/GetPageBySlugQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/ProductIncos/GetProductIncoForEditQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/ProductIncos/GetProductIncoForEditQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Products/GetBoPaginatedProductsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetBoPaginatedProductsQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Products/GetBoPaginatedProductsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Products/GetBoPaginatedProductsQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Products/GetFoProductIndexPageQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoProductIndexPageQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Products/GetFoProductIndexPageQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoProductIndexPageQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Products/GetProductFormDataQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductFormDataQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Products/GetProductFormDataQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductFormDataQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Ranges/GetPaginatedRangesQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Ranges/GetPaginatedRangesQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Settings/GetSettingsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Settings/GetSettingsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Shops/GetPaginatedShopsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Shops/GetPaginatedShopsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Shops/GetShopPickupExceptionsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Shops/GetShopPickupExceptionsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Shops/GetShopQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Shops/GetShopQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopQueryTest.php diff --git a/tests/Integration/WithApp/App/Queries/Slides/GetPaginatedSlidesQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php similarity index 100% rename from tests/Integration/WithApp/App/Queries/Slides/GetPaginatedSlidesQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php From 8b9eb59b502ef71276aedff6415b7fc3fc6da211 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 13:11:20 +0100 Subject: [PATCH 129/183] test(tests): replace $this->fail with caught exception assertion in LaravelCacheLockTest --- .../Infra/Adapters/Locks/LaravelCacheLockTest.php | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tests/Integration/Standalones/Infra/Adapters/Locks/LaravelCacheLockTest.php b/tests/Integration/Standalones/Infra/Adapters/Locks/LaravelCacheLockTest.php index 3c309327..4730703e 100644 --- a/tests/Integration/Standalones/Infra/Adapters/Locks/LaravelCacheLockTest.php +++ b/tests/Integration/Standalones/Infra/Adapters/Locks/LaravelCacheLockTest.php @@ -91,13 +91,17 @@ describe('LaravelCacheLock', function (): void { $cacheLock = new LaravelCacheLock($cache); // WHEN + $caught = null; + try { $cacheLock->synchronize('test:lock:wrapped', fn (): string => 'never', 30, 5); - $this->fail('Expected LockTimeoutException was not thrown.'); } catch (LockTimeoutException $e) { - // THEN - expect($e->getMessage())->toBe('Timed out') - ->and($e->getPrevious())->toBeInstanceOf(LaravelLockTimeoutException::class); + $caught = $e; } + + // THEN + expect($caught)->toBeInstanceOf(LockTimeoutException::class) + ->and($caught?->getMessage())->toBe('Timed out') + ->and($caught?->getPrevious())->toBeInstanceOf(LaravelLockTimeoutException::class); }); }); From 588a93cbcf53c9902cb3e5b460b8c0130bc94ca8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 14:18:42 +0100 Subject: [PATCH 130/183] test(tests): add PSR-4 namespaces to Unit test files --- .../Cqs/Actions/Common/ChangeModelOrderPositionInputTest.php | 2 ++ .../Unit/App/Cqs/Actions/Common/ExecuteMassActionInputTest.php | 2 ++ .../App/Cqs/Actions/Customers/RegisterCustomerInputTest.php | 2 ++ .../Unit/App/Cqs/Actions/Employee/ImportEmployeesInputTest.php | 2 ++ .../Unit/App/Cqs/Actions/Employee/ImportEmployeesOutputTest.php | 2 ++ tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesTest.php | 2 ++ tests/Unit/App/Cqs/Actions/Faqs/CreateFaqInputTest.php | 2 ++ tests/Unit/App/Cqs/Actions/Faqs/UpdateFaqInputTest.php | 2 ++ tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php | 2 ++ tests/Unit/App/Cqs/Actions/Orders/CancelOrderTest.php | 2 ++ tests/Unit/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php | 2 ++ tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php | 2 ++ tests/Unit/App/Cqs/Actions/Pages/UpdatePageInputTest.php | 2 ++ .../Actions/PickupExceptions/CreatePickupExceptionInputTest.php | 2 ++ .../Actions/PickupExceptions/UpdatePickupExceptionInputTest.php | 2 ++ tests/Unit/App/Cqs/Actions/Settings/UpdateSettingsInputTest.php | 2 ++ tests/Unit/App/Cqs/Actions/Shops/CreateShopInputTest.php | 2 ++ tests/Unit/App/Cqs/Actions/Shops/UpdateShopInputTest.php | 2 ++ .../Cqs/Actions/Shops/UpdateShopPickupExceptionsInputTest.php | 2 ++ tests/Unit/App/Cqs/Actions/Slides/UpdateSlideInputTest.php | 2 ++ tests/Unit/App/Cqs/Actions/Tags/CreateTagInputTest.php | 2 ++ tests/Unit/App/Cqs/Actions/Tags/UpdateTagInputTest.php | 2 ++ tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php | 2 ++ .../App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php | 2 ++ tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php | 2 ++ tests/Unit/App/Dto/ProductDtoTest.php | 2 ++ tests/Unit/App/Dto/ProductIncoDtoTest.php | 2 ++ tests/Unit/App/Dto/SettingDtoTest.php | 2 ++ tests/Unit/App/Dto/ShopDtoTest.php | 2 ++ .../Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php | 2 ++ .../Orders/InvalidateOrderBuilderOnBasketChangeTest.php | 2 ++ tests/Unit/App/Policies/Backend/DiscountPolicyTest.php | 2 ++ tests/Unit/App/Policies/Backend/FaqPolicyTest.php | 2 ++ tests/Unit/App/Policies/Backend/OrderPolicyTest.php | 2 ++ tests/Unit/App/Policies/Backend/PagePolicyTest.php | 2 ++ tests/Unit/App/Policies/Backend/PickupExceptionPolicyTest.php | 2 ++ tests/Unit/App/Policies/Backend/ProductPolicyTest.php | 2 ++ tests/Unit/App/Policies/Backend/RangePolicyTest.php | 2 ++ tests/Unit/App/Policies/Backend/ShopPolicyTest.php | 2 ++ tests/Unit/App/Policies/Backend/SlidePolicyTest.php | 2 ++ tests/Unit/App/Policies/Backend/TagPolicyTest.php | 2 ++ tests/Unit/App/Policies/Frontend/BasketPolicyTest.php | 2 ++ tests/Unit/App/Policies/Frontend/CustomerPolicyTest.php | 2 ++ tests/Unit/App/Policies/Frontend/OrderPolicyTest.php | 2 ++ tests/Unit/App/Policies/Frontend/OrderTunnelStepPolicyTest.php | 2 ++ tests/Unit/App/Policies/Frontend/ProductPolicyTest.php | 2 ++ tests/Unit/App/Policies/Frontend/ShopPolicyTest.php | 2 ++ tests/Unit/App/Services/EmployeeCsvImportLineTest.php | 2 ++ tests/Unit/App/Services/EmployeeCsvReaderServiceTest.php | 2 ++ tests/Unit/App/Services/IcsGeneratorServiceTest.php | 2 ++ tests/Unit/App/Services/MapUrlServiceTest.php | 2 ++ tests/Unit/Domain/Builders/OrderBuilderTest.php | 2 ++ tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php | 2 ++ tests/Unit/Domain/Events/BasketRemovedTest.php | 2 ++ tests/Unit/Domain/Models/ValueObjects/CoordinatesTest.php | 2 ++ tests/Unit/Domain/Models/ValueObjects/DatePeriodTest.php | 2 ++ tests/Unit/Domain/Models/ValueObjects/DiscountRateTest.php | 2 ++ tests/Unit/Domain/Models/ValueObjects/IcsContentTest.php | 2 ++ tests/Unit/Domain/Models/ValueObjects/PhoneNumberTest.php | 2 ++ tests/Unit/Domain/Models/ValueObjects/PictureMetadataTest.php | 2 ++ tests/Unit/Domain/Models/ValueObjects/SeoMetadataTest.php | 2 ++ tests/Unit/Domain/Models/ValueObjects/SlugTest.php | 2 ++ tests/Unit/Domain/Services/PickupSchedulingServiceTest.php | 2 ++ tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php | 2 ++ tests/Unit/Infra/Adapters/Services/CsvGeneratorImplTest.php | 2 ++ 65 files changed, 130 insertions(+) diff --git a/tests/Unit/App/Cqs/Actions/Common/ChangeModelOrderPositionInputTest.php b/tests/Unit/App/Cqs/Actions/Common/ChangeModelOrderPositionInputTest.php index 4a681f65..ec2ae4d6 100644 --- a/tests/Unit/App/Cqs/Actions/Common/ChangeModelOrderPositionInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Common/ChangeModelOrderPositionInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Common; + use App\Cqs\Actions\Common\ChangeModelOrderPositionInput; use App\Interfaces\ModelWithOrder; use Illuminate\Database\Eloquent\Model; diff --git a/tests/Unit/App/Cqs/Actions/Common/ExecuteMassActionInputTest.php b/tests/Unit/App/Cqs/Actions/Common/ExecuteMassActionInputTest.php index cb1a478d..76cf5cfa 100644 --- a/tests/Unit/App/Cqs/Actions/Common/ExecuteMassActionInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Common/ExecuteMassActionInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Common; + use App\Cqs\Actions\Common\ExecuteMassActionInput; use App\Enums\MassActionType; use App\Models\Product; diff --git a/tests/Unit/App/Cqs/Actions/Customers/RegisterCustomerInputTest.php b/tests/Unit/App/Cqs/Actions/Customers/RegisterCustomerInputTest.php index ece9b841..8604dc8d 100644 --- a/tests/Unit/App/Cqs/Actions/Customers/RegisterCustomerInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Customers/RegisterCustomerInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Customers; + use App\Cqs\Actions\Customers\RegisterCustomerInput; use Domain\Models\ValueObjects\Code; use Domain\Models\ValueObjects\Email; diff --git a/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesInputTest.php b/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesInputTest.php index d5a66597..ba9feab8 100644 --- a/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Employee; + use App\Cqs\Actions\Employee\ImportEmployeesInput; describe('ImportEmployeesInput', function (): void { diff --git a/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesOutputTest.php b/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesOutputTest.php index c1d46b69..3e74e6a1 100644 --- a/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesOutputTest.php +++ b/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesOutputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Employee; + use App\Cqs\Actions\Employee\ImportEmployeesOutput; describe('ImportEmployeesOutput', function (): void { diff --git a/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesTest.php b/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesTest.php index 3f2ded1a..5da46190 100644 --- a/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesTest.php +++ b/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Employee; + use App\Contracts\ActionInput; use App\Cqs\Actions\Employee\ImportEmployees; use App\Cqs\Actions\Employee\ImportEmployeesInput; diff --git a/tests/Unit/App/Cqs/Actions/Faqs/CreateFaqInputTest.php b/tests/Unit/App/Cqs/Actions/Faqs/CreateFaqInputTest.php index 5b0bf469..a7157397 100644 --- a/tests/Unit/App/Cqs/Actions/Faqs/CreateFaqInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Faqs/CreateFaqInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Faqs; + use App\Cqs\Actions\Faqs\CreateFaqInput; describe('CreateFaqInput', function (): void { diff --git a/tests/Unit/App/Cqs/Actions/Faqs/UpdateFaqInputTest.php b/tests/Unit/App/Cqs/Actions/Faqs/UpdateFaqInputTest.php index 1cdd118d..b605f2f8 100644 --- a/tests/Unit/App/Cqs/Actions/Faqs/UpdateFaqInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Faqs/UpdateFaqInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Faqs; + use App\Cqs\Actions\Faqs\UpdateFaqInput; use App\Models\Faq; diff --git a/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php b/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php index 6ab9c7cc..1941d543 100644 --- a/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php +++ b/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Orders; + use App\Cqs\Actions\Orders\ApplyPickTimeSlot; use App\Cqs\Actions\Orders\ApplyPickTimeSlotInput; use App\Cqs\Actions\Orders\ApplyPickTimeSlotOutput; diff --git a/tests/Unit/App/Cqs/Actions/Orders/CancelOrderTest.php b/tests/Unit/App/Cqs/Actions/Orders/CancelOrderTest.php index c45b670f..3786e299 100644 --- a/tests/Unit/App/Cqs/Actions/Orders/CancelOrderTest.php +++ b/tests/Unit/App/Cqs/Actions/Orders/CancelOrderTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Orders; + use App\Cqs\Actions\Orders\CancelOrder; use App\Cqs\Actions\Orders\CancelOrderInput; use App\Cqs\Actions\Orders\CancelOrderOutput; diff --git a/tests/Unit/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php b/tests/Unit/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php index 40d840b9..ea02acaa 100644 --- a/tests/Unit/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php +++ b/tests/Unit/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Orders; + use App\Cqs\Actions\Orders\InitializeOrderTunnel; use App\Cqs\Actions\Orders\InitializeOrderTunnelInput; use Domain\Models\Entities\Basket; diff --git a/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php index a2ef604c..dae2a4d5 100644 --- a/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php +++ b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Orders; + use App\Attributes\Locked; use App\Attributes\WithoutTransaction; use App\Contracts\HandlesFailure; diff --git a/tests/Unit/App/Cqs/Actions/Pages/UpdatePageInputTest.php b/tests/Unit/App/Cqs/Actions/Pages/UpdatePageInputTest.php index 27e6e2fa..b220de5f 100644 --- a/tests/Unit/App/Cqs/Actions/Pages/UpdatePageInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Pages/UpdatePageInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Pages; + use App\Cqs\Actions\Pages\UpdatePageInput; use App\Models\Page; use Domain\Models\ValueObjects\SeoMetadata; diff --git a/tests/Unit/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionInputTest.php b/tests/Unit/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionInputTest.php index dba30af5..926c3e35 100644 --- a/tests/Unit/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionInputTest.php +++ b/tests/Unit/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\PickupExceptions; + use App\Cqs\Actions\PickupExceptions\CreatePickupExceptionInput; use Domain\Enums\RepeatFrequency; diff --git a/tests/Unit/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionInputTest.php b/tests/Unit/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionInputTest.php index 372ffc1e..a5910d6e 100644 --- a/tests/Unit/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionInputTest.php +++ b/tests/Unit/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\PickupExceptions; + use App\Cqs\Actions\PickupExceptions\UpdatePickupExceptionInput; use App\Models\PickupException; use Domain\Enums\RepeatFrequency; diff --git a/tests/Unit/App/Cqs/Actions/Settings/UpdateSettingsInputTest.php b/tests/Unit/App/Cqs/Actions/Settings/UpdateSettingsInputTest.php index 2acc7d88..5123ad9f 100644 --- a/tests/Unit/App/Cqs/Actions/Settings/UpdateSettingsInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Settings/UpdateSettingsInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Settings; + use App\Cqs\Actions\Settings\UpdateSettingsInput; use Domain\Models\ValueObjects\ShopperSiteCode; diff --git a/tests/Unit/App/Cqs/Actions/Shops/CreateShopInputTest.php b/tests/Unit/App/Cqs/Actions/Shops/CreateShopInputTest.php index 6c670ff9..a7e78459 100644 --- a/tests/Unit/App/Cqs/Actions/Shops/CreateShopInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Shops/CreateShopInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Shops; + use App\Cqs\Actions\Shops\CreateShopInput; use Domain\Models\ValueObjects\Coordinates; use Domain\Models\ValueObjects\PhoneNumber; diff --git a/tests/Unit/App/Cqs/Actions/Shops/UpdateShopInputTest.php b/tests/Unit/App/Cqs/Actions/Shops/UpdateShopInputTest.php index 4ed21ca4..942fbdab 100644 --- a/tests/Unit/App/Cqs/Actions/Shops/UpdateShopInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Shops/UpdateShopInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Shops; + use App\Cqs\Actions\Shops\UpdateShopInput; use App\Models\Shop; use Domain\Models\ValueObjects\Coordinates; diff --git a/tests/Unit/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsInputTest.php b/tests/Unit/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsInputTest.php index 26e57294..dde4840b 100644 --- a/tests/Unit/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Shops; + use App\Cqs\Actions\Shops\UpdateShopPickupExceptionsInput; use App\Models\Shop; diff --git a/tests/Unit/App/Cqs/Actions/Slides/UpdateSlideInputTest.php b/tests/Unit/App/Cqs/Actions/Slides/UpdateSlideInputTest.php index 43da336a..3cb2636b 100644 --- a/tests/Unit/App/Cqs/Actions/Slides/UpdateSlideInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Slides/UpdateSlideInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Slides; + use App\Cqs\Actions\Slides\UpdateSlideInput; use App\Models\Slide; diff --git a/tests/Unit/App/Cqs/Actions/Tags/CreateTagInputTest.php b/tests/Unit/App/Cqs/Actions/Tags/CreateTagInputTest.php index 2f375487..fcd838da 100644 --- a/tests/Unit/App/Cqs/Actions/Tags/CreateTagInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Tags/CreateTagInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Tags; + use App\Cqs\Actions\Tags\CreateTagInput; describe('CreateTagInput', function (): void { diff --git a/tests/Unit/App/Cqs/Actions/Tags/UpdateTagInputTest.php b/tests/Unit/App/Cqs/Actions/Tags/UpdateTagInputTest.php index 3993ce1b..11f4606a 100644 --- a/tests/Unit/App/Cqs/Actions/Tags/UpdateTagInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Tags/UpdateTagInputTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Actions\Tags; + use App\Cqs\Actions\Tags\UpdateTagInput; use App\Models\Tag; diff --git a/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php index 10848093..5252eab3 100644 --- a/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php +++ b/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Queries\Orders; + use App\Cqs\Queries\Orders\GetBasketSummaryQuery; use App\Cqs\Queries\Orders\GetBasketSummaryQueryInput; use App\Cqs\Queries\Orders\GetBasketSummaryQueryOutput; diff --git a/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php index 4f22509e..2c78f3a4 100644 --- a/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php +++ b/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Queries\Orders; + use App\Cqs\Queries\Orders\GetOrderConfirmationQuery; use App\Cqs\Queries\Orders\GetOrderConfirmationQueryInput; use App\Cqs\Queries\Orders\GetOrderConfirmationQueryOutput; diff --git a/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php index d0ce32bb..b23aebaa 100644 --- a/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php +++ b/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Cqs\Queries\Orders; + use App\Cqs\Queries\Orders\GetPickTimeSlotQuery; use App\Cqs\Queries\Orders\GetPickTimeSlotQueryInput; use App\Cqs\Queries\Orders\GetPickTimeSlotQueryOutput; diff --git a/tests/Unit/App/Dto/ProductDtoTest.php b/tests/Unit/App/Dto/ProductDtoTest.php index 547e3884..239690ee 100644 --- a/tests/Unit/App/Dto/ProductDtoTest.php +++ b/tests/Unit/App/Dto/ProductDtoTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Dto; + use App\Dto\ProductDto; describe('ProductDto', function () { diff --git a/tests/Unit/App/Dto/ProductIncoDtoTest.php b/tests/Unit/App/Dto/ProductIncoDtoTest.php index e43bc134..d03820b0 100644 --- a/tests/Unit/App/Dto/ProductIncoDtoTest.php +++ b/tests/Unit/App/Dto/ProductIncoDtoTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Dto; + use App\Dto\ProductIncoDto; use Domain\Enums\Nutriscore; use Domain\Models\ValueObjects\NutritionalValues; diff --git a/tests/Unit/App/Dto/SettingDtoTest.php b/tests/Unit/App/Dto/SettingDtoTest.php index e241786b..779f81a6 100644 --- a/tests/Unit/App/Dto/SettingDtoTest.php +++ b/tests/Unit/App/Dto/SettingDtoTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Dto; + use App\Dto\SettingDto; use Domain\Models\ValueObjects\ShopperSiteCode; diff --git a/tests/Unit/App/Dto/ShopDtoTest.php b/tests/Unit/App/Dto/ShopDtoTest.php index 0b8b782b..d9d89ccf 100644 --- a/tests/Unit/App/Dto/ShopDtoTest.php +++ b/tests/Unit/App/Dto/ShopDtoTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Dto; + use App\Dto\ShopDto; use Domain\Models\Entities\Shop; use Domain\Models\ValueObjects\Entities\ShopId; diff --git a/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php b/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php index 99431d0a..f1ac0501 100644 --- a/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php +++ b/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Listeners\Orders; + use App\Listeners\Orders\EmptyBasketOnOrderPlaced; use Domain\Enums\Units\OrderUnit; use Domain\Events\AnOrderHasBeenPlaced; diff --git a/tests/Unit/App/Listeners/Orders/InvalidateOrderBuilderOnBasketChangeTest.php b/tests/Unit/App/Listeners/Orders/InvalidateOrderBuilderOnBasketChangeTest.php index a8284537..6709f8a4 100644 --- a/tests/Unit/App/Listeners/Orders/InvalidateOrderBuilderOnBasketChangeTest.php +++ b/tests/Unit/App/Listeners/Orders/InvalidateOrderBuilderOnBasketChangeTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Listeners\Orders; + use App\Listeners\Orders\InvalidateOrderBuilderOnBasketChange; use Domain\Events\BasketHasBeenModified; use Domain\Events\BasketRemoved; diff --git a/tests/Unit/App/Policies/Backend/DiscountPolicyTest.php b/tests/Unit/App/Policies/Backend/DiscountPolicyTest.php index 4cb45afe..1d28c39b 100644 --- a/tests/Unit/App/Policies/Backend/DiscountPolicyTest.php +++ b/tests/Unit/App/Policies/Backend/DiscountPolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Backend; + use App\Models\Customer; use App\Models\Discount; use App\Models\User; diff --git a/tests/Unit/App/Policies/Backend/FaqPolicyTest.php b/tests/Unit/App/Policies/Backend/FaqPolicyTest.php index e73b51f7..28788866 100644 --- a/tests/Unit/App/Policies/Backend/FaqPolicyTest.php +++ b/tests/Unit/App/Policies/Backend/FaqPolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Backend; + use App\Models\Customer; use App\Models\Faq; use App\Models\User; diff --git a/tests/Unit/App/Policies/Backend/OrderPolicyTest.php b/tests/Unit/App/Policies/Backend/OrderPolicyTest.php index da841eec..178cb410 100644 --- a/tests/Unit/App/Policies/Backend/OrderPolicyTest.php +++ b/tests/Unit/App/Policies/Backend/OrderPolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Backend; + use App\Models\Customer; use App\Models\Order; use App\Models\User; diff --git a/tests/Unit/App/Policies/Backend/PagePolicyTest.php b/tests/Unit/App/Policies/Backend/PagePolicyTest.php index 30b755f7..498b7de1 100644 --- a/tests/Unit/App/Policies/Backend/PagePolicyTest.php +++ b/tests/Unit/App/Policies/Backend/PagePolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Backend; + use App\Dto\PageDto; use App\Models\Customer; use App\Models\Page; diff --git a/tests/Unit/App/Policies/Backend/PickupExceptionPolicyTest.php b/tests/Unit/App/Policies/Backend/PickupExceptionPolicyTest.php index d2d215b0..85c57c15 100644 --- a/tests/Unit/App/Policies/Backend/PickupExceptionPolicyTest.php +++ b/tests/Unit/App/Policies/Backend/PickupExceptionPolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Backend; + use App\Dto\PickupExceptionDto; use App\Models\Customer; use App\Models\PickupException; diff --git a/tests/Unit/App/Policies/Backend/ProductPolicyTest.php b/tests/Unit/App/Policies/Backend/ProductPolicyTest.php index 0507393b..0fef3a31 100644 --- a/tests/Unit/App/Policies/Backend/ProductPolicyTest.php +++ b/tests/Unit/App/Policies/Backend/ProductPolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Backend; + use App\Models\Customer; use App\Models\Product; use App\Models\User; diff --git a/tests/Unit/App/Policies/Backend/RangePolicyTest.php b/tests/Unit/App/Policies/Backend/RangePolicyTest.php index ff82dd8d..0a2efc5f 100644 --- a/tests/Unit/App/Policies/Backend/RangePolicyTest.php +++ b/tests/Unit/App/Policies/Backend/RangePolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Backend; + use App\Dto\RangeDto; use App\Models\Customer; use App\Models\Range; diff --git a/tests/Unit/App/Policies/Backend/ShopPolicyTest.php b/tests/Unit/App/Policies/Backend/ShopPolicyTest.php index a08b7fc0..19291b3f 100644 --- a/tests/Unit/App/Policies/Backend/ShopPolicyTest.php +++ b/tests/Unit/App/Policies/Backend/ShopPolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Backend; + use App\Models\Customer; use App\Models\Shop; use App\Models\User; diff --git a/tests/Unit/App/Policies/Backend/SlidePolicyTest.php b/tests/Unit/App/Policies/Backend/SlidePolicyTest.php index 0c6802c1..f318d2e2 100644 --- a/tests/Unit/App/Policies/Backend/SlidePolicyTest.php +++ b/tests/Unit/App/Policies/Backend/SlidePolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Backend; + use App\Dto\SlideDto; use App\Models\Customer; use App\Models\Slide; diff --git a/tests/Unit/App/Policies/Backend/TagPolicyTest.php b/tests/Unit/App/Policies/Backend/TagPolicyTest.php index f956b8ca..c920b3e7 100644 --- a/tests/Unit/App/Policies/Backend/TagPolicyTest.php +++ b/tests/Unit/App/Policies/Backend/TagPolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Backend; + use App\Models\Customer; use App\Models\Tag; use App\Models\User; diff --git a/tests/Unit/App/Policies/Frontend/BasketPolicyTest.php b/tests/Unit/App/Policies/Frontend/BasketPolicyTest.php index 1b790446..1c9db103 100644 --- a/tests/Unit/App/Policies/Frontend/BasketPolicyTest.php +++ b/tests/Unit/App/Policies/Frontend/BasketPolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Frontend; + use App\Dto\BasketProductDto; use App\Models\Customer; use App\Models\User; diff --git a/tests/Unit/App/Policies/Frontend/CustomerPolicyTest.php b/tests/Unit/App/Policies/Frontend/CustomerPolicyTest.php index ad2bfd30..84be3e06 100644 --- a/tests/Unit/App/Policies/Frontend/CustomerPolicyTest.php +++ b/tests/Unit/App/Policies/Frontend/CustomerPolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Frontend; + use App\Models\Customer; use App\Models\User; use App\Policies\Frontend\CustomerPolicy; diff --git a/tests/Unit/App/Policies/Frontend/OrderPolicyTest.php b/tests/Unit/App/Policies/Frontend/OrderPolicyTest.php index 9d87cfe3..122d68f0 100644 --- a/tests/Unit/App/Policies/Frontend/OrderPolicyTest.php +++ b/tests/Unit/App/Policies/Frontend/OrderPolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Frontend; + use App\Models\Customer; use App\Models\Order; use App\Models\User; diff --git a/tests/Unit/App/Policies/Frontend/OrderTunnelStepPolicyTest.php b/tests/Unit/App/Policies/Frontend/OrderTunnelStepPolicyTest.php index 313fbd66..4d51cafa 100644 --- a/tests/Unit/App/Policies/Frontend/OrderTunnelStepPolicyTest.php +++ b/tests/Unit/App/Policies/Frontend/OrderTunnelStepPolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Frontend; + use App\Models\Customer; use App\Models\User; use App\Policies\Frontend\OrderTunnelStepPolicy; diff --git a/tests/Unit/App/Policies/Frontend/ProductPolicyTest.php b/tests/Unit/App/Policies/Frontend/ProductPolicyTest.php index e433f41b..aaf20c3a 100644 --- a/tests/Unit/App/Policies/Frontend/ProductPolicyTest.php +++ b/tests/Unit/App/Policies/Frontend/ProductPolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Frontend; + use App\Dto\ProductDto; use App\Dto\ProductPricingDto; use App\Dto\ProductWithPricingDto; diff --git a/tests/Unit/App/Policies/Frontend/ShopPolicyTest.php b/tests/Unit/App/Policies/Frontend/ShopPolicyTest.php index 56d3f4e1..2d2e8c9f 100644 --- a/tests/Unit/App/Policies/Frontend/ShopPolicyTest.php +++ b/tests/Unit/App/Policies/Frontend/ShopPolicyTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Frontend; + use App\Models\Customer; use App\Models\Shop; use App\Models\User; diff --git a/tests/Unit/App/Services/EmployeeCsvImportLineTest.php b/tests/Unit/App/Services/EmployeeCsvImportLineTest.php index 07502b08..c2f7945c 100644 --- a/tests/Unit/App/Services/EmployeeCsvImportLineTest.php +++ b/tests/Unit/App/Services/EmployeeCsvImportLineTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Services; + use App\Services\EmployeeCsvImportLineService; describe('EmployeeCsvImportLineService', function (): void { diff --git a/tests/Unit/App/Services/EmployeeCsvReaderServiceTest.php b/tests/Unit/App/Services/EmployeeCsvReaderServiceTest.php index cca4d72f..8dd11894 100644 --- a/tests/Unit/App/Services/EmployeeCsvReaderServiceTest.php +++ b/tests/Unit/App/Services/EmployeeCsvReaderServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Services; + use App\Services\EmployeeCsvImportLineService; use App\Services\EmployeeCsvReaderService; use Psr\Log\LoggerInterface; diff --git a/tests/Unit/App/Services/IcsGeneratorServiceTest.php b/tests/Unit/App/Services/IcsGeneratorServiceTest.php index 33f6b43d..9127f116 100644 --- a/tests/Unit/App/Services/IcsGeneratorServiceTest.php +++ b/tests/Unit/App/Services/IcsGeneratorServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Services; + use App\Dto\IcsContentDto; use App\Services\IcsGeneratorService; use Carbon\Carbon; diff --git a/tests/Unit/App/Services/MapUrlServiceTest.php b/tests/Unit/App/Services/MapUrlServiceTest.php index a7a91f62..c85bbdfd 100644 --- a/tests/Unit/App/Services/MapUrlServiceTest.php +++ b/tests/Unit/App/Services/MapUrlServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\App\Services; + use App\Dto\ShopDto; use App\Services\MapUrlService; use Domain\Models\ValueObjects\DeliveryAddress; diff --git a/tests/Unit/Domain/Builders/OrderBuilderTest.php b/tests/Unit/Domain/Builders/OrderBuilderTest.php index 84030964..246146c3 100644 --- a/tests/Unit/Domain/Builders/OrderBuilderTest.php +++ b/tests/Unit/Domain/Builders/OrderBuilderTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\Domain\Builders; + use Domain\Builders\BasketOrderBuilder; use Domain\Builders\CompletedOrderBuilder; use Domain\Builders\OrderBuilder; diff --git a/tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php b/tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php index dea9fd02..3017f81d 100644 --- a/tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php +++ b/tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\Domain\Events; + use Domain\Events\BasketHasBeenModified; use Domain\Models\ValueObjects\Entities\BasketId; use Ramsey\Uuid\Uuid; diff --git a/tests/Unit/Domain/Events/BasketRemovedTest.php b/tests/Unit/Domain/Events/BasketRemovedTest.php index ce618e54..bfcd4e00 100644 --- a/tests/Unit/Domain/Events/BasketRemovedTest.php +++ b/tests/Unit/Domain/Events/BasketRemovedTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\Domain\Events; + use Domain\Events\BasketRemoved; use Domain\Models\ValueObjects\Entities\BasketId; use Ramsey\Uuid\Uuid; diff --git a/tests/Unit/Domain/Models/ValueObjects/CoordinatesTest.php b/tests/Unit/Domain/Models/ValueObjects/CoordinatesTest.php index 0338565d..17c39d05 100644 --- a/tests/Unit/Domain/Models/ValueObjects/CoordinatesTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/CoordinatesTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\Domain\Models\ValueObjects; + use Domain\Models\ValueObjects\Coordinates; describe('Coordinates Value Object', function () { diff --git a/tests/Unit/Domain/Models/ValueObjects/DatePeriodTest.php b/tests/Unit/Domain/Models/ValueObjects/DatePeriodTest.php index 29518f99..f84da589 100644 --- a/tests/Unit/Domain/Models/ValueObjects/DatePeriodTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/DatePeriodTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\Domain\Models\ValueObjects; + use Domain\Models\ValueObjects\DatePeriod; describe('DatePeriod', function (): void { diff --git a/tests/Unit/Domain/Models/ValueObjects/DiscountRateTest.php b/tests/Unit/Domain/Models/ValueObjects/DiscountRateTest.php index 5072582c..4debbc86 100644 --- a/tests/Unit/Domain/Models/ValueObjects/DiscountRateTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/DiscountRateTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\Domain\Models\ValueObjects; + use Domain\Models\ValueObjects\DiscountRate; use Money\Money; diff --git a/tests/Unit/Domain/Models/ValueObjects/IcsContentTest.php b/tests/Unit/Domain/Models/ValueObjects/IcsContentTest.php index 48111fa5..5a3cb955 100644 --- a/tests/Unit/Domain/Models/ValueObjects/IcsContentTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/IcsContentTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\Domain\Models\ValueObjects; + use Domain\Models\ValueObjects\IcsContent; describe('IcsContent', function (): void { diff --git a/tests/Unit/Domain/Models/ValueObjects/PhoneNumberTest.php b/tests/Unit/Domain/Models/ValueObjects/PhoneNumberTest.php index d63099b5..1de2f919 100644 --- a/tests/Unit/Domain/Models/ValueObjects/PhoneNumberTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/PhoneNumberTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\Domain\Models\ValueObjects; + use Domain\Models\ValueObjects\PhoneNumber; describe('PhoneNumber Value Object', function () { diff --git a/tests/Unit/Domain/Models/ValueObjects/PictureMetadataTest.php b/tests/Unit/Domain/Models/ValueObjects/PictureMetadataTest.php index 1cb03777..262b8716 100644 --- a/tests/Unit/Domain/Models/ValueObjects/PictureMetadataTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/PictureMetadataTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\Domain\Models\ValueObjects; + use Domain\Models\ValueObjects\PictureMetadata; describe('PictureMetadata Value Object', function () { diff --git a/tests/Unit/Domain/Models/ValueObjects/SeoMetadataTest.php b/tests/Unit/Domain/Models/ValueObjects/SeoMetadataTest.php index 241d7c7e..ccef60a1 100644 --- a/tests/Unit/Domain/Models/ValueObjects/SeoMetadataTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/SeoMetadataTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\Domain\Models\ValueObjects; + use Domain\Models\ValueObjects\SeoMetadata; describe('SeoMetadata', function (): void { diff --git a/tests/Unit/Domain/Models/ValueObjects/SlugTest.php b/tests/Unit/Domain/Models/ValueObjects/SlugTest.php index 6e817f55..8514be27 100644 --- a/tests/Unit/Domain/Models/ValueObjects/SlugTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/SlugTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\Domain\Models\ValueObjects; + use Domain\Models\ValueObjects\Slug; describe('Slug Value Object', function () { diff --git a/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php b/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php index 66a821ce..b060c278 100644 --- a/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php +++ b/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\Domain\Services; + use Carbon\CarbonImmutable; use Carbon\WeekDay; use Domain\Enums\RepeatFrequency; diff --git a/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php b/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php index 65aadb0d..447a4145 100644 --- a/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php +++ b/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\Infra\Adapters\Serializers; + use Domain\Enums\ProductBrand; use Domain\Enums\TaxRate; use Domain\Enums\Units\OrderUnit; diff --git a/tests/Unit/Infra/Adapters/Services/CsvGeneratorImplTest.php b/tests/Unit/Infra/Adapters/Services/CsvGeneratorImplTest.php index b577f8aa..effa80b2 100644 --- a/tests/Unit/Infra/Adapters/Services/CsvGeneratorImplTest.php +++ b/tests/Unit/Infra/Adapters/Services/CsvGeneratorImplTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Unit\Infra\Adapters\Services; + use Infrastructure\Adapters\Services\CsvGeneratorImpl; describe('CsvGeneratorImpl', function () { From a87e5a0c94f69bfda476f7d932fe41058905797e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 14:19:02 +0100 Subject: [PATCH 131/183] test(tests): add unit tests for Pagination value object --- .../{ => Adapters}/Repositories/SessionBasketRepositoryTest.php | 2 +- .../ValueObjects => Shared/Pagination}/PaginationTest.php | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename tests/Integration/WithApp/Infra/{ => Adapters}/Repositories/SessionBasketRepositoryTest.php (98%) rename tests/Unit/{Domain/Models/ValueObjects => Shared/Pagination}/PaginationTest.php (100%) diff --git a/tests/Integration/WithApp/Infra/Repositories/SessionBasketRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php similarity index 98% rename from tests/Integration/WithApp/Infra/Repositories/SessionBasketRepositoryTest.php rename to tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php index 1d80834e..dc0ffafd 100644 --- a/tests/Integration/WithApp/Infra/Repositories/SessionBasketRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Tests\Integration\WithApp\Infra\Repositories\SessionBasketRepositoryTest; +namespace Tests\Integration\WithApp\Infra\Adapters\Repositories; use Domain\Enums\ProductBrand; use Domain\Enums\TaxRate; diff --git a/tests/Unit/Domain/Models/ValueObjects/PaginationTest.php b/tests/Unit/Shared/Pagination/PaginationTest.php similarity index 100% rename from tests/Unit/Domain/Models/ValueObjects/PaginationTest.php rename to tests/Unit/Shared/Pagination/PaginationTest.php From cdb30e2f7073d32c2f04e62bf060f9bc74fd33fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 14:21:17 +0100 Subject: [PATCH 132/183] test(tests): add PSR-4 namespaces to Integration test files --- tests/Integration/WithApp/App/Auth/CrmUserProviderTest.php | 2 ++ tests/Integration/WithApp/App/Casts/CalendarDateCastTest.php | 2 ++ tests/Integration/WithApp/App/Casts/CodeCastTest.php | 2 ++ tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php | 2 ++ tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php | 2 ++ tests/Integration/WithApp/App/Casts/EmailCastTest.php | 2 ++ tests/Integration/WithApp/App/Casts/EmployeeSitesCastTest.php | 2 ++ tests/Integration/WithApp/App/Casts/MatriculeCastTest.php | 2 ++ tests/Integration/WithApp/App/Casts/MoneyCastTest.php | 2 ++ .../Integration/WithApp/App/Casts/NutritionalValuesCastTest.php | 2 ++ tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php | 2 ++ .../Integration/WithApp/App/Casts/OrderLineProductCastTest.php | 2 ++ tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php | 2 ++ .../WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php | 2 ++ .../WithApp/App/Casts/ShopperServiceCodeCastTest.php | 2 ++ tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php | 2 ++ tests/Integration/WithApp/App/Casts/UtcDatetimeCastTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Auth/DeleteOldResetTokensTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php | 2 ++ .../App/Cqs/Actions/Common/ChangeModelOrderPositionTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Common/ChangeModelOrderTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Common/ExecuteMassActionTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Common/ToggleModelStarTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Common/ToggleModelStatusTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php | 2 ++ .../App/Cqs/Actions/Crm/UnsubscribeFromNewsletterTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php | 2 ++ .../App/Cqs/Actions/Customers/UpdateCustomerLastLoginTest.php | 2 ++ .../Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php | 2 ++ .../Integration/WithApp/App/Cqs/Actions/Faqs/CreateFaqTest.php | 2 ++ .../Integration/WithApp/App/Cqs/Actions/Faqs/DeleteFaqTest.php | 2 ++ .../Integration/WithApp/App/Cqs/Actions/Faqs/UpdateFaqTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php | 2 ++ .../App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php | 2 ++ .../App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php | 2 ++ .../App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Pages/UpdatePageTest.php | 2 ++ .../Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php | 2 ++ .../Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php | 2 ++ .../Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php | 2 ++ .../PickupExceptions/UpsertShopsPickupExceptionsForYearTest.php | 2 ++ .../App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php | 2 ++ .../App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php | 2 ++ .../ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Products/CreateProductTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Products/DeleteProductTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Products/UpdateProductTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Shops/CreateShopTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php | 2 ++ .../App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Slides/CreateSlideTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Slides/DeleteSlideTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Slides/UpdateSlideTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Slides/UpdateSlidesStatusTest.php | 2 ++ .../Integration/WithApp/App/Cqs/Actions/Tags/CreateTagTest.php | 2 ++ .../Integration/WithApp/App/Cqs/Actions/Tags/DeleteTagTest.php | 2 ++ .../Integration/WithApp/App/Cqs/Actions/Tags/UpdateTagTest.php | 2 ++ .../WithApp/App/Cqs/Actions/Users/CreateUserTest.php | 2 ++ .../App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php | 2 ++ .../WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php | 2 ++ .../WithApp/App/Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php | 2 ++ .../WithApp/App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php | 2 ++ .../PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php | 2 ++ .../HasAutoUpdatedPickupExceptionsForYearQueryTest.php | 2 ++ .../Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php | 2 ++ .../App/Cqs/Queries/Products/GetFoProductIndexPageQueryTest.php | 2 ++ .../App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php | 2 ++ .../WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php | 2 ++ .../App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php | 2 ++ .../App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php | 2 ++ .../App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php | 2 ++ tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php | 2 ++ tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php | 2 ++ tests/Integration/WithApp/App/Dto/RangeDtoTest.php | 2 ++ tests/Integration/WithApp/App/Dto/ShopDtoTest.php | 2 ++ tests/Integration/WithApp/App/Dto/SlideDtoTest.php | 2 ++ tests/Integration/WithApp/App/Models/ProductTest.php | 2 ++ tests/Integration/WithApp/App/Rules/AdultTest.php | 2 ++ .../WithApp/App/Services/ActionExecutorServiceTest.php | 2 ++ tests/Integration/WithApp/App/Services/CrmServiceTest.php | 2 ++ .../WithApp/App/Services/EmployeeSyncServiceTest.php | 2 ++ .../WithApp/App/Services/EmployeeUpsertServiceTest.php | 2 ++ .../WithApp/App/Services/FlashMessageServiceTest.php | 2 ++ .../Integration/WithApp/App/Services/MailRegateServiceTest.php | 2 ++ .../WithApp/App/Services/OrderOwnershipServiceTest.php | 2 ++ .../WithApp/App/Services/ProductDtoAssemblerTest.php | 2 ++ .../WithApp/App/Services/PublicHolidaysApiServiceTest.php | 2 ++ tests/Integration/WithApp/App/Services/StatsServiceTest.php | 2 ++ tests/Integration/WithApp/Helpers/DateHelperTest.php | 2 ++ tests/Integration/WithApp/Helpers/ToolboxHelpercoreTest.php | 2 ++ .../Infra/Adapters/Directories/EloquentShopDirectoryTest.php | 2 ++ .../Infra/Adapters/Events/LaravelDomainEventDispatcherTest.php | 2 ++ .../Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php | 2 ++ .../Repositories/EloquentPickupExceptionRepositoryTest.php | 2 ++ .../Adapters/Repositories/EloquentProductRepositoryTest.php | 2 ++ .../Infra/Adapters/Repositories/EloquentShopRepositoryTest.php | 2 ++ .../Adapters/Repositories/EloquentShopperRepositoryTest.php | 2 ++ .../Adapters/Services/EloquentEmployeeStatisticsServiceTest.php | 2 ++ .../Infra/Adapters/Services/LaravelTransactionManagerTest.php | 2 ++ 111 files changed, 222 insertions(+) diff --git a/tests/Integration/WithApp/App/Auth/CrmUserProviderTest.php b/tests/Integration/WithApp/App/Auth/CrmUserProviderTest.php index aefe00a2..7d1759e1 100644 --- a/tests/Integration/WithApp/App/Auth/CrmUserProviderTest.php +++ b/tests/Integration/WithApp/App/Auth/CrmUserProviderTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Auth; + use App\Auth\CrmUserProvider; use App\Exceptions\Crm\CrmCustomerNotActivatedException; use App\Models\Customer; diff --git a/tests/Integration/WithApp/App/Casts/CalendarDateCastTest.php b/tests/Integration/WithApp/App/Casts/CalendarDateCastTest.php index b5a967e9..de39d0cf 100644 --- a/tests/Integration/WithApp/App/Casts/CalendarDateCastTest.php +++ b/tests/Integration/WithApp/App/Casts/CalendarDateCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\CalendarDateCast; use App\Models\PickupException; use Carbon\CarbonImmutable; diff --git a/tests/Integration/WithApp/App/Casts/CodeCastTest.php b/tests/Integration/WithApp/App/Casts/CodeCastTest.php index 988ad5d4..56d26ce1 100644 --- a/tests/Integration/WithApp/App/Casts/CodeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/CodeCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\CodeCast; use Domain\Models\ValueObjects\Code; use Illuminate\Database\Eloquent\Model; diff --git a/tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php b/tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php index 979aa75f..64177cf1 100644 --- a/tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php +++ b/tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\DeliveryAddressCast; use Domain\Models\ValueObjects\DeliveryAddress; use Illuminate\Database\Eloquent\Model; diff --git a/tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php b/tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php index 291a21a0..897cfef9 100644 --- a/tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php +++ b/tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\DiscountValueCast; use Domain\Enums\DiscountType; use Domain\Models\ValueObjects\DiscountValue; diff --git a/tests/Integration/WithApp/App/Casts/EmailCastTest.php b/tests/Integration/WithApp/App/Casts/EmailCastTest.php index df906c3d..17bea089 100644 --- a/tests/Integration/WithApp/App/Casts/EmailCastTest.php +++ b/tests/Integration/WithApp/App/Casts/EmailCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\EmailCast; use Domain\Models\ValueObjects\Email; use Illuminate\Database\Eloquent\Model; diff --git a/tests/Integration/WithApp/App/Casts/EmployeeSitesCastTest.php b/tests/Integration/WithApp/App/Casts/EmployeeSitesCastTest.php index 8928b119..528c1ca7 100644 --- a/tests/Integration/WithApp/App/Casts/EmployeeSitesCastTest.php +++ b/tests/Integration/WithApp/App/Casts/EmployeeSitesCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\EmployeeSitesCast; use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Database\Eloquent\Model; diff --git a/tests/Integration/WithApp/App/Casts/MatriculeCastTest.php b/tests/Integration/WithApp/App/Casts/MatriculeCastTest.php index f4075e6c..ee3d97e9 100644 --- a/tests/Integration/WithApp/App/Casts/MatriculeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/MatriculeCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\MatriculeCast; use Domain\Models\ValueObjects\Matricule; use Illuminate\Database\Eloquent\Model; diff --git a/tests/Integration/WithApp/App/Casts/MoneyCastTest.php b/tests/Integration/WithApp/App/Casts/MoneyCastTest.php index a5fdd46a..7d6fb15b 100644 --- a/tests/Integration/WithApp/App/Casts/MoneyCastTest.php +++ b/tests/Integration/WithApp/App/Casts/MoneyCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\MoneyCast; use Illuminate\Database\Eloquent\Model; use Money\Currency; diff --git a/tests/Integration/WithApp/App/Casts/NutritionalValuesCastTest.php b/tests/Integration/WithApp/App/Casts/NutritionalValuesCastTest.php index d552bde3..fe24b79f 100644 --- a/tests/Integration/WithApp/App/Casts/NutritionalValuesCastTest.php +++ b/tests/Integration/WithApp/App/Casts/NutritionalValuesCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\NutritionalValuesCast; use Domain\Models\ValueObjects\NutritionalValues; use Illuminate\Database\Eloquent\Model; diff --git a/tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php b/tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php index b0087466..cc391254 100644 --- a/tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\OrderEmployeeCast; use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\OrderEmployee; diff --git a/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php b/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php index 1757c4c3..c0c88ead 100644 --- a/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php +++ b/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\OrderLineProductCast; use Domain\Enums\ProductBrand; use Domain\Enums\TaxRate; diff --git a/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php b/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php index 2b1b48d9..894407db 100644 --- a/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php +++ b/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\OrderReferenceCast; use Domain\Models\ValueObjects\OrderReference; use Illuminate\Database\Eloquent\Model; diff --git a/tests/Integration/WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php b/tests/Integration/WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php index 5c8576be..3a4b5704 100644 --- a/tests/Integration/WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\ShopperEstablishmentCodeCast; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Illuminate\Database\Eloquent\Model; diff --git a/tests/Integration/WithApp/App/Casts/ShopperServiceCodeCastTest.php b/tests/Integration/WithApp/App/Casts/ShopperServiceCodeCastTest.php index 02c3ad3c..d9a94f52 100644 --- a/tests/Integration/WithApp/App/Casts/ShopperServiceCodeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/ShopperServiceCodeCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\ShopperServiceCodeCast; use Domain\Models\ValueObjects\ShopperServiceCode; use Illuminate\Database\Eloquent\Model; diff --git a/tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php b/tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php index 2209806c..e40523a3 100644 --- a/tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\ShopperSiteCodeCast; use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Database\Eloquent\Model; diff --git a/tests/Integration/WithApp/App/Casts/UtcDatetimeCastTest.php b/tests/Integration/WithApp/App/Casts/UtcDatetimeCastTest.php index 6d9e5a88..33c40945 100644 --- a/tests/Integration/WithApp/App/Casts/UtcDatetimeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/UtcDatetimeCastTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Casts; + use App\Casts\UtcDatetimeCast; use App\Models\Discount; use Carbon\CarbonImmutable; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Auth/DeleteOldResetTokensTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Auth/DeleteOldResetTokensTest.php index 4bccc472..ac96b0e2 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Auth/DeleteOldResetTokensTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Auth/DeleteOldResetTokensTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Auth; + use App\Contracts\ActionInput; use App\Contracts\ActionInputEmpty; use App\Cqs\Actions\Auth\DeleteOldResetTokens; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php index 14436e33..0f000e4e 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Auth; + use App\Cqs\Actions\Auth\ResetCustomerPassword; use App\Cqs\Actions\Auth\ResetCustomerPasswordInput; use App\Cqs\Actions\Auth\ResetCustomerPasswordOutput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php index 1c63839e..4fb64524 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Basket; + use App\Cqs\Actions\Basket\AddToBasket; use App\Cqs\Actions\Basket\AddToBasketInput; use App\Models\Product; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php index b0e8b943..d7ac48d7 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Basket; + use App\Contracts\ActionInputEmpty; use App\Cqs\Actions\Basket\EmptyBasket; use App\Models\Product; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php index 7d618c49..70c49a01 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Basket; + use App\Cqs\Actions\Basket\RemoveFromBasket; use App\Cqs\Actions\Basket\RemoveProductFromBasketInput; use App\Cqs\Actions\Basket\RemoveQuantityFromBasketInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderPositionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderPositionTest.php index e9b2d58d..b8c9b2e0 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderPositionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderPositionTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Common; + use App\Contracts\ActionInput; use App\Cqs\Actions\Common\ChangeModelOrderPosition; use App\Cqs\Actions\Common\ChangeModelOrderPositionInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderTest.php index 10594ca7..a7ca05bc 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Common; + use App\Contracts\ActionInput; use App\Cqs\Actions\Common\ChangeModelOrder; use App\Cqs\Actions\Common\ChangeModelOrderInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Common/ExecuteMassActionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ExecuteMassActionTest.php index 7866a664..6d8f8753 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Common/ExecuteMassActionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Common/ExecuteMassActionTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Common; + use App\Cqs\Actions\Common\ExecuteMassAction; use App\Cqs\Actions\Common\ExecuteMassActionInput; use App\Enums\MassActionType; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStarTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStarTest.php index c779520a..c558be3c 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStarTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStarTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Common; + use App\Contracts\ActionInput; use App\Cqs\Actions\Common\ToggleModelStar; use App\Cqs\Actions\Common\ToggleModelStarInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStatusTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStatusTest.php index 1721e71e..8cd397ef 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStatusTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStatusTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Common; + use App\Contracts\ActionInput; use App\Cqs\Actions\Common\ToggleModelStatus; use App\Cqs\Actions\Common\ToggleModelStatusInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php index 994d9ff4..c384ea81 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Contact; + use App\Contracts\ActionInput; use App\Cqs\Actions\Contact\SubmitContactForm; use App\Cqs\Actions\Contact\SubmitContactFormInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UnsubscribeFromNewsletterTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UnsubscribeFromNewsletterTest.php index 2145cd8f..42e68d77 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UnsubscribeFromNewsletterTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UnsubscribeFromNewsletterTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Crm; + use App\Cqs\Actions\Crm\UnsubscribeFromNewsletter; use App\Cqs\Actions\Crm\UnsubscribeFromNewsletterInput; use App\Cqs\Actions\Crm\UnsubscribeFromNewsletterOutput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php index c5927488..54fd18d6 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Crm; + use App\Cqs\Actions\Crm\UpdateCustomerPassword; use App\Cqs\Actions\Crm\UpdateCustomerPasswordInput; use App\Cqs\Actions\Crm\UpdateCustomerPasswordOutput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php index 05584cd1..83a4153e 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Crm; + use App\Cqs\Actions\Crm\UpdateCustomer; use App\Cqs\Actions\Crm\UpdateCustomerInput; use App\Cqs\Actions\Crm\UpdateCustomerOutput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php index 6cefadec..4503a1de 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Customers; + use App\Attributes\Locked; use App\Contracts\ActionInput; use App\Contracts\Executor; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Customers/UpdateCustomerLastLoginTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Customers/UpdateCustomerLastLoginTest.php index 44aaa200..89dd859a 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Customers/UpdateCustomerLastLoginTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Customers/UpdateCustomerLastLoginTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Customers; + use App\Contracts\ActionInput; use App\Cqs\Actions\Customers\UpdateCustomerLastLogin; use App\Cqs\Actions\Customers\UpdateCustomerLastLoginInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php index 867111cd..36245e62 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Employee; + use App\Contracts\ActionInputEmpty; use App\Cqs\Actions\Employee\SynchronizeEmployeesWithArcadiaApi; use App\Cqs\Queries\Settings\GetSettingsQuery; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Faqs/CreateFaqTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Faqs/CreateFaqTest.php index bec06a46..0c42dc20 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Faqs/CreateFaqTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Faqs/CreateFaqTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Faqs; + use App\Contracts\ActionInput; use App\Cqs\Actions\Faqs\CreateFaq; use App\Cqs\Actions\Faqs\CreateFaqInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Faqs/DeleteFaqTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Faqs/DeleteFaqTest.php index 90cde2bf..0fdfd3aa 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Faqs/DeleteFaqTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Faqs/DeleteFaqTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Faqs; + use App\Contracts\ActionInput; use App\Cqs\Actions\Faqs\DeleteFaq; use App\Cqs\Actions\Faqs\DeleteFaqInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Faqs/UpdateFaqTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Faqs/UpdateFaqTest.php index a305aef9..a4725b86 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Faqs/UpdateFaqTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Faqs/UpdateFaqTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Faqs; + use App\Contracts\ActionInput; use App\Cqs\Actions\Faqs\UpdateFaq; use App\Cqs\Actions\Faqs\UpdateFaqInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php index 0116ce0c..5b486cd1 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Orders; + use App\Cqs\Actions\Orders\ApplyPickTimeSlot; use App\Cqs\Actions\Orders\ApplyPickTimeSlotInput; use App\Cqs\Actions\Orders\ApplyPickTimeSlotOutput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php index 54b9d01a..101af0b3 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Orders; + use App\Cqs\Actions\Orders\CancelOrder; use App\Cqs\Actions\Orders\CancelOrderInput; use App\Cqs\Actions\Orders\CancelOrderOutput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php index 2cdd3181..9525c9a6 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Orders; + use App\Cqs\Actions\Orders\ClaimTodayOrderReminder; use App\Cqs\Actions\Orders\ClaimTodayOrderReminderInput; use App\Models\Order; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php index 89360205..aaef4497 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Orders; + use App\Cqs\Actions\Orders\InitializeOrderTunnel; use App\Cqs\Actions\Orders\InitializeOrderTunnelInput; use Domain\Builders\OrderBuilderWithBasket; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php index 3c75ffdd..e7e8af3e 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Orders; + use App\Cqs\Actions\Orders\CancelPendingOrder; use App\Cqs\Actions\Orders\CancelPendingOrderInput; use App\Cqs\Actions\Orders\CancelPendingOrderOutput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php index db020ab5..9054e998 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Orders; + use App\Cqs\Actions\Orders\ReleaseTodayOrderReminder; use App\Cqs\Actions\Orders\ReleaseTodayOrderReminderInput; use App\Models\Order; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Pages/UpdatePageTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Pages/UpdatePageTest.php index fb1890a4..7039b5ae 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Pages/UpdatePageTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Pages/UpdatePageTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Pages; + use App\Contracts\ActionInput; use App\Cqs\Actions\Pages\UpdatePage; use App\Cqs\Actions\Pages\UpdatePageInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php index af1f77c0..96789a70 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\PickupExceptions; + use App\Contracts\ActionInput; use App\Cqs\Actions\PickupExceptions\CreatePickupException; use App\Cqs\Actions\PickupExceptions\CreatePickupExceptionInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php index e04f2607..97a684d6 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\PickupExceptions; + use App\Contracts\ActionInput; use App\Cqs\Actions\PickupExceptions\DeletePickupException; use App\Cqs\Actions\PickupExceptions\DeletePickupExceptionInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php index 709f022d..010f23d2 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\PickupExceptions; + use App\Contracts\ActionInput; use App\Cqs\Actions\PickupExceptions\UpdatePickupException; use App\Cqs\Actions\PickupExceptions\UpdatePickupExceptionInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpsertShopsPickupExceptionsForYearTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpsertShopsPickupExceptionsForYearTest.php index 5a1922f3..0fc51eac 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpsertShopsPickupExceptionsForYearTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpsertShopsPickupExceptionsForYearTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\PickupExceptions; + use App\Contracts\ActionInput; use App\Cqs\Actions\PickupExceptions\UpsertShopsPickupExceptionsForYear; use App\Cqs\Actions\PickupExceptions\UpsertShopsPickupExceptionsForYearInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php index 3f5d4768..375748c6 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\ProductIncos; + use App\Contracts\ActionInput; use App\Cqs\Actions\ProductIncos\AssociateProductInco; use App\Cqs\Actions\ProductIncos\AssociateProductIncoInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php index 65b5936b..21e9b7ec 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\ProductIncos; + use App\Cqs\Actions\ProductIncos\SyncProductInco; use App\Cqs\Actions\ProductIncos\SyncProductIncoInput; use App\Cqs\Actions\ProductIncos\SyncProductIncoOutput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php index 9d369007..0c39db03 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\ProductIncos; + use App\Contracts\ActionInputEmpty; use App\Cqs\Actions\ProductIncos\SynchronizeProductIncosWithArcadiaApi; use App\Dto\ArcadiaIncoDataDto; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php index 31b0ab32..e3bf8a93 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Products; + use App\Cqs\Actions\Products\CreateProduct; use App\Cqs\Actions\Products\CreateProductInput; use App\Lib\PublicS3Disk; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Products/DeleteProductTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Products/DeleteProductTest.php index 278e4b79..3e016a10 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Products/DeleteProductTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Products/DeleteProductTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Products; + use App\Cqs\Actions\Products\DeleteProduct; use App\Cqs\Actions\Products\DeleteProductInput; use App\Models\Product; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Products/UpdateProductTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Products/UpdateProductTest.php index f3d79eb3..689ee901 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Products/UpdateProductTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Products/UpdateProductTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Products; + use App\Cqs\Actions\Products\UpdateProduct; use App\Cqs\Actions\Products\UpdateProductInput; use App\Lib\PublicS3Disk; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php index 9918f5e8..1324051b 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Ranges; + use App\Contracts\ActionInput; use App\Cqs\Actions\Ranges\CreateRange; use App\Cqs\Actions\Ranges\CreateRangeInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php index fa8c5eda..e4ead4c8 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Ranges; + use App\Contracts\ActionInput; use App\Cqs\Actions\Ranges\DeleteRange; use App\Cqs\Actions\Ranges\DeleteRangeInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php index 8ae4899d..9e7547e3 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Ranges; + use App\Contracts\ActionInput; use App\Cqs\Actions\Ranges\UpdateRange; use App\Cqs\Actions\Ranges\UpdateRangeInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php index e279a8a8..bb3bb536 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Settings; + use App\Cqs\Actions\Settings\UpdateSettings; use App\Cqs\Actions\Settings\UpdateSettingsInput; use App\Models\Setting; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php index 5330e5c4..eb8b9b04 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Shops; + use App\Contracts\ActionInput; use App\Cqs\Actions\Shops\CreateShop; use App\Cqs\Actions\Shops\CreateShopInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php index 0185c097..a5fa0e69 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Shops; + use App\Contracts\ActionInput; use App\Cqs\Actions\Shops\DeleteShop; use App\Cqs\Actions\Shops\DeleteShopInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php index c4333ceb..45afee6f 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Shops; + use App\Contracts\ActionInput; use App\Cqs\Actions\Shops\UpdateShopPickupExceptions; use App\Cqs\Actions\Shops\UpdateShopPickupExceptionsInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php index dbb9ab51..10809ad2 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Shops; + use App\Contracts\ActionInput; use App\Cqs\Actions\Shops\UpdateShop; use App\Cqs\Actions\Shops\UpdateShopInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Slides/CreateSlideTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Slides/CreateSlideTest.php index 0c4d841b..55aedd1f 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Slides/CreateSlideTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Slides/CreateSlideTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Slides; + use App\Contracts\ActionInput; use App\Cqs\Actions\Slides\CreateSlide; use App\Cqs\Actions\Slides\CreateSlideInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Slides/DeleteSlideTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Slides/DeleteSlideTest.php index e0c7092d..ab37793b 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Slides/DeleteSlideTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Slides/DeleteSlideTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Slides; + use App\Contracts\ActionInput; use App\Cqs\Actions\Slides\DeleteSlide; use App\Cqs\Actions\Slides\DeleteSlideInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlideTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlideTest.php index e85b94ec..7f1e08ce 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlideTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlideTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Slides; + use App\Contracts\ActionInput; use App\Cqs\Actions\Slides\UpdateSlide; use App\Cqs\Actions\Slides\UpdateSlideInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlidesStatusTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlidesStatusTest.php index 172f7cb6..5462997d 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlidesStatusTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlidesStatusTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Slides; + use App\Contracts\ActionInput; use App\Contracts\ActionInputEmpty; use App\Cqs\Actions\Slides\UpdateSlidesStatus; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Tags/CreateTagTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Tags/CreateTagTest.php index 0ed3c304..dc8be7cd 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Tags/CreateTagTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Tags/CreateTagTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Tags; + use App\Contracts\ActionInput; use App\Cqs\Actions\Tags\CreateTag; use App\Cqs\Actions\Tags\CreateTagInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Tags/DeleteTagTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Tags/DeleteTagTest.php index e4ff9530..76a72aa9 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Tags/DeleteTagTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Tags/DeleteTagTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Tags; + use App\Contracts\ActionInput; use App\Cqs\Actions\Tags\DeleteTag; use App\Cqs\Actions\Tags\DeleteTagInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Tags/UpdateTagTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Tags/UpdateTagTest.php index 827b41af..e4f3b903 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Tags/UpdateTagTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Tags/UpdateTagTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Tags; + use App\Contracts\ActionInput; use App\Cqs\Actions\Tags\UpdateTag; use App\Cqs\Actions\Tags\UpdateTagInput; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Users/CreateUserTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Users/CreateUserTest.php index 064ce31d..aee214b2 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Users/CreateUserTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Users/CreateUserTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Actions\Users; + use App\Contracts\ActionInput; use App\Cqs\Actions\Users\CreateUser; use App\Cqs\Actions\Users\CreateUserInput; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php index aff05be9..3f08f406 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Queries\Customers; + use App\Cqs\Queries\Customers\GetCustomerByEmailQuery; use App\Cqs\Queries\Customers\GetCustomerByEmailQueryInput; use App\Models\Customer; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php index fe29ad95..ff3dca27 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Queries\Faqs; + use App\Contracts\QueryInputEmpty; use App\Cqs\Queries\Faqs\GetFaqsQuery; use App\Dto\FaqDto; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php index f20b88f8..77df42e0 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Queries\Faqs; + use App\Cqs\Queries\Faqs\GetPaginatedFaqsQuery; use App\Cqs\Queries\Faqs\GetPaginatedFaqsQueryInput; use App\Dto\FaqDto; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php index b207330c..68f792b7 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Queries\Pages; + use App\Cqs\Queries\Pages\GetPageQuery; use App\Cqs\Queries\Pages\GetPageQueryInput; use App\Dto\PageDto; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php index a17b5796..c2365bb9 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Queries\PickupExceptions; + use App\Cqs\Queries\PickupExceptions\GetPaginatedPickupExceptionsQuery; use App\Cqs\Queries\PickupExceptions\GetPaginatedPickupExceptionsQueryInput; use App\Dto\PickupExceptionDto; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryTest.php index 72568e13..f02a2286 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Queries\PickupExceptions; + use App\Cqs\Queries\PickupExceptions\HasAutoUpdatedPickupExceptionsForYearQuery; use App\Cqs\Queries\PickupExceptions\HasAutoUpdatedPickupExceptionsForYearQueryInput; use App\Models\PickupException; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php index 482526b9..4ee9d821 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Queries\ProductIncos; + use App\Cqs\Queries\ProductIncos\GetProductIncoForEditQuery; use App\Cqs\Queries\ProductIncos\GetProductIncoForEditQueryInput; use App\Cqs\Queries\ProductIncos\GetProductIncoForEditQueryOutput; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoProductIndexPageQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoProductIndexPageQueryTest.php index b6a859f0..e7ab32f1 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoProductIndexPageQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoProductIndexPageQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Queries\Products; + use App\Cqs\Queries\Products\GetFoProductIndexPageQuery; use App\Cqs\Queries\Products\GetFoProductIndexPageQueryInput; use App\Dto\RangeDto; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php index eae5777b..4061798c 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Queries\Ranges; + use App\Cqs\Queries\Ranges\GetPaginatedRangesQuery; use App\Cqs\Queries\Ranges\GetPaginatedRangesQueryInput; use App\Dto\RangeDto; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php index f762a335..de622d53 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Queries\Settings; + use App\Contracts\QueryInputEmpty; use App\Cqs\Queries\Settings\GetSettingsQuery; use App\Dto\SettingDto; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php index 3c04a648..0a52276a 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Queries\Shops; + use App\Cqs\Queries\Shops\GetPaginatedShopsQuery; use App\Cqs\Queries\Shops\GetPaginatedShopsQueryInput; use App\Cqs\Queries\Shops\GetPaginatedShopsQueryOutput; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php index e42d2e41..05e89606 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Queries\Shops; + use App\Cqs\Queries\Shops\GetShopPickupExceptionsQuery; use App\Cqs\Queries\Shops\GetShopPickupExceptionsQueryInput; use App\Cqs\Queries\Shops\GetShopPickupExceptionsQueryOutput; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php index 4fc1c9b7..d99558d1 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Cqs\Queries\Slides; + use App\Cqs\Queries\Slides\GetPaginatedSlidesQuery; use App\Cqs\Queries\Slides\GetPaginatedSlidesQueryInput; use App\Dto\SlideDto; diff --git a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php index 92235e70..d96b4167 100644 --- a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Dto; + use App\Dto\OrderLineDto; use App\Models\Order; use App\Models\OrderLine; diff --git a/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php b/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php index feb10552..4f718747 100644 --- a/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Dto; + use App\Dto\PickupExceptionDto; use App\Models\PickupException; use App\Models\Shop; diff --git a/tests/Integration/WithApp/App/Dto/RangeDtoTest.php b/tests/Integration/WithApp/App/Dto/RangeDtoTest.php index 615cb889..9c6747b5 100644 --- a/tests/Integration/WithApp/App/Dto/RangeDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/RangeDtoTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Dto; + use App\Dto\RangeDto; use App\Models\Range; use Illuminate\Foundation\Testing\RefreshDatabase; diff --git a/tests/Integration/WithApp/App/Dto/ShopDtoTest.php b/tests/Integration/WithApp/App/Dto/ShopDtoTest.php index 49938fff..9e2cc1da 100644 --- a/tests/Integration/WithApp/App/Dto/ShopDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/ShopDtoTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Dto; + use App\Dto\ShopDto; use App\Models\PickupException; use App\Models\Shop; diff --git a/tests/Integration/WithApp/App/Dto/SlideDtoTest.php b/tests/Integration/WithApp/App/Dto/SlideDtoTest.php index 90aa15ab..801823a4 100644 --- a/tests/Integration/WithApp/App/Dto/SlideDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/SlideDtoTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Dto; + use App\Dto\SlideDto; use App\Lib\PublicS3Disk; use App\Models\Slide; diff --git a/tests/Integration/WithApp/App/Models/ProductTest.php b/tests/Integration/WithApp/App/Models/ProductTest.php index 4e6fd90e..8c051599 100644 --- a/tests/Integration/WithApp/App/Models/ProductTest.php +++ b/tests/Integration/WithApp/App/Models/ProductTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Models; + use App\Models\Product; use App\Models\ProductInco; use App\Models\Range; diff --git a/tests/Integration/WithApp/App/Rules/AdultTest.php b/tests/Integration/WithApp/App/Rules/AdultTest.php index a4f8278f..b588bef7 100644 --- a/tests/Integration/WithApp/App/Rules/AdultTest.php +++ b/tests/Integration/WithApp/App/Rules/AdultTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Rules; + use App\Rules\Adult; use Carbon\CarbonImmutable; use Illuminate\Support\Facades\App; diff --git a/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php b/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php index 62e8e040..19c71a47 100644 --- a/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php +++ b/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Services; + use App\Attributes\Locked; use App\Attributes\WithoutTransaction; use App\Contracts\Action; diff --git a/tests/Integration/WithApp/App/Services/CrmServiceTest.php b/tests/Integration/WithApp/App/Services/CrmServiceTest.php index 42b63aa1..5b4d7efd 100644 --- a/tests/Integration/WithApp/App/Services/CrmServiceTest.php +++ b/tests/Integration/WithApp/App/Services/CrmServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Services; + use App\Exceptions\CrmServiceException; use App\Services\CrmService; use Domain\Enums\Country; diff --git a/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php b/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php index 7bce7931..2eaba579 100644 --- a/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php +++ b/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Services; + use App\Cqs\Queries\Settings\GetSettingsQuery; use App\Models\Setting; use App\Services\ArcadiaEmployee; diff --git a/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php b/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php index 9c99042e..70a24803 100644 --- a/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php +++ b/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Services; + use App\Models\Setting; use App\Services\ArcadiaEmployee; use App\Services\CodeGenerationService; diff --git a/tests/Integration/WithApp/App/Services/FlashMessageServiceTest.php b/tests/Integration/WithApp/App/Services/FlashMessageServiceTest.php index ba92e410..c5d1ab2f 100644 --- a/tests/Integration/WithApp/App/Services/FlashMessageServiceTest.php +++ b/tests/Integration/WithApp/App/Services/FlashMessageServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Services; + use App\Services\FlashMessageService; use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Session; diff --git a/tests/Integration/WithApp/App/Services/MailRegateServiceTest.php b/tests/Integration/WithApp/App/Services/MailRegateServiceTest.php index 7a7eb1da..9563b72a 100644 --- a/tests/Integration/WithApp/App/Services/MailRegateServiceTest.php +++ b/tests/Integration/WithApp/App/Services/MailRegateServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Services; + use App\Mail\RegateOrderMail; use App\Services\MailRegateService; use Carbon\CarbonImmutable; diff --git a/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php b/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php index cb520d36..e7e0a3a6 100644 --- a/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php +++ b/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Services; + use App\Models\Customer; use App\Models\Employee; use App\Models\Order; diff --git a/tests/Integration/WithApp/App/Services/ProductDtoAssemblerTest.php b/tests/Integration/WithApp/App/Services/ProductDtoAssemblerTest.php index 90342648..b15ead8b 100644 --- a/tests/Integration/WithApp/App/Services/ProductDtoAssemblerTest.php +++ b/tests/Integration/WithApp/App/Services/ProductDtoAssemblerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Services; + use App\Cqs\Queries\Products\GetPublishedProductWithPricingQuery; use App\Cqs\Queries\Products\GetPublishedProductWithPricingQueryInput; use App\Models\Product; diff --git a/tests/Integration/WithApp/App/Services/PublicHolidaysApiServiceTest.php b/tests/Integration/WithApp/App/Services/PublicHolidaysApiServiceTest.php index 9c7119d9..01df7924 100644 --- a/tests/Integration/WithApp/App/Services/PublicHolidaysApiServiceTest.php +++ b/tests/Integration/WithApp/App/Services/PublicHolidaysApiServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Services; + use App\Dto\PublicHolidayDto; use App\Services\PublicHolidaysApiService; use Carbon\CarbonImmutable; diff --git a/tests/Integration/WithApp/App/Services/StatsServiceTest.php b/tests/Integration/WithApp/App/Services/StatsServiceTest.php index 66f048be..c5582fad 100644 --- a/tests/Integration/WithApp/App/Services/StatsServiceTest.php +++ b/tests/Integration/WithApp/App/Services/StatsServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Services; + use App\Models\Customer; use App\Models\Employee; use App\Models\Order; diff --git a/tests/Integration/WithApp/Helpers/DateHelperTest.php b/tests/Integration/WithApp/Helpers/DateHelperTest.php index 8ef55b3b..c662f1a8 100644 --- a/tests/Integration/WithApp/Helpers/DateHelperTest.php +++ b/tests/Integration/WithApp/Helpers/DateHelperTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Helpers; + use Illuminate\Support\Facades\Date; use Shared\Helpers\DatesHelper; diff --git a/tests/Integration/WithApp/Helpers/ToolboxHelpercoreTest.php b/tests/Integration/WithApp/Helpers/ToolboxHelpercoreTest.php index 01a2cefc..0780c4b3 100644 --- a/tests/Integration/WithApp/Helpers/ToolboxHelpercoreTest.php +++ b/tests/Integration/WithApp/Helpers/ToolboxHelpercoreTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Helpers; + use App\Lib\Helpers\ToolboxHelperCore; it('returns false when replace is array but search is string', function (): void { diff --git a/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php index 82f4a24e..7172db33 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Infra\Adapters\Directories; + use App\Models\Shop; use Domain\Models\ValueObjects\Entities\ShopId; use Infrastructure\Adapters\Directories\EloquentShopDirectory; diff --git a/tests/Integration/WithApp/Infra/Adapters/Events/LaravelDomainEventDispatcherTest.php b/tests/Integration/WithApp/Infra/Adapters/Events/LaravelDomainEventDispatcherTest.php index e3726dd8..19c39153 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Events/LaravelDomainEventDispatcherTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Events/LaravelDomainEventDispatcherTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Infra\Adapters\Events; + use Illuminate\Support\Facades\Event; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Shared\DDD\Event as DomainEvent; diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php index 0db61cef..9db8ff66 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Infra\Adapters\Repositories; + use Domain\Enums\OrderStatus; use Domain\Models\Entities\Order as DomainOrder; use Domain\Models\ValueObjects\Entities\OrderId; diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php index 78455518..b66fb08b 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Infra\Adapters\Repositories; + use App\Models\PickupException; use App\Models\Shop; use Carbon\CarbonPeriod; diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php index 1bd0a45c..161af47a 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Infra\Adapters\Repositories; + use App\Models\Product; use App\Models\Range; use Domain\Enums\Units\OrderUnit; diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php index 40337567..11cd22c6 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Infra\Adapters\Repositories; + use App\Models\Employee; use App\Models\Shop; use Domain\Models\ValueObjects\Code; diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php index 911d2d25..80979bdc 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Infra\Adapters\Repositories; + use App\Models\Customer; use App\Models\Employee; use Carbon\CarbonImmutable; diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php index 3295b24e..5c739e86 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Infra\Adapters\Services; + use App\Models\Shop; use Carbon\CarbonImmutable; use Domain\Enums\OrderStatus; diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/LaravelTransactionManagerTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/LaravelTransactionManagerTest.php index 7d720c0a..ce48922f 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/LaravelTransactionManagerTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/LaravelTransactionManagerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Infra\Adapters\Services; + use Illuminate\Support\Facades\DB; use Infrastructure\Adapters\Services\LaravelTransactionManager; From 5b88fb098a31de5a3becfe1c3effccd277560377 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 14:26:35 +0100 Subject: [PATCH 133/183] test(tests): add PSR-4 namespaces to Architecture and Feature test files --- tests/Architecture/ApplicationTest.php | 4 +++- tests/Architecture/CodingStandardsTest.php | 2 ++ tests/Architecture/DomainTest.php | 2 ++ tests/Architecture/InfraTest.php | 2 ++ tests/Architecture/NamingConventionsTest.php | 2 ++ .../App/Console/Commands/UpsertEmployeesFormFileTest.php | 2 ++ .../UpsertPublicHolydaysOnShopsPickupExceptionsTest.php | 2 ++ tests/Feature/App/Console/Commands/UserCreateTest.php | 2 ++ tests/Feature/App/Http/Controllers/Bo/AuthTest.php | 2 ++ .../App/Http/Controllers/Bo/DashboardControllerTest.php | 2 ++ .../App/Http/Controllers/Bo/EmployeeSyncFeatureTest.php | 2 ++ .../App/Http/Controllers/Bo/EmployeesControllerTest.php | 2 ++ tests/Feature/App/Http/Controllers/Bo/FaqsControllerTest.php | 2 ++ .../Feature/App/Http/Controllers/Bo/OrdersControllerTest.php | 2 ++ tests/Feature/App/Http/Controllers/Bo/PageControllerTest.php | 2 ++ .../Http/Controllers/Bo/PickupExceptionsControllerTest.php | 2 ++ .../App/Http/Controllers/Bo/ProductIncosControllerTest.php | 2 ++ .../App/Http/Controllers/Bo/ProductsControllerTest.php | 2 ++ .../Feature/App/Http/Controllers/Bo/RangesControllerTest.php | 2 ++ .../App/Http/Controllers/Bo/SettingsControllerTest.php | 2 ++ tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php | 2 ++ .../Feature/App/Http/Controllers/Bo/SlidesControllerTest.php | 2 ++ tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php | 2 ++ .../App/Http/Controllers/Fo/Ajax/BasketControllerTest.php | 2 ++ .../App/Http/Controllers/Fo/Ajax/PickupControllerTest.php | 2 ++ .../App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php | 2 ++ .../Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php | 2 ++ .../App/Http/Controllers/Fo/Auth/LoginControllerTest.php | 2 ++ .../App/Http/Controllers/Fo/Auth/RegisterControllerTest.php | 2 ++ .../Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php | 2 ++ .../Http/Controllers/Fo/Auth/VerificationControllerTest.php | 2 ++ tests/Feature/App/Http/Controllers/Fo/AuthTest.php | 2 ++ .../Http/Controllers/Fo/Customers/CustomerControllerTest.php | 2 ++ .../App/Http/Controllers/Fo/Customers/OrderControllerTest.php | 2 ++ .../Http/Controllers/Fo/Customers/PasswordControllerTest.php | 2 ++ .../App/Http/Controllers/Fo/NewsletterControllerTest.php | 2 ++ .../App/Http/Controllers/Fo/Pages/HomeControllerTest.php | 2 ++ .../App/Http/Controllers/Fo/Pages/PageControllerTest.php | 2 ++ .../App/Http/Controllers/Fo/Pages/ProductsControllerTest.php | 2 ++ .../App/Http/Controllers/Fo/ProductCharacterizationTest.php | 2 ++ .../Feature/App/Http/Controllers/Fo/TunnelControllerTest.php | 2 ++ tests/Feature/App/Http/Middleware/TrustProxiesTest.php | 2 ++ .../Feature/App/Http/Requests/Basket/AddBasketRequestTest.php | 2 ++ .../App/Http/Requests/Basket/RemoveBasketRequestTest.php | 2 ++ .../App/Http/Requests/Bo/Dashboard/DashboardRequestTest.php | 2 ++ .../Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php | 2 ++ .../Feature/App/Http/Requests/Bo/Faqs/StoreFaqRequestTest.php | 2 ++ tests/Feature/App/Http/Requests/Bo/MassActionRequestTest.php | 2 ++ .../App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php | 2 ++ .../App/Http/Requests/Bo/Pages/UpdatePageRequestTest.php | 2 ++ .../Bo/PickupExceptions/StorePickupExceptionRequestTest.php | 2 ++ .../App/Http/Requests/Bo/Products/IndexProductRequestTest.php | 2 ++ .../App/Http/Requests/Bo/Products/StoreProductRequestTest.php | 2 ++ .../App/Http/Requests/Bo/Ranges/StoreRangeRequestTest.php | 2 ++ .../App/Http/Requests/Bo/Shops/IndexShopRequestTest.php | 2 ++ .../App/Http/Requests/Bo/Shops/StoreShopRequestTest.php | 2 ++ .../Bo/Shops/UpdateShopPickupExceptionsRequestTest.php | 2 ++ .../App/Http/Requests/Bo/Slides/StoreSlideRequestTest.php | 2 ++ .../Feature/App/Http/Requests/Bo/Tags/StoreTagRequestTest.php | 2 ++ .../App/Http/Requests/Fo/Ajax/FilterProductsRequestTest.php | 2 ++ .../Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php | 2 ++ tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php | 2 ++ .../App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php | 2 ++ .../Http/Requests/Fo/Customer/UpdatePasswordRequestTest.php | 2 ++ .../App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php | 2 ++ .../App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php | 2 ++ .../Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php | 2 ++ .../App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php | 2 ++ tests/Feature/App/Jobs/DeleteOldResetTokensTest.php | 2 ++ tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php | 2 ++ tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php | 2 ++ tests/Feature/App/Jobs/SendReminderMailTest.php | 2 ++ tests/Feature/App/Jobs/UpdateSlidesStatusTest.php | 2 ++ .../Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php | 2 ++ tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php | 2 ++ tests/Feature/App/Providers/AuthServiceProviderTest.php | 2 ++ tests/Feature/App/Providers/DateMacrosTest.php | 2 ++ tests/Feature/App/Views/ChangeOrderBladeTest.php | 2 ++ 78 files changed, 157 insertions(+), 1 deletion(-) diff --git a/tests/Architecture/ApplicationTest.php b/tests/Architecture/ApplicationTest.php index 9276acef..f49cd65c 100644 --- a/tests/Architecture/ApplicationTest.php +++ b/tests/Architecture/ApplicationTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Architecture; + use App\Casts\CalendarDateCast; use App\Casts\UtcDatetimeCast; use App\Contracts\Action; @@ -119,7 +121,7 @@ describe('application coding rules', function (): void { expect(in_array($baseCast, $forbiddenCasts, true)) ->toBeFalse( "{$className}::casts()['{$attribute}'] must use " - . UtcDatetimeCast::class . ' or ' . CalendarDateCast::class . " instead of '{$cast}'." + . UtcDatetimeCast::class . ' or ' . CalendarDateCast::class . " instead of '{$cast}'." ); } } diff --git a/tests/Architecture/CodingStandardsTest.php b/tests/Architecture/CodingStandardsTest.php index 6369187c..771a721e 100644 --- a/tests/Architecture/CodingStandardsTest.php +++ b/tests/Architecture/CodingStandardsTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Architecture; + use Shared\Filesystem\TemporaryFileFactory; describe('coding standards', function (): void { diff --git a/tests/Architecture/DomainTest.php b/tests/Architecture/DomainTest.php index ed98fee9..ae13b0ca 100644 --- a/tests/Architecture/DomainTest.php +++ b/tests/Architecture/DomainTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Architecture; + use Shared\DDD\Directory; use Shared\DDD\Entity; use Shared\DDD\Repository; diff --git a/tests/Architecture/InfraTest.php b/tests/Architecture/InfraTest.php index 208a2d68..dd8b68c4 100644 --- a/tests/Architecture/InfraTest.php +++ b/tests/Architecture/InfraTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Architecture; + describe('infra coding rules', function (): void { arch('No App classes are used in Infra') ->expect('Infrastructure') diff --git a/tests/Architecture/NamingConventionsTest.php b/tests/Architecture/NamingConventionsTest.php index ecca490d..6ad0bd74 100644 --- a/tests/Architecture/NamingConventionsTest.php +++ b/tests/Architecture/NamingConventionsTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Architecture; + use App\Exceptions\GlobalHandler; use App\Services\ArcadiaEmployee; use App\Services\EmployeeUpsertServiceResult; diff --git a/tests/Feature/App/Console/Commands/UpsertEmployeesFormFileTest.php b/tests/Feature/App/Console/Commands/UpsertEmployeesFormFileTest.php index fea882cb..9291617e 100644 --- a/tests/Feature/App/Console/Commands/UpsertEmployeesFormFileTest.php +++ b/tests/Feature/App/Console/Commands/UpsertEmployeesFormFileTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Console\Commands; + use Illuminate\Console\Command; use Illuminate\Testing\PendingCommand; use Webmozart\Assert\Assert; diff --git a/tests/Feature/App/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptionsTest.php b/tests/Feature/App/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptionsTest.php index dff5b73f..63b4dfc2 100644 --- a/tests/Feature/App/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptionsTest.php +++ b/tests/Feature/App/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptionsTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Console\Commands; + use App\Jobs\UpsertShopsPickupExceptionsUsingApiForYear; use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Date; diff --git a/tests/Feature/App/Console/Commands/UserCreateTest.php b/tests/Feature/App/Console/Commands/UserCreateTest.php index d6118567..222df908 100644 --- a/tests/Feature/App/Console/Commands/UserCreateTest.php +++ b/tests/Feature/App/Console/Commands/UserCreateTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Console\Commands; + use App\Models\User; use Domain\Enums\UserRole; use Illuminate\Foundation\Testing\RefreshDatabase; diff --git a/tests/Feature/App/Http/Controllers/Bo/AuthTest.php b/tests/Feature/App/Http/Controllers/Bo/AuthTest.php index 59c1e897..9d353cf4 100644 --- a/tests/Feature/App/Http/Controllers/Bo/AuthTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/AuthTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + it('Should required login to access backoffice', function (): void { /** @var \Tests\TestCase $this */ // GIVEN diff --git a/tests/Feature/App/Http/Controllers/Bo/DashboardControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/DashboardControllerTest.php index 99dd8167..7d8ff10c 100644 --- a/tests/Feature/App/Http/Controllers/Bo/DashboardControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/DashboardControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Models\User; use Domain\Enums\StatsShopType; use Domain\Enums\UserRole; diff --git a/tests/Feature/App/Http/Controllers/Bo/EmployeeSyncFeatureTest.php b/tests/Feature/App/Http/Controllers/Bo/EmployeeSyncFeatureTest.php index 3ed28e33..607d22e9 100644 --- a/tests/Feature/App/Http/Controllers/Bo/EmployeeSyncFeatureTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/EmployeeSyncFeatureTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Cqs\Queries\Settings\GetSettingsQuery; use App\Models\Employee; use App\Models\Setting; diff --git a/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php index 5d2c248f..e4ed6d46 100644 --- a/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Jobs\FetchAndUpsertArcadiaEmployees; use App\Models\User; use Domain\Enums\UserRole; diff --git a/tests/Feature/App/Http/Controllers/Bo/FaqsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/FaqsControllerTest.php index 17c95989..d4be13ac 100644 --- a/tests/Feature/App/Http/Controllers/Bo/FaqsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/FaqsControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Models\Faq; use App\Models\User; use Domain\Enums\UserRole; diff --git a/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php index 5d6d26e7..36cfc46d 100644 --- a/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Dto\OrderDto; use App\Models\Customer; use App\Models\Employee; diff --git a/tests/Feature/App/Http/Controllers/Bo/PageControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/PageControllerTest.php index 7588c270..e39612c7 100644 --- a/tests/Feature/App/Http/Controllers/Bo/PageControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/PageControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Dto\PageDto; use App\Models\Page; use App\Models\User; diff --git a/tests/Feature/App/Http/Controllers/Bo/PickupExceptionsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/PickupExceptionsControllerTest.php index f3bd9ac8..103664b0 100644 --- a/tests/Feature/App/Http/Controllers/Bo/PickupExceptionsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/PickupExceptionsControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Models\PickupException; use App\Models\Slide; use App\Models\User; diff --git a/tests/Feature/App/Http/Controllers/Bo/ProductIncosControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/ProductIncosControllerTest.php index a8d09109..4eaebf42 100644 --- a/tests/Feature/App/Http/Controllers/Bo/ProductIncosControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/ProductIncosControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Dto\ArcadiaIncoDataDto; use App\Dto\ArcadiaIncoPreviewDto; use App\Dto\ProductDto; diff --git a/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php index 0e7fe74c..65431daf 100644 --- a/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Http\Requests\Bo\Products\StoreProductRequest; use App\Models\Customer; use App\Models\Discount; diff --git a/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php index 82d92b58..e0426cd2 100644 --- a/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Http\Requests\Bo\Ranges\StoreRangeRequest; use App\Models\Range; use App\Models\Tag; diff --git a/tests/Feature/App/Http/Controllers/Bo/SettingsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/SettingsControllerTest.php index f049d8a8..379a0730 100644 --- a/tests/Feature/App/Http/Controllers/Bo/SettingsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/SettingsControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Models\Setting; use App\Models\User; diff --git a/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php index 7412ca26..f5f26a89 100644 --- a/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Http\Requests\Bo\Shops\IndexShopRequest; use App\Models\PickupException; use App\Models\Shop; diff --git a/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php index 9e53cdf5..d4f53324 100644 --- a/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Dto\SlideDto; use App\Http\Requests\Bo\Slides\StoreSlideRequest; use App\Models\Slide; diff --git a/tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php index bac7574e..b39e9e55 100644 --- a/tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Models\Tag; use App\Models\User; use Domain\Enums\UserRole; diff --git a/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php index d939d9ca..8bc7fc11 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Ajax; + use App\Models\Customer; use App\Models\Page; use App\Models\Product; diff --git a/tests/Feature/App/Http/Controllers/Fo/Ajax/PickupControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Ajax/PickupControllerTest.php index 2d48d5f5..5691618f 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Ajax/PickupControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Ajax/PickupControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Ajax; + use App\Http\Middleware\CustomerIsEmployed; use App\Http\Middleware\EnsureCustomerEmailIsVerified; use App\Models\Customer; diff --git a/tests/Feature/App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php index 7f8850c3..4cf2759c 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Ajax; + use App\Models\Customer; use App\Models\Discount; use App\Models\Page; diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php index 089bbbf8..08ee2956 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Auth; + use App\Models\Customer; use App\Models\Page; use App\Services\CrmService; diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php index 7ccb1000..a2578756 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Auth; + use App\Exceptions\Crm\CrmCustomerNotActivatedException; use App\Exceptions\CustomerNotEmployedException; use App\Models\Customer; diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php index 386eb62a..5367162b 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Auth; + use App\Contracts\Executor; use App\Cqs\Actions\Customers\RegisterCustomer; use App\Cqs\Actions\Customers\RegisterCustomerInput; diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php index 0cc57efe..fa9e4714 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Auth; + use App\Exceptions\CustomerNotEmployedException; use App\Models\Customer; use App\Models\Page; diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/VerificationControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/VerificationControllerTest.php index d4f02116..8020fc0e 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/VerificationControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/VerificationControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Auth; + use App\Models\Page; use Database\Seeders\ContentSeeder; use Illuminate\Support\Facades\Cache; diff --git a/tests/Feature/App/Http/Controllers/Fo/AuthTest.php b/tests/Feature/App/Http/Controllers/Fo/AuthTest.php index b584cf3a..860fa17f 100644 --- a/tests/Feature/App/Http/Controllers/Fo/AuthTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/AuthTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo; + it('Should required login to access customer dashboard', function (): void { /** @var \Tests\TestCase $this */ diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php index accc6d50..f4e794e4 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Customers; + use App\Models\Customer; use App\Models\Employee; use App\Models\Page; diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php index 96e3d88e..16b8dba1 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Customers; + use App\Dto\OrderDto; use App\Models\Customer; use App\Models\Employee; diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/PasswordControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/PasswordControllerTest.php index 4a6250e1..b827e731 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/PasswordControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/PasswordControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Customers; + use App\Models\Customer; use App\Models\Page; use App\Services\CrmService; diff --git a/tests/Feature/App/Http/Controllers/Fo/NewsletterControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/NewsletterControllerTest.php index 6ed3777e..73822b80 100644 --- a/tests/Feature/App/Http/Controllers/Fo/NewsletterControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/NewsletterControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo; + use App\Models\Page; use App\Services\CrmService; use Database\Seeders\ContentSeeder; diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php index e8f2243f..85288f82 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Pages; + use App\Models\Discount; use App\Models\Page; use App\Models\Product; diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/PageControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/PageControllerTest.php index 49aad6b9..5f0bce16 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/PageControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/PageControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Pages; + use App\Models\Page; use Database\Seeders\ContentSeeder; use Illuminate\Support\Facades\Cache; diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/ProductsControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/ProductsControllerTest.php index 343f1858..627c72ee 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/ProductsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/ProductsControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Pages; + use App\Models\Page; use App\Models\Product; use App\Models\Range; diff --git a/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php b/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php index 7c0f03a5..a7742dcb 100644 --- a/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo; + use App\Contracts\Action; use App\Contracts\ActionInput; use App\Contracts\Executor; diff --git a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php index 601fef81..c71d7b3e 100644 --- a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo; + use App\Contracts\Executor; use App\Cqs\Actions\Orders\ApplyPickTimeSlotOutput; use App\Cqs\Actions\Orders\CancelPendingOrder; diff --git a/tests/Feature/App/Http/Middleware/TrustProxiesTest.php b/tests/Feature/App/Http/Middleware/TrustProxiesTest.php index cf002000..c39e6ab3 100644 --- a/tests/Feature/App/Http/Middleware/TrustProxiesTest.php +++ b/tests/Feature/App/Http/Middleware/TrustProxiesTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Middleware; + use Illuminate\Http\Request; describe('TrustProxies and clientIp resolution', function (): void { diff --git a/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php b/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php index 13fe085a..6a11b545 100644 --- a/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php +++ b/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Basket; + use App\Cqs\Queries\Products\GetProductWithPricingQuery; use App\Http\Requests\Basket\AddBasketRequest; use App\Models\Product; diff --git a/tests/Feature/App/Http/Requests/Basket/RemoveBasketRequestTest.php b/tests/Feature/App/Http/Requests/Basket/RemoveBasketRequestTest.php index 21a9afd2..8c62d6c9 100644 --- a/tests/Feature/App/Http/Requests/Basket/RemoveBasketRequestTest.php +++ b/tests/Feature/App/Http/Requests/Basket/RemoveBasketRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Basket; + use App\Http\Requests\Basket\RemoveBasketRequest; use Domain\Models\ValueObjects\Entities\ProductId; use Illuminate\Support\Facades\Validator; diff --git a/tests/Feature/App/Http/Requests/Bo/Dashboard/DashboardRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Dashboard/DashboardRequestTest.php index 34dcc54c..704ff800 100644 --- a/tests/Feature/App/Http/Requests/Bo/Dashboard/DashboardRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Dashboard/DashboardRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo\Dashboard; + use App\Cqs\Queries\Dashboard\GetBoDashboardQueryInput; use App\Http\Requests\Bo\Dashboard\DashboardRequest; use Infrastructure\Adapters\Services\AppAdminAuthService; diff --git a/tests/Feature/App/Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php index 6c3ba358..eb00e66a 100644 --- a/tests/Feature/App/Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo\Discounts; + use App\Http\Requests\Bo\Discounts\StoreDiscountRequest; use Carbon\Exceptions\InvalidFormatException; use Domain\Enums\DiscountType; diff --git a/tests/Feature/App/Http/Requests/Bo/Faqs/StoreFaqRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Faqs/StoreFaqRequestTest.php index f4ca5fc1..bc48d50f 100644 --- a/tests/Feature/App/Http/Requests/Bo/Faqs/StoreFaqRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Faqs/StoreFaqRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo\Faqs; + use App\Http\Requests\Bo\Faqs\StoreFaqRequest; use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; diff --git a/tests/Feature/App/Http/Requests/Bo/MassActionRequestTest.php b/tests/Feature/App/Http/Requests/Bo/MassActionRequestTest.php index e64bd930..a8be7efc 100644 --- a/tests/Feature/App/Http/Requests/Bo/MassActionRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/MassActionRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo; + use App\Cqs\Actions\Common\ExecuteMassActionInput; use App\Enums\MassActionType; use App\Http\Requests\Bo\MassActionRequest; diff --git a/tests/Feature/App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php index 3caa969c..2d46bbb0 100644 --- a/tests/Feature/App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo\Orders; + use App\Cqs\Queries\Orders\GetBoPaginatedOrdersQueryInput; use App\Http\Requests\Bo\Orders\IndexOrdersRequest; use Domain\Enums\OrderStatus; diff --git a/tests/Feature/App/Http/Requests/Bo/Pages/UpdatePageRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Pages/UpdatePageRequestTest.php index a24a8f98..eea03e24 100644 --- a/tests/Feature/App/Http/Requests/Bo/Pages/UpdatePageRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Pages/UpdatePageRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo\Pages; + use App\Http\Requests\Bo\Pages\UpdatePageRequest; use Infrastructure\Adapters\Services\AppAdminAuthService; diff --git a/tests/Feature/App/Http/Requests/Bo/PickupExceptions/StorePickupExceptionRequestTest.php b/tests/Feature/App/Http/Requests/Bo/PickupExceptions/StorePickupExceptionRequestTest.php index b031d2d0..e9cff09a 100644 --- a/tests/Feature/App/Http/Requests/Bo/PickupExceptions/StorePickupExceptionRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/PickupExceptions/StorePickupExceptionRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo\PickupExceptions; + use App\Http\Requests\Bo\PickupExceptions\StorePickupExceptionRequest; use Domain\Enums\RepeatFrequency; use Infrastructure\Adapters\Services\AppAdminAuthService; diff --git a/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php index 30325936..40f156ab 100644 --- a/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo\Products; + use App\Http\Requests\Bo\Products\IndexProductRequest; use Infrastructure\Adapters\Services\AppAdminAuthService; diff --git a/tests/Feature/App/Http/Requests/Bo/Products/StoreProductRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Products/StoreProductRequestTest.php index 4689e318..232d463b 100644 --- a/tests/Feature/App/Http/Requests/Bo/Products/StoreProductRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Products/StoreProductRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo\Products; + use App\Http\Requests\Bo\Products\StoreProductRequest; use Domain\Enums\ProductBrand; use Illuminate\Http\UploadedFile; diff --git a/tests/Feature/App/Http/Requests/Bo/Ranges/StoreRangeRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Ranges/StoreRangeRequestTest.php index c87b6a21..a7631084 100644 --- a/tests/Feature/App/Http/Requests/Bo/Ranges/StoreRangeRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Ranges/StoreRangeRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo\Ranges; + use App\Http\Requests\Bo\Ranges\StoreRangeRequest; use Illuminate\Http\UploadedFile; use Infrastructure\Adapters\Services\AppAdminAuthService; diff --git a/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php index ba7eeeaa..6789a2d4 100644 --- a/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo\Shops; + use App\Http\Requests\Bo\Shops\IndexShopRequest; use Domain\Models\ValueObjects\Entities\PickupExceptionId; use Illuminate\Contracts\Session\Session; diff --git a/tests/Feature/App/Http/Requests/Bo/Shops/StoreShopRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Shops/StoreShopRequestTest.php index 84ec3a4f..1fae861b 100644 --- a/tests/Feature/App/Http/Requests/Bo/Shops/StoreShopRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Shops/StoreShopRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo\Shops; + use App\Http\Requests\Bo\Shops\StoreShopRequest; use Infrastructure\Adapters\Services\AppAdminAuthService; diff --git a/tests/Feature/App/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequestTest.php index e932daa8..b73b5c14 100644 --- a/tests/Feature/App/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo\Shops; + use App\Http\Requests\Bo\Shops\UpdateShopPickupExceptionsRequest; use App\Models\PickupException; use Illuminate\Foundation\Testing\RefreshDatabase; diff --git a/tests/Feature/App/Http/Requests/Bo/Slides/StoreSlideRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Slides/StoreSlideRequestTest.php index 8a0378b9..f293e8f1 100644 --- a/tests/Feature/App/Http/Requests/Bo/Slides/StoreSlideRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Slides/StoreSlideRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo\Slides; + use App\Http\Requests\Bo\Slides\StoreSlideRequest; use Illuminate\Http\UploadedFile; use Infrastructure\Adapters\Services\AppAdminAuthService; diff --git a/tests/Feature/App/Http/Requests/Bo/Tags/StoreTagRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Tags/StoreTagRequestTest.php index 33dd80b1..2b633a20 100644 --- a/tests/Feature/App/Http/Requests/Bo/Tags/StoreTagRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Tags/StoreTagRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Bo\Tags; + use App\Http\Requests\Bo\Tags\StoreTagRequest; use Infrastructure\Adapters\Services\AppAdminAuthService; diff --git a/tests/Feature/App/Http/Requests/Fo/Ajax/FilterProductsRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Ajax/FilterProductsRequestTest.php index f6664acb..0f9eb206 100644 --- a/tests/Feature/App/Http/Requests/Fo/Ajax/FilterProductsRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Ajax/FilterProductsRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Fo\Ajax; + use App\Http\Requests\Fo\Ajax\FilterProductsRequest; use Illuminate\Support\Facades\Validator; diff --git a/tests/Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php index 5e517429..0731ba49 100644 --- a/tests/Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Fo\Auth; + use App\Cqs\Actions\Customers\RegisterCustomerInput; use App\Http\Requests\Fo\Auth\RegisterRequest; use App\Models\Customer; diff --git a/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php b/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php index 7cce69be..752e9e99 100644 --- a/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Fo; + use App\Cqs\Actions\Contact\SubmitContactFormInput; use App\Http\Requests\Fo\ContactFormRequest; use Domain\Models\ValueObjects\OrderReference; diff --git a/tests/Feature/App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php index 4c8ccaea..e7c403cd 100644 --- a/tests/Feature/App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Fo\Customer; + use App\Cqs\Actions\Crm\UpdateCustomerInput; use App\Http\Requests\Fo\Customer\UpdateInfosRequest; use Infrastructure\Adapters\Services\AppCustomerAuthService; diff --git a/tests/Feature/App/Http/Requests/Fo/Customer/UpdatePasswordRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Customer/UpdatePasswordRequestTest.php index 98999b2f..dbb75d3e 100644 --- a/tests/Feature/App/Http/Requests/Fo/Customer/UpdatePasswordRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Customer/UpdatePasswordRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Fo\Customer; + use App\Http\Requests\Fo\Customer\UpdatePasswordRequest; use Infrastructure\Adapters\Services\AppCustomerAuthService; diff --git a/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php index 8a43fb73..6e4acb0a 100644 --- a/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Fo\Orders; + use App\Cqs\Actions\Orders\PlacePendingOrderInput; use App\Http\Requests\Fo\Orders\ConfirmOrderRequest; use App\Models\Customer; diff --git a/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php index 77094d13..226746f2 100644 --- a/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Fo\Orders; + use App\Cqs\Actions\Orders\ApplyPickTimeSlotInput; use App\Http\Requests\Fo\Orders\PickTimeSlotRequest; use App\Models\Customer; diff --git a/tests/Feature/App/Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php index 9fa35826..341af914 100644 --- a/tests/Feature/App/Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Fo\Orders; + use App\Cqs\Actions\Orders\InitializeOrderTunnelInput; use App\Http\Requests\Fo\Orders\ValidateSummaryRequest; use App\Models\Customer; diff --git a/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php b/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php index 38a9c610..468f5dcf 100644 --- a/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Fo; + use App\Http\Requests\Fo\UnsubscribeNewsletterRequest; use Illuminate\Support\Facades\Validator; use Ramsey\Uuid\Uuid; diff --git a/tests/Feature/App/Jobs/DeleteOldResetTokensTest.php b/tests/Feature/App/Jobs/DeleteOldResetTokensTest.php index 10e957b7..cac020ab 100644 --- a/tests/Feature/App/Jobs/DeleteOldResetTokensTest.php +++ b/tests/Feature/App/Jobs/DeleteOldResetTokensTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Jobs; + use App\Jobs\DeleteOldResetTokens; use App\Models\PasswordReset; use Illuminate\Foundation\Testing\RefreshDatabase; diff --git a/tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php b/tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php index 1bb245b8..333e95e8 100644 --- a/tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php +++ b/tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Jobs; + use App\Jobs\EnsurePublicHolidaysSyncedJob; use App\Models\PickupException; use App\Models\Shop; diff --git a/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php b/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php index 11466af7..333c2b40 100644 --- a/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php +++ b/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Jobs; + use App\Jobs\SendMissingOrderReminderJob; use App\Models\Customer; use App\Models\Employee; diff --git a/tests/Feature/App/Jobs/SendReminderMailTest.php b/tests/Feature/App/Jobs/SendReminderMailTest.php index 31fc3acd..064f44f7 100644 --- a/tests/Feature/App/Jobs/SendReminderMailTest.php +++ b/tests/Feature/App/Jobs/SendReminderMailTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Jobs; + use App\Cqs\Actions\Orders\ClaimTodayOrderReminder; use App\Cqs\Actions\Orders\ReleaseTodayOrderReminder; use App\Jobs\SendReminderMail; diff --git a/tests/Feature/App/Jobs/UpdateSlidesStatusTest.php b/tests/Feature/App/Jobs/UpdateSlidesStatusTest.php index 677b27b2..a5a9933f 100644 --- a/tests/Feature/App/Jobs/UpdateSlidesStatusTest.php +++ b/tests/Feature/App/Jobs/UpdateSlidesStatusTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Jobs; + use App\Jobs\UpdateSlidesStatus; use App\Models\Slide; use Illuminate\Foundation\Testing\RefreshDatabase; diff --git a/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php b/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php index 47c7644a..8e4deb47 100644 --- a/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php +++ b/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Jobs; + use App\Jobs\UpsertShopsPickupExceptionsUsingApiForYear; use App\Models\PickupException; use App\Models\Shop; diff --git a/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php b/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php index fb58349a..df486d24 100644 --- a/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php +++ b/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Listeners; + use App\Listeners\UpdateCustomerLastLogin; use App\Models\Customer; use Domain\Models\ValueObjects\Email; diff --git a/tests/Feature/App/Providers/AuthServiceProviderTest.php b/tests/Feature/App/Providers/AuthServiceProviderTest.php index 1e0042c1..668364de 100644 --- a/tests/Feature/App/Providers/AuthServiceProviderTest.php +++ b/tests/Feature/App/Providers/AuthServiceProviderTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Providers; + use App\Models\Customer; use Domain\Models\ValueObjects\Email; use Illuminate\Auth\Notifications\ResetPassword; diff --git a/tests/Feature/App/Providers/DateMacrosTest.php b/tests/Feature/App/Providers/DateMacrosTest.php index eca479f4..8ef493b6 100644 --- a/tests/Feature/App/Providers/DateMacrosTest.php +++ b/tests/Feature/App/Providers/DateMacrosTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Providers; + use Illuminate\Http\Request; use Illuminate\Support\Facades\Date; diff --git a/tests/Feature/App/Views/ChangeOrderBladeTest.php b/tests/Feature/App/Views/ChangeOrderBladeTest.php index 0c0a11d1..518b596c 100644 --- a/tests/Feature/App/Views/ChangeOrderBladeTest.php +++ b/tests/Feature/App/Views/ChangeOrderBladeTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +namespace Tests\Feature\App\Views; + use App\Models\Tag; use Illuminate\Pagination\LengthAwarePaginator; From 49c17d61f04bcd52fefa28bb438cc862a0b889f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 14:49:53 +0100 Subject: [PATCH 134/183] chore(tests): upgrade to Pest 5, PHPUnit 13, pest-plugin-phpstan and phpstan-webmozart-assert --- .../Actions/Common/ChangeModelOrderInput.php | 3 - .../Common/ChangeModelOrderPositionInput.php | 2 - .../Actions/Common/ToggleModelStarInput.php | 3 - .../Actions/Common/ToggleModelStatusInput.php | 3 - composer.json | 12 +- composer.lock | 1541 ++++++++++------- domain/Models/ValueObjects/DiscountValue.php | 2 +- phpstan.neon | 3 +- tests/Architecture/ApplicationTest.php | 203 ++- tests/Architecture/CodingStandardsTest.php | 83 +- tests/Architecture/DomainTest.php | 139 +- tests/Architecture/InfraTest.php | 11 +- tests/Architecture/NamingConventionsTest.php | 231 ++- 13 files changed, 1298 insertions(+), 938 deletions(-) diff --git a/app/Cqs/Actions/Common/ChangeModelOrderInput.php b/app/Cqs/Actions/Common/ChangeModelOrderInput.php index a640a04a..4d4470bb 100644 --- a/app/Cqs/Actions/Common/ChangeModelOrderInput.php +++ b/app/Cqs/Actions/Common/ChangeModelOrderInput.php @@ -7,7 +7,6 @@ namespace App\Cqs\Actions\Common; use App\Contracts\ActionInput; use App\Interfaces\ModelWithOrder; use Illuminate\Database\Eloquent\Model; -use Webmozart\Assert\Assert; final readonly class ChangeModelOrderInput implements ActionInput { @@ -15,7 +14,5 @@ final readonly class ChangeModelOrderInput implements ActionInput public Model & ModelWithOrder $model, public \SortDirection $direction, ) { - Assert::isInstanceOf($this->model, Model::class); - Assert::isInstanceOf($this->model, ModelWithOrder::class); } } diff --git a/app/Cqs/Actions/Common/ChangeModelOrderPositionInput.php b/app/Cqs/Actions/Common/ChangeModelOrderPositionInput.php index 23ff8799..b15756f9 100644 --- a/app/Cqs/Actions/Common/ChangeModelOrderPositionInput.php +++ b/app/Cqs/Actions/Common/ChangeModelOrderPositionInput.php @@ -15,8 +15,6 @@ final readonly class ChangeModelOrderPositionInput implements ActionInput public Model & ModelWithOrder $model, public int $targetOrder, ) { - Assert::isInstanceOf($this->model, Model::class); - Assert::isInstanceOf($this->model, ModelWithOrder::class); Assert::greaterThanEq($this->targetOrder, 1); } } diff --git a/app/Cqs/Actions/Common/ToggleModelStarInput.php b/app/Cqs/Actions/Common/ToggleModelStarInput.php index 14b6a1ef..616b8b42 100644 --- a/app/Cqs/Actions/Common/ToggleModelStarInput.php +++ b/app/Cqs/Actions/Common/ToggleModelStarInput.php @@ -7,14 +7,11 @@ namespace App\Cqs\Actions\Common; use App\Contracts\ActionInput; use App\Interfaces\ModelWithStar; use Illuminate\Database\Eloquent\Model; -use Webmozart\Assert\Assert; final readonly class ToggleModelStarInput implements ActionInput { public function __construct( public Model & ModelWithStar $model, ) { - Assert::isInstanceOf($this->model, Model::class); - Assert::isInstanceOf($this->model, ModelWithStar::class); } } diff --git a/app/Cqs/Actions/Common/ToggleModelStatusInput.php b/app/Cqs/Actions/Common/ToggleModelStatusInput.php index 293cae51..73d66a4a 100644 --- a/app/Cqs/Actions/Common/ToggleModelStatusInput.php +++ b/app/Cqs/Actions/Common/ToggleModelStatusInput.php @@ -7,14 +7,11 @@ namespace App\Cqs\Actions\Common; use App\Contracts\ActionInput; use App\Interfaces\ModelWithStatus; use Illuminate\Database\Eloquent\Model; -use Webmozart\Assert\Assert; final readonly class ToggleModelStatusInput implements ActionInput { public function __construct( public Model & ModelWithStatus $model, ) { - Assert::isInstanceOf($this->model, Model::class); - Assert::isInstanceOf($this->model, ModelWithStatus::class); } } diff --git a/composer.json b/composer.json index 5e691fec..96aa2a36 100644 --- a/composer.json +++ b/composer.json @@ -44,13 +44,15 @@ "mockery/mockery": "^1.6", "nunomaduro/collision": "^8.6", "nunomaduro/mock-final-classes": "^1.2", - "pestphp/pest": "^4.0", - "pestphp/pest-plugin-faker": "^4.0", - "pestphp/pest-plugin-laravel": "^4.0", - "pestphp/pest-plugin-type-coverage": "^4.0", + "pestphp/pest": "^5.0", + "pestphp/pest-plugin-faker": "^5.0", + "pestphp/pest-plugin-laravel": "^5.0", + "pestphp/pest-plugin-phpstan": "^5.0", + "pestphp/pest-plugin-type-coverage": "^5.0", "php-parallel-lint/php-parallel-lint": "^1.4", "phpstan/phpstan-mockery": "^2.0", - "phpunit/phpunit": "^12.5", + "phpstan/phpstan-webmozart-assert": "^2.0", + "phpunit/phpunit": "^13.0", "slevomat/coding-standard": "^8.30", "spatie/laravel-ignition": "^2.0" }, diff --git a/composer.lock b/composer.lock index fb6a68c9..54c115a3 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "5a27a0a2588a9b83fa85e242925d5128", + "content-hash": "dce4eeb75bd161f29c2bd6141296349c", "packages": [ { "name": "aws/aws-crt-php", @@ -281,7 +281,8 @@ "type": "github" } ], - "time": "2026-09-12T10:28:18+00:00" + "time": "2026-09-12T10:28:18+00:00", + "published-time": "2026-09-12T12:23:30+00:00" }, { "name": "carbonphp/carbon-doctrine-types", @@ -355,7 +356,8 @@ "type": "tidelift" } ], - "time": "2026-09-06T14:11:38+00:00" + "time": "2026-09-06T14:11:38+00:00", + "published-time": "2026-09-06T14:15:00+00:00" }, { "name": "composer/pcre", @@ -583,7 +585,8 @@ "issues": "https://github.com/dflydev/dflydev-dot-access-data/issues", "source": "https://github.com/dflydev/dflydev-dot-access-data/tree/v3.0.3" }, - "time": "2024-07-08T12:26:09+00:00" + "time": "2024-07-08T12:26:09+00:00", + "published-time": "2024-07-08T12:27:13+00:00" }, { "name": "diglactic/laravel-breadcrumbs", @@ -743,7 +746,8 @@ "type": "tidelift" } ], - "time": "2026-10-26T08:14:14+00:00" + "time": "2026-10-26T08:14:14+00:00", + "published-time": "2026-10-26T20:06:59+00:00" }, { "name": "doctrine/lexer", @@ -818,7 +822,8 @@ "type": "tidelift" } ], - "time": "2026-10-01T06:59:29+00:00" + "time": "2026-10-01T06:59:29+00:00", + "published-time": "2026-10-01T07:01:28+00:00" }, { "name": "dragonmantank/cron-expression", @@ -882,7 +887,8 @@ "type": "github" } ], - "time": "2026-10-19T17:53:57+00:00" + "time": "2026-10-19T17:53:57+00:00", + "published-time": "2026-10-19T17:54:31+00:00" }, { "name": "dxw/cidr", @@ -1045,7 +1051,8 @@ "type": "github" } ], - "time": "2025-03-06T22:45:56+00:00" + "time": "2025-03-06T22:45:56+00:00", + "published-time": "2025-03-20T21:39:03+00:00" }, { "name": "ezyang/htmlpurifier", @@ -1230,7 +1237,8 @@ "type": "github" } ], - "time": "2025-12-03T09:33:47+00:00" + "time": "2025-12-03T09:33:47+00:00", + "published-time": "2025-12-03T09:37:01+00:00" }, { "name": "giggsey/libphonenumber-for-php-lite", @@ -1370,7 +1378,8 @@ "type": "tidelift" } ], - "time": "2026-08-24T09:06:52+00:00" + "time": "2026-08-24T09:06:52+00:00", + "published-time": "2026-08-24T09:07:57+00:00" }, { "name": "guzzlehttp/guzzle", @@ -1498,7 +1507,8 @@ "type": "tidelift" } ], - "time": "2026-10-25T21:35:21+00:00" + "time": "2026-10-25T21:35:21+00:00", + "published-time": "2026-10-25T21:37:23+00:00" }, { "name": "guzzlehttp/promises", @@ -1582,7 +1592,8 @@ "type": "tidelift" } ], - "time": "2026-10-18T12:46:59+00:00" + "time": "2026-10-18T12:46:59+00:00", + "published-time": "2026-10-18T12:47:39+00:00" }, { "name": "guzzlehttp/psr7", @@ -1701,7 +1712,8 @@ "type": "tidelift" } ], - "time": "2026-11-12T15:57:42+00:00" + "time": "2026-11-12T15:57:42+00:00", + "published-time": "2026-11-12T15:58:42+00:00" }, { "name": "guzzlehttp/uri-template", @@ -1787,7 +1799,8 @@ "type": "tidelift" } ], - "time": "2026-08-24T17:13:02+00:00" + "time": "2026-08-24T17:13:02+00:00", + "published-time": "2026-08-24T17:13:22+00:00" }, { "name": "intervention/gif", @@ -1991,7 +2004,8 @@ "issues": "https://github.com/Jean85/pretty-package-versions/issues", "source": "https://github.com/Jean85/pretty-package-versions/tree/2.1.1" }, - "time": "2025-03-19T14:43:43+00:00" + "time": "2025-03-19T14:43:43+00:00", + "published-time": "2025-03-19T14:50:06+00:00" }, { "name": "kwaadpepper/serial-int-caster", @@ -2269,7 +2283,8 @@ "issues": "https://github.com/laravel/framework/issues", "source": "https://github.com/laravel/framework" }, - "time": "2026-11-10T15:54:30+00:00" + "time": "2026-11-10T15:54:30+00:00", + "published-time": "2026-11-10T15:55:04+00:00" }, { "name": "laravel/prompts", @@ -2327,7 +2342,8 @@ "support": { "source": "https://github.com/laravel/prompts/tree/v0.3.27" }, - "time": "2026-11-09T16:07:10+00:00" + "time": "2026-11-09T16:07:10+00:00", + "published-time": "2026-11-09T16:09:07+00:00" }, { "name": "laravel/serializable-closure", @@ -2388,7 +2404,8 @@ "issues": "https://github.com/laravel/serializable-closure/issues", "source": "https://github.com/laravel/serializable-closure" }, - "time": "2026-10-14T21:20:29+00:00" + "time": "2026-10-14T21:20:29+00:00", + "published-time": "2026-11-10T16:11:08+00:00" }, { "name": "laravel/tinker", @@ -2678,7 +2695,8 @@ "type": "tidelift" } ], - "time": "2026-10-31T13:35:37+00:00" + "time": "2026-10-31T13:35:37+00:00", + "published-time": "2026-10-31T13:35:57+00:00" }, { "name": "league/config", @@ -2760,7 +2778,8 @@ "type": "github" } ], - "time": "2022-12-11T20:36:23+00:00" + "time": "2022-12-11T20:36:23+00:00", + "published-time": "2022-12-11T20:36:45+00:00" }, { "name": "league/csv", @@ -2938,7 +2957,8 @@ "issues": "https://github.com/thephpleague/flysystem/issues", "source": "https://github.com/thephpleague/flysystem/tree/3.36.0" }, - "time": "2026-09-02T08:00:27+00:00" + "time": "2026-09-02T08:00:27+00:00", + "published-time": "2026-09-02T08:01:40+00:00" }, { "name": "league/flysystem-aws-s3-v3", @@ -3042,7 +3062,8 @@ "support": { "source": "https://github.com/thephpleague/flysystem-local/tree/3.35.3" }, - "time": "2026-08-12T13:29:21+00:00" + "time": "2026-08-12T13:29:21+00:00", + "published-time": "2026-08-22T12:57:18+00:00" }, { "name": "league/flysystem-path-prefixing", @@ -3144,7 +3165,8 @@ "type": "tidelift" } ], - "time": "2026-07-09T11:49:27+00:00" + "time": "2026-07-09T11:49:27+00:00", + "published-time": "2026-07-09T11:50:09+00:00" }, { "name": "league/uri", @@ -3243,7 +3265,8 @@ "type": "github" } ], - "time": "2026-11-04T12:45:07+00:00" + "time": "2026-11-04T12:45:07+00:00", + "published-time": "2026-11-04T13:02:21+00:00" }, { "name": "league/uri-interfaces", @@ -3327,7 +3350,8 @@ "type": "github" } ], - "time": "2026-11-04T12:45:07+00:00" + "time": "2026-11-04T12:45:07+00:00", + "published-time": "2026-11-04T13:02:27+00:00" }, { "name": "maatwebsite/excel", @@ -4108,16 +4132,16 @@ }, { "name": "monolog/monolog", - "version": "3.12.1", + "version": "3.13.0", "source": { "type": "git", "url": "https://github.com/Seldaek/monolog.git", - "reference": "d7059e4c691d05ea1222b5124bed0f961be46e15" + "reference": "1f5f55bb4a9a230ff6d8a4ceccea31d10b0142ac" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Seldaek/monolog/zipball/d7059e4c691d05ea1222b5124bed0f961be46e15", - "reference": "d7059e4c691d05ea1222b5124bed0f961be46e15", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/1f5f55bb4a9a230ff6d8a4ceccea31d10b0142ac", + "reference": "1f5f55bb4a9a230ff6d8a4ceccea31d10b0142ac", "shasum": "" }, "require": { @@ -4197,7 +4221,7 @@ ], "support": { "issues": "https://github.com/Seldaek/monolog/issues", - "source": "https://github.com/Seldaek/monolog/tree/3.12.1" + "source": "https://github.com/Seldaek/monolog/tree/3.13.0" }, "funding": [ { @@ -4209,7 +4233,8 @@ "type": "tidelift" } ], - "time": "2026-09-29T19:21:12+00:00" + "time": "2026-11-16T10:43:05+00:00", + "published-time": "2026-11-16T10:45:37+00:00" }, { "name": "mtdowling/jmespath.php", @@ -4381,7 +4406,8 @@ "type": "tidelift" } ], - "time": "2026-10-25T14:32:48+00:00" + "time": "2026-10-25T14:32:48+00:00", + "published-time": "2026-10-25T14:41:05+00:00" }, { "name": "nette/schema", @@ -4448,7 +4474,8 @@ "issues": "https://github.com/nette/schema/issues", "source": "https://github.com/nette/schema/tree/v1.4.0" }, - "time": "2026-10-22T02:12:50+00:00" + "time": "2026-10-22T02:12:50+00:00", + "published-time": "2026-10-22T02:14:45+00:00" }, { "name": "nette/utils", @@ -4539,7 +4566,8 @@ "issues": "https://github.com/nette/utils/issues", "source": "https://github.com/nette/utils/tree/v4.1.6" }, - "time": "2026-10-20T17:07:56+00:00" + "time": "2026-10-20T17:07:56+00:00", + "published-time": "2026-10-20T17:48:30+00:00" }, { "name": "nikic/php-parser", @@ -4596,7 +4624,8 @@ "issues": "https://github.com/nikic/PHP-Parser/issues", "source": "https://github.com/nikic/PHP-Parser/tree/v5.9.0" }, - "time": "2026-09-13T18:51:52+00:00" + "time": "2026-09-13T18:51:52+00:00", + "published-time": "2026-09-13T18:53:16+00:00" }, { "name": "nunomaduro/termwind", @@ -4683,7 +4712,8 @@ "type": "github" } ], - "time": "2026-11-07T03:57:16+00:00" + "time": "2026-11-07T03:57:16+00:00", + "published-time": "2026-11-07T04:01:24+00:00" }, { "name": "nyholm/psr7", @@ -5237,7 +5267,8 @@ "issues": "https://github.com/paragonie/random_compat/issues", "source": "https://github.com/paragonie/random_compat" }, - "time": "2020-10-15T08:29:30+00:00" + "time": "2020-10-15T08:29:30+00:00", + "published-time": "2020-10-15T08:34:16+00:00" }, { "name": "php-http/discovery", @@ -5608,7 +5639,8 @@ "type": "tidelift" } ], - "time": "2026-08-24T00:54:40+00:00" + "time": "2026-08-24T00:54:40+00:00", + "published-time": "2026-08-24T01:09:05+00:00" }, { "name": "phpseclib/phpseclib", @@ -5838,7 +5870,8 @@ "issues": "https://github.com/php-fig/clock/issues", "source": "https://github.com/php-fig/clock/tree/1.0.0" }, - "time": "2022-11-25T14:36:26+00:00" + "time": "2022-11-25T14:36:26+00:00", + "published-time": "2022-11-25T14:59:22+00:00" }, { "name": "psr/container", @@ -5891,7 +5924,8 @@ "issues": "https://github.com/php-fig/container/issues", "source": "https://github.com/php-fig/container/tree/2.0.2" }, - "time": "2021-11-05T16:47:00+00:00" + "time": "2021-11-05T16:47:00+00:00", + "published-time": "2021-11-05T16:53:27+00:00" }, { "name": "psr/event-dispatcher", @@ -5941,7 +5975,8 @@ "issues": "https://github.com/php-fig/event-dispatcher/issues", "source": "https://github.com/php-fig/event-dispatcher/tree/1.0.0" }, - "time": "2019-01-08T18:20:26+00:00" + "time": "2019-01-08T18:20:26+00:00", + "published-time": "2019-03-25T15:31:44+00:00" }, { "name": "psr/http-client", @@ -5993,7 +6028,8 @@ "support": { "source": "https://github.com/php-fig/http-client" }, - "time": "2023-09-23T14:17:50+00:00" + "time": "2023-09-23T14:17:50+00:00", + "published-time": "2023-09-23T14:18:12+00:00" }, { "name": "psr/http-factory", @@ -6048,7 +6084,8 @@ "support": { "source": "https://github.com/php-fig/http-factory" }, - "time": "2024-04-15T12:06:14+00:00" + "time": "2024-04-15T12:06:14+00:00", + "published-time": "2024-05-10T07:32:19+00:00" }, { "name": "psr/http-message", @@ -6101,7 +6138,8 @@ "support": { "source": "https://github.com/php-fig/http-message/tree/2.0" }, - "time": "2023-04-04T09:54:51+00:00" + "time": "2023-04-04T09:54:51+00:00", + "published-time": "2023-04-04T09:55:35+00:00" }, { "name": "psr/log", @@ -6151,7 +6189,8 @@ "support": { "source": "https://github.com/php-fig/log/tree/3.0.2" }, - "time": "2024-09-11T13:17:53+00:00" + "time": "2024-09-11T13:17:53+00:00", + "published-time": "2024-09-11T13:21:14+00:00" }, { "name": "psr/simple-cache", @@ -6202,7 +6241,8 @@ "support": { "source": "https://github.com/php-fig/simple-cache/tree/3.0.0" }, - "time": "2021-10-29T13:26:27+00:00" + "time": "2021-10-29T13:26:27+00:00", + "published-time": "2021-10-29T13:27:19+00:00" }, { "name": "psy/psysh", @@ -6325,7 +6365,8 @@ "issues": "https://github.com/ralouphie/getallheaders/issues", "source": "https://github.com/ralouphie/getallheaders/tree/develop" }, - "time": "2019-03-08T08:55:37+00:00" + "time": "2019-03-08T08:55:37+00:00", + "published-time": "2019-03-08T09:01:32+00:00" }, { "name": "ramsey/collection", @@ -6401,20 +6442,21 @@ "issues": "https://github.com/ramsey/collection/issues", "source": "https://github.com/ramsey/collection/tree/2.1.1" }, - "time": "2025-03-22T05:38:12+00:00" + "time": "2025-03-22T05:38:12+00:00", + "published-time": "2025-03-22T05:39:22+00:00" }, { "name": "ramsey/uuid", - "version": "4.9.4", + "version": "4.10.0", "source": { "type": "git", "url": "https://github.com/ramsey/uuid.git", - "reference": "75d73f48d02797c2c285a7e9f348fadc0102ffe2" + "reference": "f9aa3efc8015fcbc013d84d699583b268ccb593a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/ramsey/uuid/zipball/75d73f48d02797c2c285a7e9f348fadc0102ffe2", - "reference": "75d73f48d02797c2c285a7e9f348fadc0102ffe2", + "url": "https://api.github.com/repos/ramsey/uuid/zipball/f9aa3efc8015fcbc013d84d699583b268ccb593a", + "reference": "f9aa3efc8015fcbc013d84d699583b268ccb593a", "shasum": "" }, "require": { @@ -6426,23 +6468,22 @@ "rhumsaa/uuid": "self.version" }, "require-dev": { - "captainhook/captainhook": "^5.25", - "captainhook/plugin-composer": "^5.3", - "dealerdirect/phpcodesniffer-composer-installer": "^1.0", - "ergebnis/composer-normalize": "^2.47", - "mockery/mockery": "^1.6", - "paragonie/random-lib": "^2", - "php-mock/php-mock": "^2.6", - "php-mock/php-mock-mockery": "^1.5", + "captainhook/captainhook": "^5.29.3", + "captainhook/plugin-composer": "^5.3.3", + "dealerdirect/phpcodesniffer-composer-installer": "^1.2.1", + "mockery/mockery": "^1.6.15", + "paragonie/random-lib": "^2.0.3", + "php-mock/php-mock": "^2.7.0", + "php-mock/php-mock-mockery": "^1.5.0", "php-parallel-lint/php-parallel-lint": "^1.4.0", "phpbench/phpbench": "^1.2.14", - "phpstan/extension-installer": "^1.4", - "phpstan/phpstan": "^2.1", - "phpstan/phpstan-mockery": "^2.0", - "phpstan/phpstan-phpunit": "^2.0", - "phpunit/phpunit": "^9.6", - "slevomat/coding-standard": "^8.18", - "squizlabs/php_codesniffer": "^3.13" + "phpstan/extension-installer": "^1.4.3", + "phpstan/phpstan": "^2.3.5", + "phpstan/phpstan-mockery": "^2.0.0", + "phpstan/phpstan-phpunit": "^2.1.2", + "phpunit/phpunit": "^9.6.39", + "slevomat/coding-standard": "^8.31.3", + "squizlabs/php_codesniffer": "^4.0.4" }, "suggest": { "ext-bcmath": "Enables faster math with arbitrary-precision integers using BCMath.", @@ -6477,9 +6518,10 @@ ], "support": { "issues": "https://github.com/ramsey/uuid/issues", - "source": "https://github.com/ramsey/uuid/tree/4.9.4" + "source": "https://github.com/ramsey/uuid/tree/4.10.0" }, - "time": "2026-09-16T11:39:30+00:00" + "time": "2026-11-14T23:23:20+00:00", + "published-time": "2026-11-14T23:35:39+00:00" }, { "name": "respect/stringifier", @@ -7230,7 +7272,8 @@ "type": "tidelift" } ], - "time": "2026-10-12T14:32:04+00:00" + "time": "2026-10-12T14:32:04+00:00", + "published-time": "2026-10-14T06:48:32+00:00" }, { "name": "symfony/console", @@ -7330,7 +7373,8 @@ "type": "tidelift" } ], - "time": "2026-11-04T07:07:11+00:00" + "time": "2026-11-04T07:07:11+00:00", + "published-time": "2026-11-04T11:31:39+00:00" }, { "name": "symfony/css-selector", @@ -7399,7 +7443,8 @@ "type": "tidelift" } ], - "time": "2026-10-18T14:56:39+00:00" + "time": "2026-10-18T14:56:39+00:00", + "published-time": "2026-10-28T18:24:46+00:00" }, { "name": "symfony/deprecation-contracts", @@ -7470,7 +7515,8 @@ "type": "tidelift" } ], - "time": "2026-09-16T14:15:10+00:00" + "time": "2026-09-16T14:15:10+00:00", + "published-time": "2026-11-04T11:25:34+00:00" }, { "name": "symfony/dom-crawler", @@ -7621,7 +7667,8 @@ "type": "tidelift" } ], - "time": "2026-10-25T14:40:25+00:00" + "time": "2026-10-25T14:40:25+00:00", + "published-time": "2026-10-28T18:24:13+00:00" }, { "name": "symfony/event-dispatcher", @@ -7707,7 +7754,8 @@ "type": "tidelift" } ], - "time": "2026-08-21T17:47:34+00:00" + "time": "2026-08-21T17:47:34+00:00", + "published-time": "2026-08-22T13:46:58+00:00" }, { "name": "symfony/event-dispatcher-contracts", @@ -7787,7 +7835,8 @@ "type": "tidelift" } ], - "time": "2026-09-16T14:15:10+00:00" + "time": "2026-09-16T14:15:10+00:00", + "published-time": "2026-11-04T11:25:36+00:00" }, { "name": "symfony/filesystem", @@ -7926,7 +7975,8 @@ "type": "tidelift" } ], - "time": "2026-11-02T10:58:30+00:00" + "time": "2026-11-02T10:58:30+00:00", + "published-time": "2026-11-04T11:31:20+00:00" }, { "name": "symfony/http-foundation", @@ -8007,7 +8057,8 @@ "type": "tidelift" } ], - "time": "2026-11-04T08:39:20+00:00" + "time": "2026-11-04T08:39:20+00:00", + "published-time": "2026-11-04T11:31:54+00:00" }, { "name": "symfony/http-kernel", @@ -8117,7 +8168,8 @@ "type": "tidelift" } ], - "time": "2026-11-04T11:29:46+00:00" + "time": "2026-11-04T11:29:46+00:00", + "published-time": "2026-11-04T11:32:19+00:00" }, { "name": "symfony/mailer", @@ -8197,7 +8249,8 @@ "type": "tidelift" } ], - "time": "2026-10-23T17:06:53+00:00" + "time": "2026-10-23T17:06:53+00:00", + "published-time": "2026-10-28T18:23:52+00:00" }, { "name": "symfony/mime", @@ -8283,7 +8336,8 @@ "type": "tidelift" } ], - "time": "2026-10-28T17:58:38+00:00" + "time": "2026-10-28T17:58:38+00:00", + "published-time": "2026-10-28T18:23:55+00:00" }, { "name": "symfony/options-resolver", @@ -8437,7 +8491,8 @@ "type": "tidelift" } ], - "time": "2026-04-10T16:19:22+00:00" + "time": "2026-04-10T16:19:22+00:00", + "published-time": "2026-04-26T14:44:50+00:00" }, { "name": "symfony/polyfill-intl-grapheme", @@ -8519,7 +8574,8 @@ "type": "tidelift" } ], - "time": "2026-10-15T09:18:53+00:00" + "time": "2026-10-15T09:18:53+00:00", + "published-time": "2026-10-28T10:07:44+00:00" }, { "name": "symfony/polyfill-intl-idn", @@ -8606,7 +8662,8 @@ "type": "tidelift" } ], - "time": "2026-09-23T14:40:04+00:00" + "time": "2026-09-23T14:40:04+00:00", + "published-time": "2026-09-30T10:23:39+00:00" }, { "name": "symfony/polyfill-intl-normalizer", @@ -8691,7 +8748,8 @@ "type": "tidelift" } ], - "time": "2026-09-23T22:02:09+00:00" + "time": "2026-09-23T22:02:09+00:00", + "published-time": "2026-09-30T10:23:47+00:00" }, { "name": "symfony/polyfill-mbstring", @@ -8776,7 +8834,8 @@ "type": "tidelift" } ], - "time": "2026-10-28T09:35:49+00:00" + "time": "2026-10-28T09:35:49+00:00", + "published-time": "2026-10-28T10:07:45+00:00" }, { "name": "symfony/polyfill-php80", @@ -8860,7 +8919,8 @@ "type": "tidelift" } ], - "time": "2026-09-25T15:50:05+00:00" + "time": "2026-09-25T15:50:05+00:00", + "published-time": "2026-09-30T10:23:35+00:00" }, { "name": "symfony/polyfill-php84", @@ -8940,20 +9000,21 @@ "type": "tidelift" } ], - "time": "2026-09-23T22:01:09+00:00" + "time": "2026-09-23T22:01:09+00:00", + "published-time": "2026-09-30T10:23:33+00:00" }, { "name": "symfony/polyfill-php85", - "version": "v1.43.0", + "version": "v1.44.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php85.git", - "reference": "86a42cbcc07adc331481a5ab310a4024bfc227f6" + "reference": "94c794cb5ba51784bc259f11e9f128593297d8dc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/86a42cbcc07adc331481a5ab310a4024bfc227f6", - "reference": "86a42cbcc07adc331481a5ab310a4024bfc227f6", + "url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/94c794cb5ba51784bc259f11e9f128593297d8dc", + "reference": "94c794cb5ba51784bc259f11e9f128593297d8dc", "shasum": "" }, "require": { @@ -9000,7 +9061,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php85/tree/v1.43.0" + "source": "https://github.com/symfony/polyfill-php85/tree/v1.44.0" }, "funding": [ { @@ -9020,7 +9081,8 @@ "type": "tidelift" } ], - "time": "2026-09-25T15:46:47+00:00" + "time": "2026-10-30T15:20:09+00:00", + "published-time": "2026-11-15T14:20:22+00:00" }, { "name": "symfony/polyfill-php86", @@ -9100,7 +9162,8 @@ "type": "tidelift" } ], - "time": "2026-09-25T15:46:47+00:00" + "time": "2026-09-25T15:46:47+00:00", + "published-time": "2026-09-30T10:23:43+00:00" }, { "name": "symfony/polyfill-time", @@ -9183,7 +9246,8 @@ "type": "tidelift" } ], - "time": "2026-08-07T13:08:13+00:00" + "time": "2026-08-07T13:08:13+00:00", + "published-time": "2026-08-24T11:45:15+00:00" }, { "name": "symfony/polyfill-uuid", @@ -9266,7 +9330,8 @@ "type": "tidelift" } ], - "time": "2026-09-24T05:20:52+00:00" + "time": "2026-09-24T05:20:52+00:00", + "published-time": "2026-09-30T10:23:49+00:00" }, { "name": "symfony/process", @@ -9331,7 +9396,8 @@ "type": "tidelift" } ], - "time": "2026-10-25T14:40:25+00:00" + "time": "2026-10-25T14:40:25+00:00", + "published-time": "2026-10-28T18:25:20+00:00" }, { "name": "symfony/psr-http-message-bridge", @@ -9498,7 +9564,8 @@ "type": "tidelift" } ], - "time": "2026-11-04T08:39:20+00:00" + "time": "2026-11-04T08:39:20+00:00", + "published-time": "2026-11-04T11:30:59+00:00" }, { "name": "symfony/service-contracts", @@ -9585,7 +9652,8 @@ "type": "tidelift" } ], - "time": "2026-10-20T17:38:25+00:00" + "time": "2026-10-20T17:38:25+00:00", + "published-time": "2026-11-04T11:25:33+00:00" }, { "name": "symfony/string", @@ -9675,7 +9743,8 @@ "type": "tidelift" } ], - "time": "2026-10-23T17:06:53+00:00" + "time": "2026-10-23T17:06:53+00:00", + "published-time": "2026-10-28T18:24:27+00:00" }, { "name": "symfony/translation", @@ -9768,7 +9837,8 @@ "type": "tidelift" } ], - "time": "2026-11-01T22:27:46+00:00" + "time": "2026-11-01T22:27:46+00:00", + "published-time": "2026-11-04T11:31:54+00:00" }, { "name": "symfony/translation-contracts", @@ -9850,7 +9920,8 @@ "type": "tidelift" } ], - "time": "2026-10-03T08:17:19+00:00" + "time": "2026-10-03T08:17:19+00:00", + "published-time": "2026-11-04T11:25:31+00:00" }, { "name": "symfony/uid", @@ -9928,7 +9999,8 @@ "type": "tidelift" } ], - "time": "2026-10-12T14:32:04+00:00" + "time": "2026-10-12T14:32:04+00:00", + "published-time": "2026-10-14T06:48:53+00:00" }, { "name": "symfony/var-dumper", @@ -10015,7 +10087,8 @@ "type": "tidelift" } ], - "time": "2026-10-26T21:55:04+00:00" + "time": "2026-10-26T21:55:04+00:00", + "published-time": "2026-10-28T18:25:26+00:00" }, { "name": "tbachert/spi", @@ -10122,7 +10195,8 @@ "issues": "https://github.com/tijsverkoyen/CssToInlineStyles/issues", "source": "https://github.com/tijsverkoyen/CssToInlineStyles/tree/v2.4.0" }, - "time": "2025-12-02T11:56:42+00:00" + "time": "2025-12-02T11:56:42+00:00", + "published-time": "2025-12-11T21:29:16+00:00" }, { "name": "uwil/arcadia-api-php-client", @@ -10713,7 +10787,8 @@ "type": "tidelift" } ], - "time": "2026-10-25T16:26:19+00:00" + "time": "2026-10-25T16:26:19+00:00", + "published-time": "2026-10-25T16:26:50+00:00" }, { "name": "voku/portable-ascii", @@ -10787,20 +10862,21 @@ "type": "tidelift" } ], - "time": "2026-04-26T05:33:54+00:00" + "time": "2026-04-26T05:33:54+00:00", + "published-time": "2026-04-26T05:43:38+00:00" }, { "name": "webmozart/assert", - "version": "2.5.0", + "version": "2.5.1", "source": { "type": "git", "url": "https://github.com/webmozarts/assert.git", - "reference": "8a163706bbcac613733dba03f51e13b5eb1bb819" + "reference": "e578132c01bd0c64108386ab20d8217cd175ddec" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/webmozarts/assert/zipball/8a163706bbcac613733dba03f51e13b5eb1bb819", - "reference": "8a163706bbcac613733dba03f51e13b5eb1bb819", + "url": "https://api.github.com/repos/webmozarts/assert/zipball/e578132c01bd0c64108386ab20d8217cd175ddec", + "reference": "e578132c01bd0c64108386ab20d8217cd175ddec", "shasum": "" }, "require": { @@ -10851,9 +10927,10 @@ ], "support": { "issues": "https://github.com/webmozarts/assert/issues", - "source": "https://github.com/webmozarts/assert/tree/2.5.0" + "source": "https://github.com/webmozarts/assert/tree/2.5.1" }, - "time": "2026-10-05T23:14:19+00:00" + "time": "2026-11-15T13:41:13+00:00", + "published-time": "2026-11-15T13:41:42+00:00" } ], "packages-dev": [ @@ -11110,16 +11187,16 @@ }, { "name": "brianium/paratest", - "version": "v7.20.0", + "version": "v7.29.0", "source": { "type": "git", "url": "https://github.com/paratestphp/paratest.git", - "reference": "81c80677c9ec0ed4ef16b246167f11dec81a6e3d" + "reference": "2e4bbc8340be877d4f1a82f993a387e2c8c76272" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/paratestphp/paratest/zipball/81c80677c9ec0ed4ef16b246167f11dec81a6e3d", - "reference": "81c80677c9ec0ed4ef16b246167f11dec81a6e3d", + "url": "https://api.github.com/repos/paratestphp/paratest/zipball/2e4bbc8340be877d4f1a82f993a387e2c8c76272", + "reference": "2e4bbc8340be877d4f1a82f993a387e2c8c76272", "shasum": "" }, "require": { @@ -11127,27 +11204,27 @@ "ext-pcre": "*", "ext-reflection": "*", "ext-simplexml": "*", - "fidry/cpu-core-counter": "^1.3.0", + "fidry/cpu-core-counter": "^1.4.1", "jean85/pretty-package-versions": "^2.1.1", - "php": "~8.3.0 || ~8.4.0 || ~8.5.0", - "phpunit/php-code-coverage": "^12.5.3 || ^13.0.1", - "phpunit/php-file-iterator": "^6.0.1 || ^7", - "phpunit/php-timer": "^8 || ^9", - "phpunit/phpunit": "^12.5.14 || ^13.0.5", - "sebastian/environment": "^8.0.3 || ^9", - "symfony/console": "^7.4.7 || ^8.0.7", - "symfony/process": "^7.4.5 || ^8.0.5" + "php": "~8.4.0 || ~8.5.0 || ~8.6.0", + "phpunit/php-code-coverage": "^14.5.2", + "phpunit/php-file-iterator": "^7.0.2", + "phpunit/php-timer": "^9", + "phpunit/phpunit": "^13.4.7", + "sebastian/environment": "^9.3.3", + "symfony/console": "^7.4.20 || ^8.1.8", + "symfony/process": "^7.4.19 || ^8.1.7" }, "require-dev": { "doctrine/coding-standard": "^14.0.0", "ext-pcntl": "*", "ext-pcov": "*", "ext-posix": "*", - "phpstan/phpstan": "^2.1.44", - "phpstan/phpstan-deprecation-rules": "^2.0.4", - "phpstan/phpstan-phpunit": "^2.0.16", - "phpstan/phpstan-strict-rules": "^2.0.10", - "symfony/filesystem": "^7.4.6 || ^8.0.6" + "phpstan/phpstan": "^2.3.5", + "phpstan/phpstan-deprecation-rules": "^2.0.5", + "phpstan/phpstan-phpunit": "^2.1.2", + "phpstan/phpstan-strict-rules": "^2.1.1", + "symfony/filesystem": "^7.4.18 || ^8.1.6" }, "bin": [ "bin/paratest", @@ -11187,7 +11264,7 @@ ], "support": { "issues": "https://github.com/paratestphp/paratest/issues", - "source": "https://github.com/paratestphp/paratest/tree/v7.20.0" + "source": "https://github.com/paratestphp/paratest/tree/v7.29.0" }, "funding": [ { @@ -11199,7 +11276,8 @@ "type": "paypal" } ], - "time": "2026-03-29T15:46:14+00:00" + "time": "2026-11-14T20:49:33+00:00", + "published-time": "2026-11-14T20:50:36+00:00" }, { "name": "codezero/browser-locale", @@ -11340,72 +11418,6 @@ ], "time": "2026-11-03T10:10:19+00:00" }, - { - "name": "composer/xdebug-handler", - "version": "3.0.5", - "source": { - "type": "git", - "url": "https://github.com/composer/xdebug-handler.git", - "reference": "6c1925561632e83d60a44492e0b344cf48ab85ef" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/composer/xdebug-handler/zipball/6c1925561632e83d60a44492e0b344cf48ab85ef", - "reference": "6c1925561632e83d60a44492e0b344cf48ab85ef", - "shasum": "" - }, - "require": { - "composer/pcre": "^1 || ^2 || ^3", - "php": "^7.2.5 || ^8.0", - "psr/log": "^1 || ^2 || ^3" - }, - "require-dev": { - "phpstan/phpstan": "^1.0", - "phpstan/phpstan-strict-rules": "^1.1", - "phpunit/phpunit": "^8.5 || ^9.6 || ^10.5" - }, - "type": "library", - "autoload": { - "psr-4": { - "Composer\\XdebugHandler\\": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "John Stevenson", - "email": "john-stevenson@blueyonder.co.uk" - } - ], - "description": "Restarts a process without Xdebug.", - "keywords": [ - "Xdebug", - "performance" - ], - "support": { - "irc": "ircs://irc.libera.chat:6697/composer", - "issues": "https://github.com/composer/xdebug-handler/issues", - "source": "https://github.com/composer/xdebug-handler/tree/3.0.5" - }, - "funding": [ - { - "url": "https://packagist.com", - "type": "custom" - }, - { - "url": "https://github.com/composer", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/composer/composer", - "type": "tidelift" - } - ], - "time": "2024-05-06T16:37:16+00:00" - }, { "name": "dealerdirect/phpcodesniffer-composer-installer", "version": "v1.2.1", @@ -11605,7 +11617,8 @@ "issues": "https://github.com/doctrine/deprecations/issues", "source": "https://github.com/doctrine/deprecations/tree/1.2.0" }, - "time": "2026-11-11T10:04:49+00:00" + "time": "2026-11-11T10:04:49+00:00", + "published-time": "2026-11-11T10:12:24+00:00" }, { "name": "dragon-code/contracts", @@ -11838,16 +11851,16 @@ }, { "name": "entropy/entropy", - "version": "0.4.36", + "version": "0.4.37", "source": { "type": "git", "url": "https://github.com/TomasVotruba/entropy.git", - "reference": "9f08272a96275d22a9d9808a32581392920626db" + "reference": "57bd06e1652f3c38148944b4880ee3b6e6284da3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/TomasVotruba/entropy/zipball/9f08272a96275d22a9d9808a32581392920626db", - "reference": "9f08272a96275d22a9d9808a32581392920626db", + "url": "https://api.github.com/repos/TomasVotruba/entropy/zipball/57bd06e1652f3c38148944b4880ee3b6e6284da3", + "reference": "57bd06e1652f3c38148944b4880ee3b6e6284da3", "shasum": "" }, "require": { @@ -11883,9 +11896,10 @@ "description": "Entropy framework", "support": { "issues": "https://github.com/TomasVotruba/entropy/issues", - "source": "https://github.com/TomasVotruba/entropy/tree/0.4.36" + "source": "https://github.com/TomasVotruba/entropy/tree/0.4.37" }, - "time": "2026-10-26T16:46:17+00:00" + "time": "2026-11-14T16:57:42+00:00", + "published-time": "2026-11-14T16:57:58+00:00" }, { "name": "fakerphp/faker", @@ -11948,7 +11962,8 @@ "issues": "https://github.com/FakerPHP/Faker/issues", "source": "https://github.com/FakerPHP/Faker/tree/v1.24.1" }, - "time": "2024-11-21T13:46:39+00:00" + "time": "2024-11-21T13:46:39+00:00", + "published-time": "2024-11-21T13:47:18+00:00" }, { "name": "fidry/cpu-core-counter", @@ -12010,7 +12025,8 @@ "type": "github" } ], - "time": "2026-09-29T22:11:39+00:00" + "time": "2026-09-29T22:11:39+00:00", + "published-time": "2026-09-29T22:12:43+00:00" }, { "name": "filp/whoops", @@ -12081,7 +12097,8 @@ "type": "github" } ], - "time": "2026-11-09T23:30:17+00:00" + "time": "2026-11-09T23:30:17+00:00", + "published-time": "2026-11-09T23:32:45+00:00" }, { "name": "hamcrest/hamcrest-php", @@ -13834,7 +13851,8 @@ "type": "github" } ], - "time": "2026-08-11T10:17:44+00:00" + "time": "2026-08-11T10:17:44+00:00", + "published-time": "2026-08-11T10:29:20+00:00" }, { "name": "nunomaduro/collision", @@ -13930,7 +13948,8 @@ "type": "patreon" } ], - "time": "2026-11-10T17:06:52+00:00" + "time": "2026-11-10T17:06:52+00:00", + "published-time": "2026-11-10T17:23:22+00:00" }, { "name": "nunomaduro/mock-final-classes", @@ -14082,46 +14101,48 @@ "type": "patreon" } ], - "time": "2026-04-12T12:06:31+00:00" + "time": "2026-04-12T12:06:31+00:00", + "published-time": "2026-04-12T12:07:55+00:00" }, { "name": "pestphp/pest", - "version": "v4.7.8", + "version": "v5.3.6", "source": { "type": "git", "url": "https://github.com/pestphp/pest.git", - "reference": "5b2293f67adcf1b2320b33f521b94a692d18f360" + "reference": "848c740a44e5994e524f35ce9d4345bacf0dec74" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pestphp/pest/zipball/5b2293f67adcf1b2320b33f521b94a692d18f360", - "reference": "5b2293f67adcf1b2320b33f521b94a692d18f360", + "url": "https://api.github.com/repos/pestphp/pest/zipball/848c740a44e5994e524f35ce9d4345bacf0dec74", + "reference": "848c740a44e5994e524f35ce9d4345bacf0dec74", "shasum": "" }, "require": { - "brianium/paratest": "^7.20.0", - "composer/xdebug-handler": "^3.0.5", - "nunomaduro/collision": "^8.9.5", - "nunomaduro/termwind": "^2.4.0", - "pestphp/pest-plugin": "^4.0.0", - "pestphp/pest-plugin-arch": "^4.0.2", - "pestphp/pest-plugin-mutate": "^4.0.1", - "pestphp/pest-plugin-profanity": "^4.2.1", - "php": "^8.3.0", - "phpunit/phpunit": "^12.5.33", - "symfony/process": "^7.4.13|^8.1.0" + "brianium/paratest": "^7.29.0", + "nunomaduro/collision": "^8.9.6", + "nunomaduro/termwind": "^2.4.1", + "pestphp/pest-plugin": "^5.0.0", + "pestphp/pest-plugin-arch": "^5.0.0", + "pestphp/pest-plugin-mutate": "^5.0.2", + "pestphp/pest-plugin-profanity": "^5.0.1", + "php": "^8.4", + "phpunit/phpunit": "^13.4.7", + "symfony/process": "^8.1.10" }, "conflict": { "filp/whoops": "<2.18.3", - "phpunit/phpunit": ">12.5.33", + "laravel/boost": "<2.6.0", + "phpunit/phpunit": ">13.4.7", "sebastian/exporter": "<7.0.0", "webmozart/assert": "<1.11.0" }, "require-dev": { - "mrpunyapal/peststan": "^0.2.12", - "pestphp/pest-dev-tools": "^4.1.0", - "pestphp/pest-plugin-browser": "^4.3.1", - "pestphp/pest-plugin-type-coverage": "^4.0.4", + "pestphp/pest-dev-tools": "^5.0.0", + "pestphp/pest-plugin-browser": "^5.2.0", + "pestphp/pest-plugin-phpstan": "^5.3.1", + "pestphp/pest-plugin-rector": "^5.0.6", + "pestphp/pest-plugin-type-coverage": "^5.1.0", "psy/psysh": "^0.12.24" }, "bin": [ @@ -14149,6 +14170,7 @@ "Pest\\Plugins\\Verbose", "Pest\\Plugins\\Version", "Pest\\Plugins\\Shard", + "Pest\\Plugins\\Tia", "Pest\\Plugins\\Parallel" ] }, @@ -14188,7 +14210,7 @@ ], "support": { "issues": "https://github.com/pestphp/pest/issues", - "source": "https://github.com/pestphp/pest/tree/v4.7.8" + "source": "https://github.com/pestphp/pest/tree/v5.3.6" }, "funding": [ { @@ -14200,34 +14222,35 @@ "type": "github" } ], - "time": "2026-08-03T20:49:44+00:00" + "time": "2026-11-14T21:14:48+00:00", + "published-time": "2026-11-14T21:21:17+00:00" }, { "name": "pestphp/pest-plugin", - "version": "v4.0.0", + "version": "v5.0.0", "source": { "type": "git", "url": "https://github.com/pestphp/pest-plugin.git", - "reference": "9d4b93d7f73d3f9c3189bb22c220fef271cdf568" + "reference": "87283f41aafa2561b7618be53eab00f2d06f4140" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pestphp/pest-plugin/zipball/9d4b93d7f73d3f9c3189bb22c220fef271cdf568", - "reference": "9d4b93d7f73d3f9c3189bb22c220fef271cdf568", + "url": "https://api.github.com/repos/pestphp/pest-plugin/zipball/87283f41aafa2561b7618be53eab00f2d06f4140", + "reference": "87283f41aafa2561b7618be53eab00f2d06f4140", "shasum": "" }, "require": { "composer-plugin-api": "^2.0.0", "composer-runtime-api": "^2.2.2", - "php": "^8.3" + "php": "^8.4" }, "conflict": { - "pestphp/pest": "<4.0.0" + "pestphp/pest": "<5.0.0" }, "require-dev": { - "composer/composer": "^2.8.10", - "pestphp/pest": "^4.0.0", - "pestphp/pest-dev-tools": "^4.0.0" + "composer/composer": "^2.10.2", + "pestphp/pest": "^5.0.0", + "pestphp/pest-dev-tools": "^5.0.0" }, "type": "composer-plugin", "extra": { @@ -14254,7 +14277,7 @@ "unit" ], "support": { - "source": "https://github.com/pestphp/pest-plugin/tree/v4.0.0" + "source": "https://github.com/pestphp/pest-plugin/tree/v5.0.0" }, "funding": [ { @@ -14270,30 +14293,34 @@ "type": "patreon" } ], - "time": "2025-08-20T12:35:58+00:00" + "time": "2026-07-18T17:10:45+00:00", + "published-time": "2026-07-28T14:33:43+00:00" }, { "name": "pestphp/pest-plugin-arch", - "version": "v4.0.2", + "version": "v5.0.0", "source": { "type": "git", "url": "https://github.com/pestphp/pest-plugin-arch.git", - "reference": "3fb0d02a91b9da504b139dc7ab2a31efb7c3215c" + "reference": "244465d5dc9ea9fb5ac5c9badb7eb47d1594e4c1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pestphp/pest-plugin-arch/zipball/3fb0d02a91b9da504b139dc7ab2a31efb7c3215c", - "reference": "3fb0d02a91b9da504b139dc7ab2a31efb7c3215c", + "url": "https://api.github.com/repos/pestphp/pest-plugin-arch/zipball/244465d5dc9ea9fb5ac5c9badb7eb47d1594e4c1", + "reference": "244465d5dc9ea9fb5ac5c9badb7eb47d1594e4c1", "shasum": "" }, "require": { - "pestphp/pest-plugin": "^4.0.0", - "php": "^8.3", + "pestphp/pest-plugin": "^5.0.0", + "php": "^8.4", "ta-tikoma/phpunit-architecture-test": "^0.8.7" }, + "conflict": { + "pestphp/pest": "<5.0.0" + }, "require-dev": { - "pestphp/pest": "^4.4.6", - "pestphp/pest-dev-tools": "^4.1.0" + "pestphp/pest": "^5.0.0", + "pestphp/pest-dev-tools": "^5.0.0" }, "type": "library", "extra": { @@ -14328,7 +14355,7 @@ "unit" ], "support": { - "source": "https://github.com/pestphp/pest-plugin-arch/tree/v4.0.2" + "source": "https://github.com/pestphp/pest-plugin-arch/tree/v5.0.0" }, "funding": [ { @@ -14340,29 +14367,33 @@ "type": "github" } ], - "time": "2026-04-10T17:20:19+00:00" + "time": "2026-07-21T07:48:55+00:00", + "published-time": "2026-07-28T14:33:47+00:00" }, { "name": "pestphp/pest-plugin-faker", - "version": "v4.0.0", + "version": "v5.0.0", "source": { "type": "git", "url": "https://github.com/pestphp/pest-plugin-faker.git", - "reference": "afb07eeca115cc19a2f5e20a4ec113ee6e26d4ec" + "reference": "131cf00ecf0814dc0969633763ab7577a714e8d6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pestphp/pest-plugin-faker/zipball/afb07eeca115cc19a2f5e20a4ec113ee6e26d4ec", - "reference": "afb07eeca115cc19a2f5e20a4ec113ee6e26d4ec", + "url": "https://api.github.com/repos/pestphp/pest-plugin-faker/zipball/131cf00ecf0814dc0969633763ab7577a714e8d6", + "reference": "131cf00ecf0814dc0969633763ab7577a714e8d6", "shasum": "" }, "require": { "fakerphp/faker": "^1.24.1", - "pestphp/pest": "^4.0.0", - "php": "^8.3.0" + "pestphp/pest": "^5.0.0", + "php": "^8.4" + }, + "conflict": { + "pestphp/pest": "<5.0.0" }, "require-dev": { - "pestphp/pest-dev-tools": "^4.0.0" + "pestphp/pest-dev-tools": "^5.0.0" }, "type": "library", "autoload": { @@ -14389,7 +14420,7 @@ "unit" ], "support": { - "source": "https://github.com/pestphp/pest-plugin-faker/tree/v4.0.0" + "source": "https://github.com/pestphp/pest-plugin-faker/tree/v5.0.0" }, "funding": [ { @@ -14405,31 +14436,35 @@ "type": "patreon" } ], - "time": "2025-08-20T10:22:28+00:00" + "time": "2026-07-21T07:48:56+00:00", + "published-time": "2026-07-28T14:33:57+00:00" }, { "name": "pestphp/pest-plugin-laravel", - "version": "v4.1.0", + "version": "v5.0.1", "source": { "type": "git", "url": "https://github.com/pestphp/pest-plugin-laravel.git", - "reference": "3057a36669ff11416cc0dc2b521b3aec58c488d0" + "reference": "d1564646e3198f1b607e64a36501d6edff7d104e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pestphp/pest-plugin-laravel/zipball/3057a36669ff11416cc0dc2b521b3aec58c488d0", - "reference": "3057a36669ff11416cc0dc2b521b3aec58c488d0", + "url": "https://api.github.com/repos/pestphp/pest-plugin-laravel/zipball/d1564646e3198f1b607e64a36501d6edff7d104e", + "reference": "d1564646e3198f1b607e64a36501d6edff7d104e", "shasum": "" }, "require": { - "laravel/framework": "^11.45.2|^12.52.0|^13.0", - "pestphp/pest": "^4.4.1", - "php": "^8.3.0" + "laravel/framework": "^13.23.0", + "pestphp/pest": "^5.0.1", + "php": "^8.4" + }, + "conflict": { + "pestphp/pest": "<5.0.0" }, "require-dev": { - "laravel/dusk": "^8.3.6", - "orchestra/testbench": "^9.13.0|^10.9.0|^11.0", - "pestphp/pest-dev-tools": "^4.1.0" + "laravel/dusk": "^8.6.0", + "orchestra/testbench": "^11.1", + "pestphp/pest-dev-tools": "^5.0.0" }, "type": "library", "extra": { @@ -14467,7 +14502,7 @@ "unit" ], "support": { - "source": "https://github.com/pestphp/pest-plugin-laravel/tree/v4.1.0" + "source": "https://github.com/pestphp/pest-plugin-laravel/tree/v5.0.1" }, "funding": [ { @@ -14479,32 +14514,37 @@ "type": "github" } ], - "time": "2026-02-21T00:29:45+00:00" + "time": "2026-07-29T18:19:36+00:00", + "published-time": "2026-07-29T18:21:59+00:00" }, { "name": "pestphp/pest-plugin-mutate", - "version": "v4.0.1", + "version": "v5.0.2", "source": { "type": "git", "url": "https://github.com/pestphp/pest-plugin-mutate.git", - "reference": "d9b32b60b2385e1688a68cc227594738ec26d96c" + "reference": "d0c87110416b699413cc073b8dcc92e440d81931" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pestphp/pest-plugin-mutate/zipball/d9b32b60b2385e1688a68cc227594738ec26d96c", - "reference": "d9b32b60b2385e1688a68cc227594738ec26d96c", + "url": "https://api.github.com/repos/pestphp/pest-plugin-mutate/zipball/d0c87110416b699413cc073b8dcc92e440d81931", + "reference": "d0c87110416b699413cc073b8dcc92e440d81931", "shasum": "" }, "require": { - "nikic/php-parser": "^5.6.1", - "pestphp/pest-plugin": "^4.0.0", - "php": "^8.3", + "nikic/php-parser": "^5.8.0", + "pestphp/pest-plugin": "^5.0.0", + "php": "^8.4", + "phpunit/php-code-coverage": "^14.3.0", "psr/simple-cache": "^3.0.0" }, + "conflict": { + "pestphp/pest": "<5.0.0" + }, "require-dev": { - "pestphp/pest": "^4.0.0", - "pestphp/pest-dev-tools": "^4.0.0", - "pestphp/pest-plugin-type-coverage": "^4.0.0" + "pestphp/pest": "^5.0.4", + "pestphp/pest-dev-tools": "^5.0.0", + "pestphp/pest-plugin-type-coverage": "^5.0.2" }, "type": "library", "autoload": { @@ -14539,7 +14579,7 @@ "unit" ], "support": { - "source": "https://github.com/pestphp/pest-plugin-mutate/tree/v4.0.1" + "source": "https://github.com/pestphp/pest-plugin-mutate/tree/v5.0.2" }, "funding": [ { @@ -14555,30 +14595,127 @@ "type": "github" } ], - "time": "2025-08-21T20:19:25+00:00" + "time": "2026-08-10T11:01:27+00:00", + "published-time": "2026-08-10T11:01:53+00:00" }, { - "name": "pestphp/pest-plugin-profanity", - "version": "v4.2.1", + "name": "pestphp/pest-plugin-phpstan", + "version": "v5.3.1", "source": { "type": "git", - "url": "https://github.com/pestphp/pest-plugin-profanity.git", - "reference": "343cfa6f3564b7e35df0ebb77b7fa97039f72b27" + "url": "https://github.com/pestphp/pest-plugin-phpstan.git", + "reference": "a56d8e58dc8892ff89e15c4bca38e74f9f97ff99" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pestphp/pest-plugin-profanity/zipball/343cfa6f3564b7e35df0ebb77b7fa97039f72b27", - "reference": "343cfa6f3564b7e35df0ebb77b7fa97039f72b27", + "url": "https://api.github.com/repos/pestphp/pest-plugin-phpstan/zipball/a56d8e58dc8892ff89e15c4bca38e74f9f97ff99", + "reference": "a56d8e58dc8892ff89e15c4bca38e74f9f97ff99", "shasum": "" }, "require": { - "pestphp/pest-plugin": "^4.0.0", - "php": "^8.3" + "pestphp/pest": "^5.0.0", + "php": "^8.4", + "phpstan/phpstan": "^2.2.5" + }, + "conflict": { + "pestphp/pest": "<5.0.0" }, "require-dev": { - "faissaloux/pest-plugin-inside": "^1.9", - "pestphp/pest": "^4.0.0", - "pestphp/pest-dev-tools": "^4.0.0" + "laravel/pao": "^1.1.2", + "laravel/pint": "^1.29.3", + "pestphp/pest-plugin-rector": "^5.0", + "phpstan/extension-installer": "^1.4.3", + "phpstan/phpstan-strict-rules": "^2.0.12", + "rector/rector": "^2.5.7" + }, + "type": "phpstan-extension", + "extra": { + "phpstan": { + "includes": [ + "extension.neon" + ] + } + }, + "autoload": { + "psr-4": { + "Pest\\PHPStan\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Punyapal Shah", + "email": "mrpunyapal@gmail.com" + }, + { + "name": "Nuno Maduro", + "email": "enunomaduro@gmail.com" + } + ], + "description": "PHPStan plugin for Pest", + "keywords": [ + "PHPStan", + "framework", + "pest", + "php", + "plugin", + "test", + "testing", + "unit" + ], + "support": { + "source": "https://github.com/pestphp/pest-plugin-phpstan/tree/v5.3.1" + }, + "funding": [ + { + "url": "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=66BYDWAT92N6L", + "type": "custom" + }, + { + "url": "https://github.com/mrpunyapal", + "type": "github" + }, + { + "url": "https://github.com/nunomaduro", + "type": "github" + }, + { + "url": "https://www.patreon.com/nunomaduro", + "type": "patreon" + } + ], + "time": "2026-11-02T07:22:57+00:00", + "published-time": "2026-11-02T07:24:28+00:00" + }, + { + "name": "pestphp/pest-plugin-profanity", + "version": "v5.0.1", + "source": { + "type": "git", + "url": "https://github.com/pestphp/pest-plugin-profanity.git", + "reference": "2b5fc73ce561b835ba5bf9596c97a84333af2eb8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/pestphp/pest-plugin-profanity/zipball/2b5fc73ce561b835ba5bf9596c97a84333af2eb8", + "reference": "2b5fc73ce561b835ba5bf9596c97a84333af2eb8", + "shasum": "" + }, + "require": { + "pestphp/pest-plugin": "^5.0.0", + "php": "^8.4" + }, + "conflict": { + "pestphp/pest": "<5.0.0", + "phpunit/phpunit": "<13.4.1" + }, + "require-dev": { + "faissaloux/pest-plugin-inside": "^1.11", + "pestphp/pest": "^5.0.0", + "pestphp/pest-dev-tools": "^5.0.0" }, "type": "library", "extra": { @@ -14609,34 +14746,40 @@ "unit" ], "support": { - "source": "https://github.com/pestphp/pest-plugin-profanity/tree/v4.2.1" + "source": "https://github.com/pestphp/pest-plugin-profanity/tree/v5.0.1" }, - "time": "2025-12-08T00:13:17+00:00" + "time": "2026-10-07T19:41:52+00:00", + "published-time": "2026-10-07T19:42:16+00:00" }, { "name": "pestphp/pest-plugin-type-coverage", - "version": "v4.0.4", + "version": "v5.1.0", "source": { "type": "git", "url": "https://github.com/pestphp/pest-plugin-type-coverage.git", - "reference": "f485d40ec4e2081f9d3456c00f2c008f145d7896" + "reference": "3951c85494cede417987c6418005b96e68e30e5b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pestphp/pest-plugin-type-coverage/zipball/f485d40ec4e2081f9d3456c00f2c008f145d7896", - "reference": "f485d40ec4e2081f9d3456c00f2c008f145d7896", + "url": "https://api.github.com/repos/pestphp/pest-plugin-type-coverage/zipball/3951c85494cede417987c6418005b96e68e30e5b", + "reference": "3951c85494cede417987c6418005b96e68e30e5b", "shasum": "" }, "require": { - "nunomaduro/pokio": "^1.0.0", - "pestphp/pest-plugin": "^4.0.0", - "php": "^8.3", - "phpstan/phpstan": "^1.12.24|^2.1.46", - "tomasvotruba/type-coverage": "^1.0.0|^2.1.0" + "nunomaduro/pokio": "^1.0.1", + "pestphp/pest-plugin": "^5.0.0", + "php": "^8.4", + "phpstan/phpstan": "^2.3.4", + "tomasvotruba/type-coverage": "^2.5.1" + }, + "conflict": { + "pestphp/pest": "<5.0.0", + "phpstan/phpstan": "<2.2.7", + "phpunit/phpunit": "<13.4.1" }, "require-dev": { - "pestphp/pest": "^4.4.5", - "pestphp/pest-dev-tools": "^4.1.0" + "pestphp/pest": "^5.3.4", + "pestphp/pest-dev-tools": "^5.0.0" }, "type": "library", "extra": { @@ -14668,7 +14811,7 @@ "unit" ], "support": { - "source": "https://github.com/pestphp/pest-plugin-type-coverage/tree/v4.0.4" + "source": "https://github.com/pestphp/pest-plugin-type-coverage/tree/v5.1.0" }, "funding": [ { @@ -14680,7 +14823,8 @@ "type": "github" } ], - "time": "2026-04-06T14:00:30+00:00" + "time": "2026-10-30T09:08:01+00:00", + "published-time": "2026-10-30T09:08:27+00:00" }, { "name": "phar-io/manifest", @@ -14747,7 +14891,8 @@ "type": "github" } ], - "time": "2024-03-03T12:33:53+00:00" + "time": "2024-03-03T12:33:53+00:00", + "published-time": "2024-03-03T12:39:44+00:00" }, { "name": "phar-io/version", @@ -14798,7 +14943,8 @@ "issues": "https://github.com/phar-io/version/issues", "source": "https://github.com/phar-io/version/tree/3.2.1" }, - "time": "2022-02-21T01:04:05+00:00" + "time": "2022-02-21T01:04:05+00:00", + "published-time": "2022-02-21T01:04:30+00:00" }, { "name": "php-parallel-lint/php-parallel-lint", @@ -14917,7 +15063,8 @@ "issues": "https://github.com/phpDocumentor/ReflectionCommon/issues", "source": "https://github.com/phpDocumentor/ReflectionCommon/tree/2.2.1" }, - "time": "2025-11-10T21:21:55+00:00" + "time": "2025-11-10T21:21:55+00:00", + "published-time": "2026-09-27T10:14:49+00:00" }, { "name": "phpdocumentor/reflection-docblock", @@ -14982,7 +15129,8 @@ "issues": "https://github.com/phpDocumentor/ReflectionDocBlock/issues", "source": "https://github.com/phpDocumentor/ReflectionDocBlock/tree/6.0.3" }, - "time": "2026-03-18T20:49:53+00:00" + "time": "2026-03-18T20:49:53+00:00", + "published-time": "2026-03-18T20:51:16+00:00" }, { "name": "phpdocumentor/type-resolver", @@ -15040,7 +15188,8 @@ "issues": "https://github.com/phpDocumentor/TypeResolver/issues", "source": "https://github.com/phpDocumentor/TypeResolver/tree/2.1.0" }, - "time": "2026-09-27T19:32:54+00:00" + "time": "2026-09-27T19:32:54+00:00", + "published-time": "2026-09-28T18:39:55+00:00" }, { "name": "phpstan/phpdoc-parser", @@ -15087,15 +15236,16 @@ "issues": "https://github.com/phpstan/phpdoc-parser/issues", "source": "https://github.com/phpstan/phpdoc-parser/tree/2.4.1" }, - "time": "2026-10-30T19:36:28+00:00" + "time": "2026-10-30T19:36:28+00:00", + "published-time": "2026-10-30T19:37:11+00:00" }, { "name": "phpstan/phpstan", - "version": "2.3.5", + "version": "2.3.6", "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/645a1bd6bead15fc1b8474137467961d0fa30a79", - "reference": "645a1bd6bead15fc1b8474137467961d0fa30a79", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/00cedebb76cc82c1592414fa4f616cefdccda16f", + "reference": "00cedebb76cc82c1592414fa4f616cefdccda16f", "shasum": "" }, "require": { @@ -15151,7 +15301,8 @@ "type": "github" } ], - "time": "2026-11-03T12:14:22+00:00" + "time": "2026-11-15T19:58:26+00:00", + "published-time": "2026-11-15T19:58:39+00:00" }, { "name": "phpstan/phpstan-mockery", @@ -15204,34 +15355,87 @@ "published-time": "2024-11-11T07:42:39+00:00" }, { - "name": "phpunit/php-code-coverage", - "version": "12.5.8", + "name": "phpstan/phpstan-webmozart-assert", + "version": "2.0.0", "source": { "type": "git", - "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "7440368d94738d54f2c1de24dbd3871793bbb0dd" + "url": "https://github.com/phpstan/phpstan-webmozart-assert.git", + "reference": "0c641817d2a8f05c7157f92d91986e74d3c8ab0c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/7440368d94738d54f2c1de24dbd3871793bbb0dd", - "reference": "7440368d94738d54f2c1de24dbd3871793bbb0dd", + "url": "https://api.github.com/repos/phpstan/phpstan-webmozart-assert/zipball/0c641817d2a8f05c7157f92d91986e74d3c8ab0c", + "reference": "0c641817d2a8f05c7157f92d91986e74d3c8ab0c", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0", + "phpstan/phpstan": "^2.0" + }, + "require-dev": { + "nikic/php-parser": "^5.1", + "php-parallel-lint/php-parallel-lint": "^1.2", + "phpstan/phpstan-deprecation-rules": "^2.0", + "phpstan/phpstan-phpunit": "^2.0", + "phpstan/phpstan-strict-rules": "^2.0", + "phpunit/phpunit": "^9.6", + "webmozart/assert": "^1.11.0" + }, + "type": "phpstan-extension", + "extra": { + "phpstan": { + "includes": [ + "extension.neon" + ] + } + }, + "autoload": { + "psr-4": { + "PHPStan\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan webmozart/assert extension", + "support": { + "issues": "https://github.com/phpstan/phpstan-webmozart-assert/issues", + "source": "https://github.com/phpstan/phpstan-webmozart-assert/tree/2.0.0" + }, + "time": "2024-10-14T03:45:26+00:00", + "published-time": "2024-11-11T07:42:24+00:00" + }, + { + "name": "phpunit/php-code-coverage", + "version": "14.5.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-code-coverage.git", + "reference": "2f122b9b48af71ad9b4448368febc26af86534c9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/2f122b9b48af71ad9b4448368febc26af86534c9", + "reference": "2f122b9b48af71ad9b4448368febc26af86534c9", "shasum": "" }, "require": { "ext-dom": "*", "ext-libxml": "*", + "ext-mbstring": "*", "ext-xmlwriter": "*", "nikic/php-parser": "^5.9.0", - "php": ">=8.3", - "phpunit/php-text-template": "^5.0.1", - "sebastian/complexity": "^5.0", - "sebastian/environment": "^8.1.2", - "sebastian/lines-of-code": "^4.0.1", - "sebastian/version": "^6.0", - "theseer/tokenizer": "^2.0.1" + "php": ">=8.4", + "phpunit/php-text-template": "^6.0.1", + "sebastian/complexity": "^6.0", + "sebastian/environment": "^9.3.3", + "sebastian/git-state": "^1.1.0", + "sebastian/lines-of-code": "^5.0.2", + "sebastian/version": "^7.0.1" }, "require-dev": { - "phpunit/phpunit": "^12.5.37" + "phpunit/phpunit": "^13.4.6" }, "suggest": { "ext-pcov": "PHP extension that provides line coverage", @@ -15240,7 +15444,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "12.5.x-dev" + "dev-main": "14.5.x-dev" } }, "autoload": { @@ -15269,7 +15473,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", "security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy", - "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/12.5.8" + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/14.5.2" }, "funding": [ { @@ -15289,32 +15493,33 @@ "type": "tidelift" } ], - "time": "2026-10-03T14:03:50+00:00" + "time": "2026-11-09T05:24:08+00:00", + "published-time": "2026-11-09T05:25:09+00:00" }, { "name": "phpunit/php-file-iterator", - "version": "6.0.2", + "version": "7.0.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-file-iterator.git", - "reference": "a248d1640ab059b075f53a2ef0f9856e864e06b5" + "reference": "9bb4e6c58b62c1e043be995c66abec7c97307aae" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/a248d1640ab059b075f53a2ef0f9856e864e06b5", - "reference": "a248d1640ab059b075f53a2ef0f9856e864e06b5", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/9bb4e6c58b62c1e043be995c66abec7c97307aae", + "reference": "9bb4e6c58b62c1e043be995c66abec7c97307aae", "shasum": "" }, "require": { - "php": ">=8.3" + "php": ">=8.4" }, "require-dev": { - "phpunit/phpunit": "^12.5.33" + "phpunit/phpunit": "^13.3.1" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "6.0-dev" + "dev-main": "7.0-dev" } }, "autoload": { @@ -15342,7 +15547,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/php-file-iterator/issues", "security": "https://github.com/sebastianbergmann/php-file-iterator/security/policy", - "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/6.0.2" + "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/7.0.2" }, "funding": [ { @@ -15362,28 +15567,29 @@ "type": "tidelift" } ], - "time": "2026-08-25T14:40:53+00:00" + "time": "2026-08-25T14:47:43+00:00", + "published-time": "2026-08-25T14:48:49+00:00" }, { "name": "phpunit/php-invoker", - "version": "6.0.0", + "version": "7.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-invoker.git", - "reference": "12b54e689b07a25a9b41e57736dfab6ec9ae5406" + "reference": "42e5c5cae0c65df12d1b1a3ab52bf3f50f244d88" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-invoker/zipball/12b54e689b07a25a9b41e57736dfab6ec9ae5406", - "reference": "12b54e689b07a25a9b41e57736dfab6ec9ae5406", + "url": "https://api.github.com/repos/sebastianbergmann/php-invoker/zipball/42e5c5cae0c65df12d1b1a3ab52bf3f50f244d88", + "reference": "42e5c5cae0c65df12d1b1a3ab52bf3f50f244d88", "shasum": "" }, "require": { - "php": ">=8.3" + "php": ">=8.4" }, "require-dev": { "ext-pcntl": "*", - "phpunit/phpunit": "^12.0" + "phpunit/phpunit": "^13.0" }, "suggest": { "ext-pcntl": "*" @@ -15391,7 +15597,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "6.0-dev" + "dev-main": "7.0-dev" } }, "autoload": { @@ -15418,40 +15624,53 @@ "support": { "issues": "https://github.com/sebastianbergmann/php-invoker/issues", "security": "https://github.com/sebastianbergmann/php-invoker/security/policy", - "source": "https://github.com/sebastianbergmann/php-invoker/tree/6.0.0" + "source": "https://github.com/sebastianbergmann/php-invoker/tree/7.0.0" }, "funding": [ { "url": "https://github.com/sebastianbergmann", "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpunit/php-invoker", + "type": "tidelift" } ], - "time": "2025-02-07T04:58:58+00:00" + "time": "2026-02-06T04:34:47+00:00", + "published-time": "2026-02-06T04:35:29+00:00" }, { "name": "phpunit/php-text-template", - "version": "5.0.1", + "version": "6.0.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-text-template.git", - "reference": "babab73b7ef9fae406f2eb3ee11323a61caa63d5" + "reference": "97107691cb2b6c743b5e0c44be19e983cb337a02" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/babab73b7ef9fae406f2eb3ee11323a61caa63d5", - "reference": "babab73b7ef9fae406f2eb3ee11323a61caa63d5", + "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/97107691cb2b6c743b5e0c44be19e983cb337a02", + "reference": "97107691cb2b6c743b5e0c44be19e983cb337a02", "shasum": "" }, "require": { - "php": ">=8.3" + "php": ">=8.4" }, "require-dev": { - "phpunit/phpunit": "^12.5.37" + "phpunit/phpunit": "^13.3.6" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "5.0-dev" + "dev-main": "6.0-dev" } }, "autoload": { @@ -15478,7 +15697,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/php-text-template/issues", "security": "https://github.com/sebastianbergmann/php-text-template/security/policy", - "source": "https://github.com/sebastianbergmann/php-text-template/tree/5.0.1" + "source": "https://github.com/sebastianbergmann/php-text-template/tree/6.0.1" }, "funding": [ { @@ -15498,32 +15717,33 @@ "type": "tidelift" } ], - "time": "2026-10-03T04:51:29+00:00" + "time": "2026-10-03T04:54:24+00:00", + "published-time": "2026-10-03T04:54:39+00:00" }, { "name": "phpunit/php-timer", - "version": "8.0.0", + "version": "9.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-timer.git", - "reference": "f258ce36aa457f3aa3339f9ed4c81fc66dc8c2cc" + "reference": "a0e12065831f6ab0d83120dc61513eb8d9a966f6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/f258ce36aa457f3aa3339f9ed4c81fc66dc8c2cc", - "reference": "f258ce36aa457f3aa3339f9ed4c81fc66dc8c2cc", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/a0e12065831f6ab0d83120dc61513eb8d9a966f6", + "reference": "a0e12065831f6ab0d83120dc61513eb8d9a966f6", "shasum": "" }, "require": { - "php": ">=8.3" + "php": ">=8.4" }, "require-dev": { - "phpunit/phpunit": "^12.0" + "phpunit/phpunit": "^13.0" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "8.0-dev" + "dev-main": "9.0-dev" } }, "autoload": { @@ -15550,28 +15770,41 @@ "support": { "issues": "https://github.com/sebastianbergmann/php-timer/issues", "security": "https://github.com/sebastianbergmann/php-timer/security/policy", - "source": "https://github.com/sebastianbergmann/php-timer/tree/8.0.0" + "source": "https://github.com/sebastianbergmann/php-timer/tree/9.0.0" }, "funding": [ { "url": "https://github.com/sebastianbergmann", "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpunit/php-timer", + "type": "tidelift" } ], - "time": "2025-02-07T04:59:38+00:00" + "time": "2026-02-06T04:37:53+00:00", + "published-time": "2026-02-06T04:38:39+00:00" }, { "name": "phpunit/phpunit", - "version": "12.5.33", + "version": "13.4.7", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "b98e028a26c5c5ba7e4a54be96ccf35f2914d184" + "reference": "e6458d44279e3b4fc492d4c41fe8e677efed7a2c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/b98e028a26c5c5ba7e4a54be96ccf35f2914d184", - "reference": "b98e028a26c5c5ba7e4a54be96ccf35f2914d184", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/e6458d44279e3b4fc492d4c41fe8e677efed7a2c", + "reference": "e6458d44279e3b4fc492d4c41fe8e677efed7a2c", "shasum": "" }, "require": { @@ -15581,25 +15814,27 @@ "ext-libxml": "*", "ext-mbstring": "*", "ext-xmlwriter": "*", - "myclabs/deep-copy": "^1.13.4", + "myclabs/deep-copy": "^1.14.0", "phar-io/manifest": "^2.0.4", "phar-io/version": "^3.2.1", - "php": ">=8.3", - "phpunit/php-code-coverage": "^12.5.7", - "phpunit/php-file-iterator": "^6.0.1", - "phpunit/php-invoker": "^6.0.0", - "phpunit/php-text-template": "^5.0.0", - "phpunit/php-timer": "^8.0.0", - "sebastian/cli-parser": "^4.2.1", - "sebastian/comparator": "^7.1.8", - "sebastian/diff": "^7.0.0", - "sebastian/environment": "^8.1.2", - "sebastian/exporter": "^7.0.3", - "sebastian/global-state": "^8.0.3", - "sebastian/object-enumerator": "^7.0.0", - "sebastian/recursion-context": "^7.0.1", - "sebastian/type": "^6.0.4", - "sebastian/version": "^6.0.0", + "php": ">=8.4.1", + "phpunit/php-code-coverage": "^14.5.2", + "phpunit/php-file-iterator": "^7.0.2", + "phpunit/php-invoker": "^7.0.0", + "phpunit/php-text-template": "^6.0.1", + "phpunit/php-timer": "^9.0.0", + "sebastian/cli-parser": "^5.0.1", + "sebastian/comparator": "^8.4", + "sebastian/diff": "^9.0.1", + "sebastian/environment": "^9.3.3", + "sebastian/exporter": "^8.2.1", + "sebastian/file-filter": "^1.0", + "sebastian/git-state": "^1.1", + "sebastian/global-state": "^9.0.1", + "sebastian/object-enumerator": "^8.1.0", + "sebastian/recursion-context": "^8.0.1", + "sebastian/type": "^7.0.2", + "sebastian/version": "^7.1.0", "staabm/side-effects-detector": "^1.0.5" }, "bin": [ @@ -15608,7 +15843,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "12.5-dev" + "dev-main": "13.4-dev" } }, "autoload": { @@ -15640,7 +15875,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/12.5.33" + "source": "https://github.com/sebastianbergmann/phpunit/tree/13.4.7" }, "funding": [ { @@ -15648,7 +15883,8 @@ "type": "other" } ], - "time": "2026-07-28T13:58:09+00:00" + "time": "2026-11-13T11:10:10+00:00", + "published-time": "2026-11-13T11:11:23+00:00" }, { "name": "react/event-loop", @@ -15781,28 +16017,28 @@ }, { "name": "sebastian/cli-parser", - "version": "4.2.1", + "version": "5.0.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/cli-parser.git", - "reference": "7d05781b13f7dec9043a629a21d086ed74582a15" + "reference": "eeb759ad3146b7096fb59c3195d39e071cd409e3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/7d05781b13f7dec9043a629a21d086ed74582a15", - "reference": "7d05781b13f7dec9043a629a21d086ed74582a15", + "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/eeb759ad3146b7096fb59c3195d39e071cd409e3", + "reference": "eeb759ad3146b7096fb59c3195d39e071cd409e3", "shasum": "" }, "require": { - "php": ">=8.3" + "php": ">=8.4" }, "require-dev": { - "phpunit/phpunit": "^12.5.25" + "phpunit/phpunit": "^13.2.6" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "4.2-dev" + "dev-main": "5.0-dev" } }, "autoload": { @@ -15826,7 +16062,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/cli-parser/issues", "security": "https://github.com/sebastianbergmann/cli-parser/security/policy", - "source": "https://github.com/sebastianbergmann/cli-parser/tree/4.2.1" + "source": "https://github.com/sebastianbergmann/cli-parser/tree/5.0.1" }, "funding": [ { @@ -15846,31 +16082,32 @@ "type": "tidelift" } ], - "time": "2026-05-17T05:29:34+00:00" + "time": "2026-08-01T04:27:14+00:00", + "published-time": "2026-08-01T04:29:01+00:00" }, { "name": "sebastian/comparator", - "version": "7.1.8", + "version": "8.4.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/comparator.git", - "reference": "7c65c1e79836812819705b473a90c12399542485" + "reference": "3b070e608146cba00fd6fd1f0ffba89e5a8897fb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/7c65c1e79836812819705b473a90c12399542485", - "reference": "7c65c1e79836812819705b473a90c12399542485", + "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/3b070e608146cba00fd6fd1f0ffba89e5a8897fb", + "reference": "3b070e608146cba00fd6fd1f0ffba89e5a8897fb", "shasum": "" }, "require": { "ext-dom": "*", "ext-mbstring": "*", - "php": ">=8.3", - "sebastian/diff": "^7.0", - "sebastian/exporter": "^7.0.3" + "php": ">=8.4", + "sebastian/diff": "^9.0", + "sebastian/exporter": "^8.2" }, "require-dev": { - "phpunit/phpunit": "^12.5.25" + "phpunit/phpunit": "^13.3" }, "suggest": { "ext-bcmath": "For comparing BcMath\\Number objects" @@ -15878,7 +16115,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "7.1-dev" + "dev-main": "8.4-dev" } }, "autoload": { @@ -15918,7 +16155,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/comparator/issues", "security": "https://github.com/sebastianbergmann/comparator/security/policy", - "source": "https://github.com/sebastianbergmann/comparator/tree/7.1.8" + "source": "https://github.com/sebastianbergmann/comparator/tree/8.4.0" }, "funding": [ { @@ -15938,33 +16175,34 @@ "type": "tidelift" } ], - "time": "2026-05-21T04:45:25+00:00" + "time": "2026-08-07T07:23:13+00:00", + "published-time": "2026-08-07T07:23:29+00:00" }, { "name": "sebastian/complexity", - "version": "5.0.0", + "version": "6.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/complexity.git", - "reference": "bad4316aba5303d0221f43f8cee37eb58d384bbb" + "reference": "c5651c795c98093480df79350cb050813fc7a2f3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/bad4316aba5303d0221f43f8cee37eb58d384bbb", - "reference": "bad4316aba5303d0221f43f8cee37eb58d384bbb", + "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/c5651c795c98093480df79350cb050813fc7a2f3", + "reference": "c5651c795c98093480df79350cb050813fc7a2f3", "shasum": "" }, "require": { "nikic/php-parser": "^5.0", - "php": ">=8.3" + "php": ">=8.4" }, "require-dev": { - "phpunit/phpunit": "^12.0" + "phpunit/phpunit": "^13.0" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "5.0-dev" + "dev-main": "6.0-dev" } }, "autoload": { @@ -15988,41 +16226,54 @@ "support": { "issues": "https://github.com/sebastianbergmann/complexity/issues", "security": "https://github.com/sebastianbergmann/complexity/security/policy", - "source": "https://github.com/sebastianbergmann/complexity/tree/5.0.0" + "source": "https://github.com/sebastianbergmann/complexity/tree/6.0.0" }, "funding": [ { "url": "https://github.com/sebastianbergmann", "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/complexity", + "type": "tidelift" } ], - "time": "2025-02-07T04:55:25+00:00" + "time": "2026-02-06T04:41:32+00:00", + "published-time": "2026-02-06T04:41:49+00:00" }, { "name": "sebastian/diff", - "version": "7.0.1", + "version": "9.0.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/diff.git", - "reference": "cd4cabe39f8a4e8ee6818ba99f10a05561ea4ad6" + "reference": "a2df6626c1baf31d5a88674882a3072f151b5a26" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/cd4cabe39f8a4e8ee6818ba99f10a05561ea4ad6", - "reference": "cd4cabe39f8a4e8ee6818ba99f10a05561ea4ad6", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/a2df6626c1baf31d5a88674882a3072f151b5a26", + "reference": "a2df6626c1baf31d5a88674882a3072f151b5a26", "shasum": "" }, "require": { - "php": ">=8.3" + "php": ">=8.4" }, "require-dev": { - "phpunit/phpunit": "^12.5.33", + "phpunit/phpunit": "^13.3.1", "symfony/process": "^7.4.17" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "7.0-dev" + "dev-main": "9.0-dev" } }, "autoload": { @@ -16055,7 +16306,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/diff/issues", "security": "https://github.com/sebastianbergmann/diff/security/policy", - "source": "https://github.com/sebastianbergmann/diff/tree/7.0.1" + "source": "https://github.com/sebastianbergmann/diff/tree/9.0.1" }, "funding": [ { @@ -16075,27 +16326,28 @@ "type": "tidelift" } ], - "time": "2026-08-25T15:35:54+00:00" + "time": "2026-08-25T15:38:55+00:00", + "published-time": "2026-08-25T15:39:44+00:00" }, { "name": "sebastian/environment", - "version": "8.1.2", + "version": "9.3.3", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/environment.git", - "reference": "9d32c685773823b1983e256ae4ecd48a10d6e439" + "reference": "d4dd10267a11055066a2a78ae04583d8ddd4f595" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/9d32c685773823b1983e256ae4ecd48a10d6e439", - "reference": "9d32c685773823b1983e256ae4ecd48a10d6e439", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/d4dd10267a11055066a2a78ae04583d8ddd4f595", + "reference": "d4dd10267a11055066a2a78ae04583d8ddd4f595", "shasum": "" }, "require": { - "php": ">=8.3" + "php": ">=8.4" }, "require-dev": { - "phpunit/phpunit": "^12.5.26" + "phpunit/phpunit": "^13.3.6" }, "suggest": { "ext-posix": "*" @@ -16103,7 +16355,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "8.1-dev" + "dev-main": "9.3-dev" } }, "autoload": { @@ -16131,7 +16383,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/environment/issues", "security": "https://github.com/sebastianbergmann/environment/security/policy", - "source": "https://github.com/sebastianbergmann/environment/tree/8.1.2" + "source": "https://github.com/sebastianbergmann/environment/tree/9.3.3" }, "funding": [ { @@ -16151,34 +16403,35 @@ "type": "tidelift" } ], - "time": "2026-05-25T13:40:20+00:00" + "time": "2026-10-01T12:37:56+00:00", + "published-time": "2026-10-01T12:38:48+00:00" }, { "name": "sebastian/exporter", - "version": "7.0.3", + "version": "8.2.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/exporter.git", - "reference": "c5e21b5de653ce0a769fb36f5cdfcb5e7a32cf23" + "reference": "24a3b69bba4a12ab615fca9d34680c5598d9ab7a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/c5e21b5de653ce0a769fb36f5cdfcb5e7a32cf23", - "reference": "c5e21b5de653ce0a769fb36f5cdfcb5e7a32cf23", + "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/24a3b69bba4a12ab615fca9d34680c5598d9ab7a", + "reference": "24a3b69bba4a12ab615fca9d34680c5598d9ab7a", "shasum": "" }, "require": { "ext-mbstring": "*", - "php": ">=8.3", - "sebastian/recursion-context": "^7.0.1" + "php": ">=8.4", + "sebastian/recursion-context": "^8.0.1" }, "require-dev": { - "phpunit/phpunit": "^12.5.25" + "phpunit/phpunit": "^13.3" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "7.0-dev" + "dev-main": "8.2-dev" } }, "autoload": { @@ -16221,7 +16474,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/exporter/issues", "security": "https://github.com/sebastianbergmann/exporter/security/policy", - "source": "https://github.com/sebastianbergmann/exporter/tree/7.0.3" + "source": "https://github.com/sebastianbergmann/exporter/tree/8.2.1" }, "funding": [ { @@ -16241,35 +16494,176 @@ "type": "tidelift" } ], - "time": "2026-05-20T04:37:17+00:00" + "time": "2026-08-07T07:22:06+00:00", + "published-time": "2026-08-07T07:23:47+00:00" }, { - "name": "sebastian/global-state", - "version": "8.0.3", + "name": "sebastian/file-filter", + "version": "1.0.0", "source": { "type": "git", - "url": "https://github.com/sebastianbergmann/global-state.git", - "reference": "b164d3274d6537ab462591c5755f76a8f5b1aae9" + "url": "https://github.com/sebastianbergmann/file-filter.git", + "reference": "33a26f394330f6faa7684bb9cc73afb7727aae93" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/b164d3274d6537ab462591c5755f76a8f5b1aae9", - "reference": "b164d3274d6537ab462591c5755f76a8f5b1aae9", + "url": "https://api.github.com/repos/sebastianbergmann/file-filter/zipball/33a26f394330f6faa7684bb9cc73afb7727aae93", + "reference": "33a26f394330f6faa7684bb9cc73afb7727aae93", "shasum": "" }, "require": { - "php": ">=8.3", - "sebastian/object-reflector": "^5.0", - "sebastian/recursion-context": "^7.0.1" + "php": ">=8.4" }, "require-dev": { - "ext-dom": "*", - "phpunit/phpunit": "^12.5.28" + "phpunit/phpunit": "^13.0" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "8.0-dev" + "dev-main": "1.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for filtering files", + "homepage": "https://github.com/sebastianbergmann/file-filter", + "support": { + "issues": "https://github.com/sebastianbergmann/file-filter/issues", + "security": "https://github.com/sebastianbergmann/file-filter/security/policy", + "source": "https://github.com/sebastianbergmann/file-filter/tree/1.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/file-filter", + "type": "tidelift" + } + ], + "time": "2026-04-22T07:20:04+00:00", + "published-time": "2026-04-22T07:20:25+00:00" + }, + { + "name": "sebastian/git-state", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/git-state.git", + "reference": "31a565f463686f0eefa85f899549256bf5805985" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/git-state/zipball/31a565f463686f0eefa85f899549256bf5805985", + "reference": "31a565f463686f0eefa85f899549256bf5805985", + "shasum": "" + }, + "require": { + "php": ">=8.4" + }, + "require-dev": { + "phpunit/phpunit": "^13.4.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for describing the state of a Git checkout", + "homepage": "https://github.com/sebastianbergmann/git-state", + "support": { + "issues": "https://github.com/sebastianbergmann/git-state/issues", + "security": "https://github.com/sebastianbergmann/git-state/security/policy", + "source": "https://github.com/sebastianbergmann/git-state/tree/1.1.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/git-state", + "type": "tidelift" + } + ], + "time": "2026-10-21T05:59:52+00:00", + "published-time": "2026-10-21T06:01:28+00:00" + }, + { + "name": "sebastian/global-state", + "version": "9.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/global-state.git", + "reference": "ba68ba79da690cf7eddefd3ce5b78b20b9ba9945" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/ba68ba79da690cf7eddefd3ce5b78b20b9ba9945", + "reference": "ba68ba79da690cf7eddefd3ce5b78b20b9ba9945", + "shasum": "" + }, + "require": { + "php": ">=8.4", + "sebastian/object-reflector": "^6.0", + "sebastian/recursion-context": "^8.0" + }, + "require-dev": { + "ext-dom": "*", + "phpunit/phpunit": "^13.1.13" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "9.0-dev" } }, "autoload": { @@ -16295,7 +16689,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/global-state/issues", "security": "https://github.com/sebastianbergmann/global-state/security/policy", - "source": "https://github.com/sebastianbergmann/global-state/tree/8.0.3" + "source": "https://github.com/sebastianbergmann/global-state/tree/9.0.1" }, "funding": [ { @@ -16315,33 +16709,34 @@ "type": "tidelift" } ], - "time": "2026-06-01T15:10:33+00:00" + "time": "2026-06-01T15:11:33+00:00", + "published-time": "2026-06-01T15:20:45+00:00" }, { "name": "sebastian/lines-of-code", - "version": "4.0.1", + "version": "5.0.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/lines-of-code.git", - "reference": "d543b8ef219dcd8da262cbb958639a96bedba10e" + "reference": "d1b6f8fce682505dbd048977f1abedf1b8ad3ff8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/d543b8ef219dcd8da262cbb958639a96bedba10e", - "reference": "d543b8ef219dcd8da262cbb958639a96bedba10e", + "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/d1b6f8fce682505dbd048977f1abedf1b8ad3ff8", + "reference": "d1b6f8fce682505dbd048977f1abedf1b8ad3ff8", "shasum": "" }, "require": { - "nikic/php-parser": "^5.7.0", - "php": ">=8.3" + "nikic/php-parser": "^5.8.0", + "php": ">=8.4" }, "require-dev": { - "phpunit/phpunit": "^12.5.25" + "phpunit/phpunit": "^13.2.4" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "4.0-dev" + "dev-main": "5.0-dev" } }, "autoload": { @@ -16365,7 +16760,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/lines-of-code/issues", "security": "https://github.com/sebastianbergmann/lines-of-code/security/policy", - "source": "https://github.com/sebastianbergmann/lines-of-code/tree/4.0.1" + "source": "https://github.com/sebastianbergmann/lines-of-code/tree/5.0.2" }, "funding": [ { @@ -16385,34 +16780,34 @@ "type": "tidelift" } ], - "time": "2026-05-19T16:22:07+00:00" + "time": "2026-07-09T08:42:34+00:00", + "published-time": "2026-07-09T08:44:06+00:00" }, { "name": "sebastian/object-enumerator", - "version": "7.0.0", + "version": "8.1.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/object-enumerator.git", - "reference": "1effe8e9b8e068e9ae228e542d5d11b5d16db894" + "reference": "511064ecde82bd747e2ba2fab3dda8d977b59576" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/1effe8e9b8e068e9ae228e542d5d11b5d16db894", - "reference": "1effe8e9b8e068e9ae228e542d5d11b5d16db894", + "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/511064ecde82bd747e2ba2fab3dda8d977b59576", + "reference": "511064ecde82bd747e2ba2fab3dda8d977b59576", "shasum": "" }, "require": { - "php": ">=8.3", - "sebastian/object-reflector": "^5.0", - "sebastian/recursion-context": "^7.0" + "php": ">=8.4", + "sebastian/recursion-context": "^8.0.1" }, "require-dev": { - "phpunit/phpunit": "^12.0" + "phpunit/phpunit": "^13.3.0" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "7.0-dev" + "dev-main": "8.1-dev" } }, "autoload": { @@ -16435,40 +16830,53 @@ "support": { "issues": "https://github.com/sebastianbergmann/object-enumerator/issues", "security": "https://github.com/sebastianbergmann/object-enumerator/security/policy", - "source": "https://github.com/sebastianbergmann/object-enumerator/tree/7.0.0" + "source": "https://github.com/sebastianbergmann/object-enumerator/tree/8.1.0" }, "funding": [ { "url": "https://github.com/sebastianbergmann", "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/object-enumerator", + "type": "tidelift" } ], - "time": "2025-02-07T04:57:48+00:00" + "time": "2026-08-13T07:05:05+00:00", + "published-time": "2026-08-13T07:07:58+00:00" }, { "name": "sebastian/object-reflector", - "version": "5.0.0", + "version": "6.1.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/object-reflector.git", - "reference": "4bfa827c969c98be1e527abd576533293c634f6a" + "reference": "f71bbcdc4f95456b4622810bec64eb06372e25b2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/4bfa827c969c98be1e527abd576533293c634f6a", - "reference": "4bfa827c969c98be1e527abd576533293c634f6a", + "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/f71bbcdc4f95456b4622810bec64eb06372e25b2", + "reference": "f71bbcdc4f95456b4622810bec64eb06372e25b2", "shasum": "" }, "require": { - "php": ">=8.3" + "php": ">=8.4" }, "require-dev": { - "phpunit/phpunit": "^12.0" + "phpunit/phpunit": "^13.3.0" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "5.0-dev" + "dev-main": "6.0-dev" } }, "autoload": { @@ -16491,40 +16899,53 @@ "support": { "issues": "https://github.com/sebastianbergmann/object-reflector/issues", "security": "https://github.com/sebastianbergmann/object-reflector/security/policy", - "source": "https://github.com/sebastianbergmann/object-reflector/tree/5.0.0" + "source": "https://github.com/sebastianbergmann/object-reflector/tree/6.1.0" }, "funding": [ { "url": "https://github.com/sebastianbergmann", "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/object-reflector", + "type": "tidelift" } ], - "time": "2025-02-07T04:58:17+00:00" + "time": "2026-08-13T06:34:36+00:00", + "published-time": "2026-08-13T06:39:22+00:00" }, { "name": "sebastian/recursion-context", - "version": "7.0.1", + "version": "8.0.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/recursion-context.git", - "reference": "0b01998a7d5b1f122911a66bebcb8d46f0c82d8c" + "reference": "32dba72f2b4642d6a93db22d6c0a9280ff2e3ca0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/0b01998a7d5b1f122911a66bebcb8d46f0c82d8c", - "reference": "0b01998a7d5b1f122911a66bebcb8d46f0c82d8c", + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/32dba72f2b4642d6a93db22d6c0a9280ff2e3ca0", + "reference": "32dba72f2b4642d6a93db22d6c0a9280ff2e3ca0", "shasum": "" }, "require": { - "php": ">=8.3" + "php": ">=8.4" }, "require-dev": { - "phpunit/phpunit": "^12.0" + "phpunit/phpunit": "^13.2.6" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "7.0-dev" + "dev-main": "8.0-dev" } }, "autoload": { @@ -16555,7 +16976,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/recursion-context/issues", "security": "https://github.com/sebastianbergmann/recursion-context/security/policy", - "source": "https://github.com/sebastianbergmann/recursion-context/tree/7.0.1" + "source": "https://github.com/sebastianbergmann/recursion-context/tree/8.0.1" }, "funding": [ { @@ -16575,32 +16996,33 @@ "type": "tidelift" } ], - "time": "2025-08-13T04:44:59+00:00" + "time": "2026-08-03T05:58:12+00:00", + "published-time": "2026-08-03T05:59:59+00:00" }, { "name": "sebastian/type", - "version": "6.0.4", + "version": "7.0.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/type.git", - "reference": "82ff822c2edc46724be9f7411d3163021f602773" + "reference": "bd1df467864cb95140414059a535b2d906173fcf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/82ff822c2edc46724be9f7411d3163021f602773", - "reference": "82ff822c2edc46724be9f7411d3163021f602773", + "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/bd1df467864cb95140414059a535b2d906173fcf", + "reference": "bd1df467864cb95140414059a535b2d906173fcf", "shasum": "" }, "require": { - "php": ">=8.3" + "php": ">=8.4" }, "require-dev": { - "phpunit/phpunit": "^12.5.25" + "phpunit/phpunit": "^13.3.0" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "6.0-dev" + "dev-main": "7.0-dev" } }, "autoload": { @@ -16624,7 +17046,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/type/issues", "security": "https://github.com/sebastianbergmann/type/security/policy", - "source": "https://github.com/sebastianbergmann/type/tree/6.0.4" + "source": "https://github.com/sebastianbergmann/type/tree/7.0.2" }, "funding": [ { @@ -16644,29 +17066,30 @@ "type": "tidelift" } ], - "time": "2026-05-20T06:45:45+00:00" + "time": "2026-08-10T08:00:57+00:00", + "published-time": "2026-08-10T08:01:43+00:00" }, { "name": "sebastian/version", - "version": "6.0.2", + "version": "7.1.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/version.git", - "reference": "a8b6643a19ba6c8125a473623e45fb8cbb0e4159" + "reference": "08e41d0c7e146bfc8cef7e63989b1294453a6d6a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/a8b6643a19ba6c8125a473623e45fb8cbb0e4159", - "reference": "a8b6643a19ba6c8125a473623e45fb8cbb0e4159", + "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/08e41d0c7e146bfc8cef7e63989b1294453a6d6a", + "reference": "08e41d0c7e146bfc8cef7e63989b1294453a6d6a", "shasum": "" }, "require": { - "php": ">=8.3" + "php": ">=8.4" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "6.0-dev" + "dev-main": "7.1-dev" } }, "autoload": { @@ -16690,7 +17113,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/version/issues", "security": "https://github.com/sebastianbergmann/version/security/policy", - "source": "https://github.com/sebastianbergmann/version/tree/6.0.2" + "source": "https://github.com/sebastianbergmann/version/tree/7.1.0" }, "funding": [ { @@ -16710,7 +17133,8 @@ "type": "tidelift" } ], - "time": "2026-11-09T06:30:55+00:00" + "time": "2026-11-09T06:31:27+00:00", + "published-time": "2026-11-09T06:31:50+00:00" }, { "name": "slevomat/coding-standard", @@ -17296,7 +17720,8 @@ "type": "github" } ], - "time": "2024-10-20T05:08:20+00:00" + "time": "2024-10-20T05:08:20+00:00", + "published-time": "2024-10-20T05:09:39+00:00" }, { "name": "symplify/rule-doc-generator-contracts", @@ -17415,57 +17840,8 @@ "issues": "https://github.com/ta-tikoma/phpunit-architecture-test/issues", "source": "https://github.com/ta-tikoma/phpunit-architecture-test/tree/0.8.7" }, - "time": "2026-02-17T17:25:14+00:00" - }, - { - "name": "theseer/tokenizer", - "version": "2.0.1", - "source": { - "type": "git", - "url": "https://github.com/theseer/tokenizer.git", - "reference": "7989e43bf381af0eac72e4f0ca5bcbfa81658be4" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/theseer/tokenizer/zipball/7989e43bf381af0eac72e4f0ca5bcbfa81658be4", - "reference": "7989e43bf381af0eac72e4f0ca5bcbfa81658be4", - "shasum": "" - }, - "require": { - "ext-dom": "*", - "ext-tokenizer": "*", - "ext-xmlwriter": "*", - "php": "^8.1" - }, - "type": "library", - "autoload": { - "classmap": [ - "src/" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-3-Clause" - ], - "authors": [ - { - "name": "Arne Blankerts", - "email": "arne@blankerts.de", - "role": "Developer" - } - ], - "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", - "support": { - "issues": "https://github.com/theseer/tokenizer/issues", - "source": "https://github.com/theseer/tokenizer/tree/2.0.1" - }, - "funding": [ - { - "url": "https://github.com/theseer", - "type": "github" - } - ], - "time": "2025-12-08T11:19:18+00:00" + "time": "2026-02-17T17:25:14+00:00", + "published-time": "2026-02-17T17:26:32+00:00" }, { "name": "tomasvotruba/type-coverage", @@ -17536,7 +17912,8 @@ "type": "github" } ], - "time": "2026-10-09T19:09:05+00:00" + "time": "2026-10-09T19:09:05+00:00", + "published-time": "2026-10-09T19:09:39+00:00" } ], "aliases": [], diff --git a/domain/Models/ValueObjects/DiscountValue.php b/domain/Models/ValueObjects/DiscountValue.php index 55cf2a10..0168c76c 100644 --- a/domain/Models/ValueObjects/DiscountValue.php +++ b/domain/Models/ValueObjects/DiscountValue.php @@ -118,6 +118,6 @@ final readonly class DiscountValue $rate = $this->getPercentageRate(); - return $basePrice->multiply((string) $rate, Product::ROUNDING); + return $basePrice->multiply(number_format($rate, 2, '.', ''), Product::ROUNDING); } } diff --git a/phpstan.neon b/phpstan.neon index 4674f530..d8f5f013 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,8 +1,9 @@ includes: - vendor/larastan/larastan/extension.neon - vendor/nesbot/carbon/extension.neon - - vendor/pestphp/pest/phpstan-pest-extension.neon + - vendor/pestphp/pest-plugin-phpstan/extension.neon - vendor/phpstan/phpstan-mockery/extension.neon + - vendor/phpstan/phpstan-webmozart-assert/extension.neon parameters: paths: diff --git a/tests/Architecture/ApplicationTest.php b/tests/Architecture/ApplicationTest.php index f49cd65c..438de8fe 100644 --- a/tests/Architecture/ApplicationTest.php +++ b/tests/Architecture/ApplicationTest.php @@ -13,117 +13,114 @@ use App\Contracts\QueryInput; use Illuminate\Database\Eloquent\Model; use Symfony\Component\Finder\Finder; -describe('application coding rules', function (): void { - arch('No Domain Entities are used in Controllers') - ->expect('App\Http\Controllers') - ->not->toUse('Domain\Models\Entities'); +// Application coding rules +arch('No Domain Entities are used in Controllers') + ->expect('App\Http\Controllers') + ->not->toUse('Domain\Models\Entities'); - arch('No Domain Entities are used in Policies') - ->expect('App\Policies') - ->not->toUse('Domain\Models\Entities'); +arch('No Domain Entities are used in Policies') + ->expect('App\Policies') + ->not->toUse('Domain\Models\Entities'); - arch('App DTOs are final readonly classes') - ->expect('App\Dto') - ->classes() - ->toBeFinal() - ->toBeReadonly(); +arch('App DTOs are final readonly classes') + ->expect('App\Dto') + ->classes() + ->toBeFinal() + ->toBeReadonly(); - arch('App Actions implement App\Contracts\Action and Inputs implement ActionInput', function (): void { - $path = __DIR__ . '/../../app/Cqs/Actions'; - $files = (new Finder())->files()->in($path)->name('*.php'); +arch('App Actions implement App\Contracts\Action and Inputs implement ActionInput', function (): void { + $path = __DIR__ . '/../../app/Cqs/Actions'; + $files = (new Finder())->files()->in($path)->name('*.php'); - foreach ($files as $file) { - $subPath = $file->getRelativePathname(); - $className = 'App\\Cqs\\Actions\\' . str_replace(['/', '.php'], ['\\', ''], $subPath); + foreach ($files as $file) { + $subPath = $file->getRelativePathname(); + $className = 'App\\Cqs\\Actions\\' . str_replace(['/', '.php'], ['\\', ''], $subPath); - if (! class_exists($className) && ! interface_exists($className)) { - throw new \RuntimeException("Symbol {$className} does not exist."); - } - - $reflection = new \ReflectionClass($className); - - if (str_ends_with($className, 'Input')) { - expect($reflection->implementsInterface(ActionInput::class)) - ->toBeTrue("{$className} must implement App\Contracts\ActionInput"); - } elseif (str_ends_with($className, 'Output')) { - if ($reflection->isEnum()) { - expect($reflection->isEnum())->toBeTrue(); - } else { - expect($reflection->isFinal()) - ->toBeTrue("{$className} must be final"); - expect($reflection->isReadOnly()) - ->toBeTrue("{$className} must be readonly"); - } - } else { - expect($reflection->implementsInterface(Action::class)) - ->toBeTrue("{$className} must implement App\Contracts\Action"); - } + if (! class_exists($className) && ! interface_exists($className)) { + throw new \RuntimeException("Symbol {$className} does not exist."); } - }); - arch('App Queries implement App\Contracts\Query and Inputs implement QueryInput', function (): void { - $path = __DIR__ . '/../../app/Cqs/Queries'; - $files = (new Finder())->files()->in($path)->name('*.php'); + $reflection = new \ReflectionClass($className); - foreach ($files as $file) { - $subPath = $file->getRelativePathname(); - $className = 'App\\Cqs\\Queries\\' . str_replace(['/', '.php'], ['\\', ''], $subPath); - - if (! class_exists($className) && ! interface_exists($className)) { - throw new \RuntimeException("Symbol {$className} does not exist."); - } - - $reflection = new \ReflectionClass($className); - - if (str_ends_with($className, 'Input')) { - expect($reflection->implementsInterface(QueryInput::class)) - ->toBeTrue("{$className} must implement App\Contracts\QueryInput"); - } elseif (str_ends_with($className, 'Output')) { - expect($reflection->isFinal() && $reflection->isReadOnly()) - ->toBeTrue("{$className} must be final readonly"); - } else { - expect($reflection->implementsInterface(Query::class)) - ->toBeTrue("{$className} must implement App\Contracts\Query"); + if (str_ends_with($className, 'Input')) { + expect($reflection->implementsInterface(ActionInput::class)) + ->toBeTrue("{$className} must implement App\Contracts\ActionInput"); + } elseif (str_ends_with($className, 'Output')) { + if (! $reflection->isEnum()) { + expect($reflection->isFinal()) + ->toBeTrue("{$className} must be final"); + expect($reflection->isReadOnly()) + ->toBeTrue("{$className} must be readonly"); } + } else { + expect($reflection->implementsInterface(Action::class)) + ->toBeTrue("{$className} must implement App\Contracts\Action"); } - }); - - arch('Eloquent models use UtcDatetimeCast or CalendarDateCast instead of raw date or datetime casts', function (): void { - $forbiddenCasts = [ - 'date', - 'datetime', - 'immutable_date', - 'immutable_datetime', - 'custom_datetime', - 'immutable_custom_datetime', - 'timestamp', - ]; - $path = __DIR__ . '/../../app/Models'; - $files = (new Finder())->files()->in($path)->name('*.php'); - - foreach ($files as $file) { - $subPath = $file->getRelativePathname(); - $className = 'App\\Models\\' . str_replace(['/', '.php'], ['\\', ''], $subPath); - - if (! class_exists($className)) { - throw new \RuntimeException("Model class {$className} does not exist."); - } - - $reflection = new \ReflectionClass($className); - if ($reflection->isAbstract() || ! $reflection->isSubclassOf(Model::class)) { - continue; - } - - /** @var Model $instance */ - $instance = $reflection->newInstanceWithoutConstructor(); - foreach ($instance->getCasts() as $attribute => $cast) { - $baseCast = is_string($cast) ? explode(':', $cast, 2)[0] : ''; - expect(in_array($baseCast, $forbiddenCasts, true)) - ->toBeFalse( - "{$className}::casts()['{$attribute}'] must use " - . UtcDatetimeCast::class . ' or ' . CalendarDateCast::class . " instead of '{$cast}'." - ); - } - } - }); + } +}); + +arch('App Queries implement App\Contracts\Query and Inputs implement QueryInput', function (): void { + $path = __DIR__ . '/../../app/Cqs/Queries'; + $files = (new Finder())->files()->in($path)->name('*.php'); + + foreach ($files as $file) { + $subPath = $file->getRelativePathname(); + $className = 'App\\Cqs\\Queries\\' . str_replace(['/', '.php'], ['\\', ''], $subPath); + + if (! class_exists($className) && ! interface_exists($className)) { + throw new \RuntimeException("Symbol {$className} does not exist."); + } + + $reflection = new \ReflectionClass($className); + + if (str_ends_with($className, 'Input')) { + expect($reflection->implementsInterface(QueryInput::class)) + ->toBeTrue("{$className} must implement App\Contracts\QueryInput"); + } elseif (str_ends_with($className, 'Output')) { + expect($reflection->isFinal() && $reflection->isReadOnly()) + ->toBeTrue("{$className} must be final readonly"); + } else { + expect($reflection->implementsInterface(Query::class)) + ->toBeTrue("{$className} must implement App\Contracts\Query"); + } + } +}); + +arch('Eloquent models use UtcDatetimeCast or CalendarDateCast instead of raw date or datetime casts', function (): void { + $forbiddenCasts = [ + 'date', + 'datetime', + 'immutable_date', + 'immutable_datetime', + 'custom_datetime', + 'immutable_custom_datetime', + 'timestamp', + ]; + $path = __DIR__ . '/../../app/Models'; + $files = (new Finder())->files()->in($path)->name('*.php'); + + foreach ($files as $file) { + $subPath = $file->getRelativePathname(); + $className = 'App\\Models\\' . str_replace(['/', '.php'], ['\\', ''], $subPath); + + if (! class_exists($className)) { + throw new \RuntimeException("Model class {$className} does not exist."); + } + + $reflection = new \ReflectionClass($className); + if ($reflection->isAbstract() || ! $reflection->isSubclassOf(Model::class)) { + continue; + } + + /** @var Model $instance */ + $instance = $reflection->newInstanceWithoutConstructor(); + foreach ($instance->getCasts() as $attribute => $cast) { + $baseCast = is_string($cast) ? explode(':', $cast, 2)[0] : ''; + expect(in_array($baseCast, $forbiddenCasts, true)) + ->toBeFalse( + "{$className}::casts()['{$attribute}'] must use " + . UtcDatetimeCast::class . ' or ' . CalendarDateCast::class . " instead of '{$cast}'." + ); + } + } }); diff --git a/tests/Architecture/CodingStandardsTest.php b/tests/Architecture/CodingStandardsTest.php index 771a721e..be85ba3d 100644 --- a/tests/Architecture/CodingStandardsTest.php +++ b/tests/Architecture/CodingStandardsTest.php @@ -6,57 +6,56 @@ namespace Tests\Architecture; use Shared\Filesystem\TemporaryFileFactory; -describe('coding standards', function (): void { - arch()->preset()->php(); - arch()->preset()->security()->ignoring([ - TemporaryFileFactory::class, - ]); +// Coding standards +arch()->preset()->php(); +arch()->preset()->security()->ignoring([ + TemporaryFileFactory::class, +]); - arch('it has no shell execution functions are used') - ->expect(['exec', 'shell_exec', 'system', 'passthru', 'proc_open']) - ->not->toBeUsed(); +arch('it has no shell execution functions are used') + ->expect(['exec', 'shell_exec', 'system', 'passthru', 'proc_open']) + ->not->toBeUsed(); - arch('it has no eval usage') - ->expect(['eval']) - ->not->toBeUsed(); +arch('it has no eval usage') + ->expect(['eval']) + ->not->toBeUsed(); - arch('it has no dangerous file functions') - ->expect(['file_get_contents', 'file_put_contents', 'fopen']) - ->not->toBeUsed(); +arch('it has no dangerous file functions') + ->expect(['file_get_contents', 'file_put_contents', 'fopen']) + ->not->toBeUsed(); - arch('it has no globals are used') - ->expect(['$GLOBALS', 'global']) - ->not->toBeUsed(); +arch('it has no globals are used') + ->expect(['$GLOBALS', 'global']) + ->not->toBeUsed(); - arch('it has no singletons') - ->expect(['getInstance', 'instance']) - ->not->toBeUsed(); +arch('it has no singletons') + ->expect(['getInstance', 'instance']) + ->not->toBeUsed(); - arch('it has no insecure hashing') - ->expect(['md5', 'sha1']) - ->not->toBeUsed(); +arch('it has no insecure hashing') + ->expect(['md5', 'sha1']) + ->not->toBeUsed(); - arch('it has no sleep function are used') - ->expect(['sleep', 'usleep']) - ->not->toBeUsed(); +arch('it has no sleep function are used') + ->expect(['sleep', 'usleep']) + ->not->toBeUsed(); - arch('it has no debug globals are used') - ->expect(['var_dump', 'die', 'print_r']) - ->not->toBeUsed(); +arch('it has no debug globals are used') + ->expect(['var_dump', 'die', 'print_r']) + ->not->toBeUsed(); - arch('all app source files use strict types') - ->expect('App') - ->toUseStrictTypes(); +arch('all app source files use strict types') + ->expect('App') + ->toUseStrictTypes(); - arch('all domain source files use strict types') - ->expect('Domain') - ->toUseStrictTypes(); +arch('all domain source files use strict types') + ->expect('Domain') + ->toUseStrictTypes(); - arch('all shared source files use strict types') - ->expect('Shared') - ->toUseStrictTypes(); +arch('all shared source files use strict types') + ->expect('Shared') + ->toUseStrictTypes(); - arch('all infrastructure source files use strict types') - ->expect('Infrastructure') - ->toUseStrictTypes(); -}); +arch('all infrastructure source files use strict types') + ->expect('Infrastructure') + ->toUseStrictTypes(); diff --git a/tests/Architecture/DomainTest.php b/tests/Architecture/DomainTest.php index ae13b0ca..59765932 100644 --- a/tests/Architecture/DomainTest.php +++ b/tests/Architecture/DomainTest.php @@ -8,83 +8,82 @@ use Shared\DDD\Directory; use Shared\DDD\Entity; use Shared\DDD\Repository; -describe('domain coding rules', function (): void { - arch('Entities implements Entity') - ->expect("Domain\Models\Entities") - ->toImplement(Entity::class); +// Domain coding rules +arch('Entities implements Entity') + ->expect("Domain\Models\Entities") + ->toImplement(Entity::class); - arch('Entities are final') - ->expect("Domain\Models\Entities") - ->toBeFinal(); +arch('Entities are final') + ->expect("Domain\Models\Entities") + ->toBeFinal(); - arch('ValueObjects are immutable (disabled due to mock-final-classes conflict)') - ->expect("Domain\Models\ValueObjects") - ->toBeReadonly() - ->toBeFinal(); +arch('ValueObjects are immutable (disabled due to mock-final-classes conflict)') + ->expect("Domain\Models\ValueObjects") + ->toBeReadonly() + ->toBeFinal(); - arch('Ports contains only interfaces') - ->expect("Domain\Ports") - ->classes() - ->toBeInterface(); +arch('Ports contains only interfaces') + ->expect("Domain\Ports") + ->classes() + ->toBeInterface(); - arch('No App classes are used in Domain') - ->expect('Domain') - ->not->toUse('App'); +arch('No App classes are used in Domain') + ->expect('Domain') + ->not->toUse('App'); - arch('No Infrastructure classes are used in Domain') - ->expect('Domain') - ->not->toUse('Infrastructure'); +arch('No Infrastructure classes are used in Domain') + ->expect('Domain') + ->not->toUse('Infrastructure'); - arch('No Illuminate classes are used in Domain') - ->expect('Domain') - ->not->toUse('Illuminate'); +arch('No Illuminate classes are used in Domain') + ->expect('Domain') + ->not->toUse('Illuminate'); - arch('No Symfony components are used in Domain') - ->expect('Domain') - ->not->toUse('Symfony'); +arch('No Symfony components are used in Domain') + ->expect('Domain') + ->not->toUse('Symfony'); - // * Deny some Laravel Functions in Domain - arch('it has no laravel helper functions') - ->expect('Domain') - ->not->toUse([ - 'abort', - 'app', - 'auth', - 'asset', - 'back', - 'bcrypt', - 'broadcast', - 'cache', - 'config', - 'cookie', - 'csrf_token', - 'dd', - 'dump', - 'decrypt', - 'dispatch', - 'event', - 'factory', - 'logger', - 'redirect', - 'request', - 'response', - 'route', - 'session', - 'storage', - 'url', - 'throw_if', - 'throw_unless', - '__', - 'trans', - 'trans_choice', - 'view', - ]); +// * Deny some Laravel Functions in Domain +arch('it has no laravel helper functions') + ->expect('Domain') + ->not->toUse([ + 'abort', + 'app', + 'auth', + 'asset', + 'back', + 'bcrypt', + 'broadcast', + 'cache', + 'config', + 'cookie', + 'csrf_token', + 'dd', + 'dump', + 'decrypt', + 'dispatch', + 'event', + 'factory', + 'logger', + 'redirect', + 'request', + 'response', + 'route', + 'session', + 'storage', + 'url', + 'throw_if', + 'throw_unless', + '__', + 'trans', + 'trans_choice', + 'view', + ]); - arch('Port Repositories extend Shared\DDD\Repository') - ->expect("Domain\Ports\Repositories") - ->toExtend(Repository::class); +arch('Port Repositories extend Shared\DDD\Repository') + ->expect("Domain\Ports\Repositories") + ->toExtend(Repository::class); - arch('Port Directories extend Shared\DDD\Directory') - ->expect("Domain\Ports\Directories") - ->toExtend(Directory::class); -}); +arch('Port Directories extend Shared\DDD\Directory') + ->expect("Domain\Ports\Directories") + ->toExtend(Directory::class); diff --git a/tests/Architecture/InfraTest.php b/tests/Architecture/InfraTest.php index dd8b68c4..6d00a418 100644 --- a/tests/Architecture/InfraTest.php +++ b/tests/Architecture/InfraTest.php @@ -4,9 +4,8 @@ declare(strict_types=1); namespace Tests\Architecture; -describe('infra coding rules', function (): void { - arch('No App classes are used in Infra') - ->expect('Infrastructure') - ->not->toUse('App') - ->ignoring('App\Models'); -}); +// Infra coding rules +arch('No App classes are used in Infra') + ->expect('Infrastructure') + ->not->toUse('App') + ->ignoring('App\Models'); diff --git a/tests/Architecture/NamingConventionsTest.php b/tests/Architecture/NamingConventionsTest.php index 6ad0bd74..76923cad 100644 --- a/tests/Architecture/NamingConventionsTest.php +++ b/tests/Architecture/NamingConventionsTest.php @@ -9,125 +9,122 @@ use App\Services\ArcadiaEmployee; use App\Services\EmployeeUpsertServiceResult; use Symfony\Component\Finder\Finder; -describe('naming conventions in app', function (): void { - arch('casts have Cast suffix') - ->expect("App\Casts") - ->toHaveSuffix('Cast'); +// Naming conventions in app +arch('casts have Cast suffix') + ->expect("App\Casts") + ->toHaveSuffix('Cast'); - arch('adapters repositories have Repository suffix') - ->expect("Infrastructure\Adapters\Repositories") - ->toHaveSuffix('Repository'); +arch('adapters repositories have Repository suffix') + ->expect("Infrastructure\Adapters\Repositories") + ->toHaveSuffix('Repository'); - arch('dtos have Dto suffix') - ->expect("App\Dto") - ->toHaveSuffix('Dto'); +arch('dtos have Dto suffix') + ->expect("App\Dto") + ->toHaveSuffix('Dto'); - arch('exceptions have Exception suffix') - ->expect("App\Exceptions") - ->toHaveSuffix('Exception') - ->ignoring([ - GlobalHandler::class, - ]); - - arch('controllers have Controller suffix') - ->expect("App\Http\Controllers") - ->toHaveSuffix('Controller'); - - arch('requests have Request suffix') - ->expect("App\Http\Requests") - ->toHaveSuffix('Request'); - - arch('resources have Resource suffix') - ->expect("App\Http\Resources") - ->toHaveSuffix('Resource'); - - arch('policies have Policy suffix') - ->expect("App\Policies") - ->toHaveSuffix('Policy'); - - arch('providers have Provider suffix') - ->expect("App\Providers") - ->toHaveSuffix('Provider'); - - arch('services have Service suffix') - ->expect("App\Services") - ->toHaveSuffix('Service') - ->ignoring([ - ArcadiaEmployee::class, - EmployeeUpsertServiceResult::class, - ]); - - arch('queries have Query, QueryInput or QueryOutput suffix', function (): void { - $path = __DIR__ . '/../../app/Cqs/Queries'; - $files = (new Finder())->files()->in($path)->name('*.php'); - - foreach ($files as $file) { - $className = $file->getBasename('.php'); - expect( - str_ends_with($className, 'Query') - || str_ends_with($className, 'QueryInput') - || str_ends_with($className, 'QueryOutput') - )->toBeTrue("{$className} must have suffix Query, QueryInput or QueryOutput"); - } - }); -}); - -describe('naming conventions in domain', function (): void { - arch('exceptions have Exception suffix') - ->expect("Domain\Exceptions") - ->toHaveSuffix('Exception'); - - arch('policies have Policy suffix') - ->expect("Domain\Policies") - ->toHaveSuffix('Policy'); - - arch('port directories have Directory suffix') - ->expect("Domain\Ports\Directories") - ->toHaveSuffix('Directory'); - - arch('port repositories have Repository suffix') - ->expect("Domain\Ports\Repositories") - ->toHaveSuffix('Repository'); - - arch('domain services have Service suffix') - ->expect("Domain\Services") - ->toHaveSuffix('Service'); -}); - -describe('naming conventions in infrastructure', function (): void { - arch('adapters serializers have Serializer suffix') - ->expect("Infrastructure\Adapters\Serializers") - ->toHaveSuffix('Serializer'); - - arch('adapters implement an interface from their domain or shared ports', function ( - string $folder, - string $infraNs, - string $portNs - ): void { - $path = __DIR__ . '/../../infra/' . $folder; - $files = (new Finder())->files()->in($path)->name('*.php'); - - foreach ($files as $file) { - $className = $infraNs . '\\' . $file->getFilenameWithoutExtension(); - - if (! class_exists($className) && ! interface_exists($className)) { - throw new \RuntimeException("Symbol {$className} does not exist."); - } - - $interfaces = (new \ReflectionClass($className))->getInterfaceNames(); - $hasPort = ! empty(array_filter( - $interfaces, - fn ($interface) => str_starts_with($interface, $portNs) - )); - - expect($hasPort) - ->toBeTrue(message: "La classe {$className} n'implémente aucune interface de {$portNs}."); - } - })->with([ - 'Directories' => ['Adapters/Directories', 'Infrastructure\Adapters\Directories', 'Domain\Ports\Directories\\'], - 'Events' => ['Adapters/Events', 'Infrastructure\Adapters\Events', 'Shared\DDD\\'], - 'Locks' => ['Adapters/Locks', 'Infrastructure\Adapters\Locks', 'Shared\Concurrency\\'], - 'Repositories' => ['Adapters/Repositories', 'Infrastructure\Adapters\Repositories', 'Domain\Ports\Repositories\\'], - 'Services' => ['Adapters/Services', 'Infrastructure\Adapters\Services', 'Domain\Ports\Services\\'], +arch('app exceptions have Exception suffix') + ->expect("App\Exceptions") + ->toHaveSuffix('Exception') + ->ignoring([ + GlobalHandler::class, ]); + +arch('controllers have Controller suffix') + ->expect("App\Http\Controllers") + ->toHaveSuffix('Controller'); + +arch('requests have Request suffix') + ->expect("App\Http\Requests") + ->toHaveSuffix('Request'); + +arch('resources have Resource suffix') + ->expect("App\Http\Resources") + ->toHaveSuffix('Resource'); + +arch('app policies have Policy suffix') + ->expect("App\Policies") + ->toHaveSuffix('Policy'); + +arch('providers have Provider suffix') + ->expect("App\Providers") + ->toHaveSuffix('Provider'); + +arch('services have Service suffix') + ->expect("App\Services") + ->toHaveSuffix('Service') + ->ignoring([ + ArcadiaEmployee::class, + EmployeeUpsertServiceResult::class, + ]); + +arch('queries have Query, QueryInput or QueryOutput suffix', function (): void { + $path = __DIR__ . '/../../app/Cqs/Queries'; + $files = (new Finder())->files()->in($path)->name('*.php'); + + foreach ($files as $file) { + $className = $file->getBasename('.php'); + expect( + str_ends_with($className, 'Query') + || str_ends_with($className, 'QueryInput') + || str_ends_with($className, 'QueryOutput') + )->toBeTrue("{$className} must have suffix Query, QueryInput or QueryOutput"); + } }); + +// Naming conventions in domain +arch('domain exceptions have Exception suffix') + ->expect("Domain\Exceptions") + ->toHaveSuffix('Exception'); + +arch('domain policies have Policy suffix') + ->expect("Domain\Policies") + ->toHaveSuffix('Policy'); + +arch('port directories have Directory suffix') + ->expect("Domain\Ports\Directories") + ->toHaveSuffix('Directory'); + +arch('port repositories have Repository suffix') + ->expect("Domain\Ports\Repositories") + ->toHaveSuffix('Repository'); + +arch('domain services have Service suffix') + ->expect("Domain\Services") + ->toHaveSuffix('Service'); + +// Naming conventions in infrastructure +arch('adapters serializers have Serializer suffix') + ->expect("Infrastructure\Adapters\Serializers") + ->toHaveSuffix('Serializer'); + +arch('adapters implement an interface from their domain or shared ports', function ( + string $folder, + string $infraNs, + string $portNs +): void { + $path = __DIR__ . '/../../infra/' . $folder; + $files = (new Finder())->files()->in($path)->name('*.php'); + + foreach ($files as $file) { + $className = $infraNs . '\\' . $file->getFilenameWithoutExtension(); + + if (! class_exists($className) && ! interface_exists($className)) { + throw new \RuntimeException("Symbol {$className} does not exist."); + } + + $interfaces = (new \ReflectionClass($className))->getInterfaceNames(); + $hasPort = ! empty(array_filter( + $interfaces, + fn ($interface) => str_starts_with($interface, $portNs) + )); + + expect($hasPort) + ->toBeTrue(message: "La classe {$className} n'implémente aucune interface de {$portNs}."); + } +})->with([ + 'Directories' => ['Adapters/Directories', 'Infrastructure\Adapters\Directories', 'Domain\Ports\Directories\\'], + 'Events' => ['Adapters/Events', 'Infrastructure\Adapters\Events', 'Shared\DDD\\'], + 'Locks' => ['Adapters/Locks', 'Infrastructure\Adapters\Locks', 'Shared\Concurrency\\'], + 'Repositories' => ['Adapters/Repositories', 'Infrastructure\Adapters\Repositories', 'Domain\Ports\Repositories\\'], + 'Services' => ['Adapters/Services', 'Infrastructure\Adapters\Services', 'Domain\Ports\Services\\'], +]); From 8a6b1442e61eaedfb39ed29228f339b5fd9d27ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 15:01:17 +0100 Subject: [PATCH 135/183] test(tests): remove Reflection attribute/constructor hacks and pass-through InitializeOrderTunnel (lot 4A) --- .../Customers/RegisterCustomerTest.php | 63 ++++++++++++------- .../Actions/Orders/PlacePendingOrderTest.php | 48 ++++++++++++++ .../Orders/InitializeOrderTunnelTest.php | 38 ----------- .../Actions/Orders/PlacePendingOrderTest.php | 31 +-------- .../Models/ValueObjects/DiscountValueTest.php | 60 +----------------- 5 files changed, 95 insertions(+), 145 deletions(-) delete mode 100644 tests/Unit/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php index 4503a1de..4a133b7b 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php @@ -4,13 +4,8 @@ declare(strict_types=1); namespace Tests\Integration\WithApp\App\Cqs\Actions\Customers; -use App\Attributes\Locked; use App\Contracts\ActionInput; use App\Contracts\Executor; -use App\Contracts\HandlesFailure; -use App\Contracts\HandlesLockTimeout; -use App\Contracts\HandlesSuccess; -use App\Contracts\ProvidesLockKey; use App\Cqs\Actions\Customers\RegisterCustomer; use App\Cqs\Actions\Customers\RegisterCustomerInput; use App\Cqs\Actions\Customers\RegisterCustomerOutput; @@ -19,6 +14,7 @@ use App\Exceptions\Crm\CrmCustomerExistsException; use App\Exceptions\CrmServiceException; use App\Models\Customer; use App\Models\Employee; +use App\Services\ActionExecutorService; use App\Services\CrmService; use Domain\Enums\Country; use Domain\Models\ValueObjects\Code; @@ -35,8 +31,12 @@ use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Notification; use Illuminate\Validation\ValidationException; +use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Infrastructure\Adapters\Services\AppCustomerAuthService; +use Psr\Log\NullLogger; use Ramsey\Uuid\Uuid; +use Shared\Concurrency\Lock; +use Shared\Concurrency\LockTimeoutException; use Shared\ValueObjects\CrmHashcode; describe('RegisterCustomer action', function (): void { @@ -242,7 +242,7 @@ describe('RegisterCustomer action', function (): void { $result = $action($input); // THEN - expect($result)->toBeInstanceOf(RegisterCustomerOutput::class) + expect($result) ->and($result->status)->toBe(RegisterCustomerStatus::EMPLOYEE_INACTIVE) ->and($result->customer)->toBeNull() ->and(Customer::query()->count())->toBe(0); @@ -450,30 +450,49 @@ describe('RegisterCustomer action', function (): void { expect(fn () => $action($invalidInput))->toThrow(\InvalidArgumentException::class); }); - it('has Locked attribute with expected TTL and wait seconds and implements lock contracts', function (): void { + it('acquires matricule lock via ActionExecutorService and returns LOCK_TIMEOUT when lock fails', function (): void { // GIVEN - $crmService = \Mockery::mock(CrmService::class); - $authService = \Mockery::mock(AppCustomerAuthService::class); - $action = new RegisterCustomer( + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldNotReceive('persist'); + $authService = \Mockery::mock(AppCustomerAuthService::class); + $action = new RegisterCustomer( authService: $authService, crmService: $crmService, ); - $reflection = new \ReflectionClass(RegisterCustomer::class); - $attributes = $reflection->getAttributes(Locked::class); + $input = new RegisterCustomerInput( + matricule: new Matricule('1234567'), + code: new Code('ABCDEF'), + firstname: 'John', + lastname: 'Doe', + email: new Email('john.doe@example.com'), + password: 'secretPassword123!', + birthDate: new \DateTimeImmutable('1990-01-01'), + phone: null, + address: null, + postcode: '75001', + city: 'Paris', + ); + + /** @var Lock&\Mockery\MockInterface $lock */ + $lock = \Mockery::mock(Lock::class); + $lock->shouldReceive('synchronize') + ->once() + ->with('customer:register:employee:1234567', \Mockery::type(\Closure::class), 30, 10) + ->andThrow(new LockTimeoutException('Lock timed out')); + + $executor = new ActionExecutorService( + $lock, + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); // WHEN - $locked = ($attributes[0] ?? null)?->newInstance(); + $output = $executor->execute($action, $input); // THEN - expect($locked)->toBeInstanceOf(Locked::class) - ->and($locked->ttlSeconds)->toBe(30) - ->and($locked->waitSeconds)->toBe(10) - ->and($locked->key)->toBeNull() - ->and($action)->toBeInstanceOf(ProvidesLockKey::class) - ->and($action)->toBeInstanceOf(HandlesLockTimeout::class) - ->and($action)->toBeInstanceOf(HandlesSuccess::class) - ->and($action)->toBeInstanceOf(HandlesFailure::class); + expect($output) + ->and($output->status)->toBe(RegisterCustomerStatus::LOCK_TIMEOUT); }); it('builds lockKey from input matricule', function (): void { @@ -533,7 +552,7 @@ describe('RegisterCustomer action', function (): void { $result = $action->onLockTimeout($input); // THEN - expect($result)->toBeInstanceOf(RegisterCustomerOutput::class) + expect($result) ->and($result->status)->toBe(RegisterCustomerStatus::LOCK_TIMEOUT) ->and($result->customer)->toBeNull() ->and($result->errorMessage)->toBeNull(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php index e7e8af3e..8f208810 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -465,4 +465,52 @@ describe('Order placement two-step CQS actions', function (): void { ); expect($lockOut->status)->toBe(PlacePendingOrderStatus::LOCK_TIMEOUT); }); + + it('executes ExportOrderToRegate without opening a DB transaction and returns LOCK_TIMEOUT when lock fails', function (): void { + // GIVEN + $orderId = new OrderId(Uuid::uuid7()); + $input = new ExportOrderToRegateInput($orderId); + $levelBeforeExecute = DB::transactionLevel(); + $levelInsideAction = null; + + /** @var OrderTunnelService&\Mockery\MockInterface $tunnelService */ + $tunnelService = \Mockery::mock(OrderTunnelService::class); + $tunnelService->shouldReceive('exportOrderToRegate') + ->once() + ->with($orderId) + ->andReturnUsing(function () use (&$levelInsideAction): void { + $levelInsideAction = DB::transactionLevel(); + }); + + $memoryExecutor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN + $sentOutput = $memoryExecutor->execute(new ExportOrderToRegate($tunnelService), $input); + + // GIVEN (contended lock) + /** @var Lock&\Mockery\MockInterface $contendedLock */ + $contendedLock = \Mockery::mock(Lock::class); + $contendedLock->shouldReceive('synchronize') + ->once() + ->with("order:export:{$orderId->value}", \Mockery::type(\Closure::class), 30, 10) + ->andThrow(new LockTimeoutException('Lock timed out')); + + $contendedExecutor = new ActionExecutorService( + $contendedLock, + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN + $timeoutOutput = $contendedExecutor->execute(new ExportOrderToRegate($tunnelService), $input); + + // THEN + expect($sentOutput)->toBe(ExportOrderToRegateOutput::SENT) + ->and($levelInsideAction)->toBe($levelBeforeExecute) + ->and($timeoutOutput)->toBe(ExportOrderToRegateOutput::LOCK_TIMEOUT); + }); }); diff --git a/tests/Unit/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php b/tests/Unit/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php deleted file mode 100644 index ea02acaa..00000000 --- a/tests/Unit/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php +++ /dev/null @@ -1,38 +0,0 @@ -shouldReceive('initializeFromBasket') - ->once() - ->with($basket, $shopperId); - - $action = new InitializeOrderTunnel($orderTunnelService); - - // WHEN - $action($input); - - // THEN - expect(true)->toBeTrue(); - }); -}); diff --git a/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php index dae2a4d5..1492ff5c 100644 --- a/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php +++ b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -4,12 +4,8 @@ declare(strict_types=1); namespace Tests\Unit\App\Cqs\Actions\Orders; -use App\Attributes\Locked; -use App\Attributes\WithoutTransaction; use App\Contracts\HandlesFailure; -use App\Contracts\HandlesLockTimeout; use App\Contracts\HandlesSuccess; -use App\Contracts\ProvidesLockKey; use App\Cqs\Actions\Orders\CancelPendingOrder; use App\Cqs\Actions\Orders\CancelPendingOrderInput; use App\Cqs\Actions\Orders\CancelPendingOrderOutput; @@ -195,7 +191,7 @@ describe('PlacePendingOrder', function (): void { ->and($result->errorMessage)->toBe('The price of one or more products in your basket has changed.'); }); - it('has Locked attribute and lock key contracts', function (): void { + it('builds shopper lock key and returns LOCK_TIMEOUT output on lock timeout', function (): void { // GIVEN $shopperId = new ShopperId(Uuid::uuid7()); $input = new PlacePendingOrderInput(shopperId: $shopperId); @@ -204,40 +200,19 @@ describe('PlacePendingOrder', function (): void { /** @var \Mockery\MockInterface&BasketRepository $basketRepository */ $basketRepository = \Mockery::mock(BasketRepository::class); - $action = new PlacePendingOrder($orderTunnelService, $basketRepository); - $reflection = new \ReflectionClass(PlacePendingOrder::class); - $attributes = $reflection->getAttributes(Locked::class); - $locked = ($attributes[0] ?? null)?->newInstance(); + $action = new PlacePendingOrder($orderTunnelService, $basketRepository); // WHEN $key = $action->lockKey($input); $timeout = $action->onLockTimeout($input); // THEN - expect($locked)->toBeInstanceOf(Locked::class) - ->and($locked?->ttlSeconds)->toBe(30) - ->and($locked?->waitSeconds)->toBe(10) - ->and($action)->toBeInstanceOf(ProvidesLockKey::class) - ->and($action)->toBeInstanceOf(HandlesLockTimeout::class) - ->and($key)->toBe("order:finalize:shopper:{$shopperId->value}") + expect($key)->toBe("order:finalize:shopper:{$shopperId->value}") ->and($timeout->status)->toBe(PlacePendingOrderStatus::LOCK_TIMEOUT); }); }); describe('ExportOrderToRegate, ConfirmPlacedOrder and CancelPendingOrder', function (): void { - it('marks ExportOrderToRegate with WithoutTransaction and Locked attributes', function (): void { - // GIVEN - $reflection = new \ReflectionClass(ExportOrderToRegate::class); - - // WHEN - $withoutTx = $reflection->getAttributes(WithoutTransaction::class); - $locked = $reflection->getAttributes(Locked::class); - - // THEN - expect($withoutTx)->toHaveCount(1) - ->and($locked)->toHaveCount(1); - }); - it('exports order via OrderTunnelService and handles lock timeout', function (): void { // GIVEN $orderId = new OrderId(Uuid::uuid7()); diff --git a/tests/Unit/Domain/Models/ValueObjects/DiscountValueTest.php b/tests/Unit/Domain/Models/ValueObjects/DiscountValueTest.php index cae74ff3..04ffafa5 100644 --- a/tests/Unit/Domain/Models/ValueObjects/DiscountValueTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/DiscountValueTest.php @@ -4,15 +4,17 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\ValueObjects; -use Domain\Enums\DiscountType; use Domain\Models\ValueObjects\DiscountValue; use Money\Currency; use Money\Money; +use Webmozart\Assert\Assert; describe('DiscountValue', function () { function getDiscountMoney(int $amount, string $currency = 'EUR'): Money { + Assert::notEmpty($currency); + return new Money($amount, new Currency($currency)); } @@ -24,7 +26,6 @@ describe('DiscountValue', function () { $vo = DiscountValue::fromAmount($amount); // THEN - expect($vo)->toBeInstanceOf(DiscountValue::class); expect($vo->isPercentage())->toBeFalse(); }); @@ -36,7 +37,6 @@ describe('DiscountValue', function () { $vo = DiscountValue::fromPercentage($rate); // THEN - expect($vo)->toBeInstanceOf(DiscountValue::class); expect($vo->isPercentage())->toBeTrue(); }); @@ -174,57 +174,3 @@ describe('DiscountValue', function () { expect($action)->toThrow(\DomainException::class); }); }); - -describe('DiscountValue exceptions', function (): void { - it('throws when percentage is missing for percent type', function (): void { - // GIVEN - $reflection = new \ReflectionClass(DiscountValue::class); - $method = $reflection->getMethod('__construct'); - $vo = $reflection->newInstanceWithoutConstructor(); - // WHEN - $action = fn () => $method->invoke($vo, DiscountType::PERCENT, null, null); - // THEN - expect($action)->toThrow(\DomainException::class); - }); - - it('throws when amount is missing for amount type', function (): void { - // GIVEN - $reflection = new \ReflectionClass(DiscountValue::class); - $method = $reflection->getMethod('__construct'); - $vo = $reflection->newInstanceWithoutConstructor(); - // WHEN - $action = fn () => $method->invoke($vo, DiscountType::AMOUNT, null, null); - // THEN - expect($action)->toThrow(\DomainException::class); - }); - - it('throws unexpected value if percentage is null', function (): void { - // GIVEN - $reflection = new \ReflectionClass(DiscountValue::class); - $vo = $reflection->newInstanceWithoutConstructor(); - $prop = $reflection->getProperty('type'); - $prop->setValue($vo, DiscountType::PERCENT); - $prop2 = $reflection->getProperty('percentage'); - $prop2->setValue($vo, null); - - // WHEN - $action = fn () => $vo->getPercentage(); - // THEN - expect($action)->toThrow(\DomainException::class); - }); - - it('throws unexpected value if amount is null', function (): void { - // GIVEN - $reflection = new \ReflectionClass(DiscountValue::class); - $vo = $reflection->newInstanceWithoutConstructor(); - $prop = $reflection->getProperty('type'); - $prop->setValue($vo, DiscountType::AMOUNT); - $prop2 = $reflection->getProperty('amount'); - $prop2->setValue($vo, null); - - // WHEN - $action = fn () => $vo->getAmount(); - // THEN - expect($action)->toThrow(\DomainException::class); - }); -}); From 99a923a7df9c93d1991466fc8d930ad7132a9cd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 15:04:17 +0100 Subject: [PATCH 136/183] test(tests): replace internal Laravel Session/Mail/DB mocks with real stores and Mail::fake (lot 4B) --- .../App/Jobs/SendContactMailJobTest.php | 155 ++++++++-------- .../SessionBasketRepositoryTest.php | 132 +++++--------- .../SessionOrderBuilderManagerTest.php | 169 ++++++++++-------- .../App/Services/FlashMessageServiceTest.php | 66 +++---- .../LaravelTransactionManagerTest.php | 42 +++-- 5 files changed, 268 insertions(+), 296 deletions(-) diff --git a/tests/Feature/App/Jobs/SendContactMailJobTest.php b/tests/Feature/App/Jobs/SendContactMailJobTest.php index 3778f4b4..df7af92f 100644 --- a/tests/Feature/App/Jobs/SendContactMailJobTest.php +++ b/tests/Feature/App/Jobs/SendContactMailJobTest.php @@ -10,16 +10,20 @@ use App\Mail\SendContactMail; use Domain\Models\ValueObjects\AttachedFile; use Domain\Models\ValueObjects\ContactFormData; use Illuminate\Contracts\Mail\Mailer; -use Illuminate\Mail\Mailables\Address; -use Illuminate\Mail\PendingMail; +use Illuminate\Support\Facades\Mail; use Uwil\Storage\Contracts\StorageService; use Uwil\Storage\Lib\ValueObjects\DiskName; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; +use function Pest\Laravel\instance; + describe('SendContactMailJob', function (): void { it('sends SendContactMail and idempotently deletes attachment when it exists on s3-private', function (): void { - /** @var \Tests\TestCase $this */ // GIVEN + Mail::fake(); + /** @var Mailer $mailer */ + $mailer = Mail::getFacadeRoot(); + $data = new ContactFormData( lastName: 'Dupont', firstName: 'Jean', @@ -36,46 +40,38 @@ describe('SendContactMailJob', function (): void { $job = new SendContactMailJob($data, 'contact@example.com', 'Support'); $privateS3Disk = new PrivateS3Disk(); - $pendingMail = \Mockery::mock(PendingMail::class); - $pendingMail->shouldReceive('send') - ->once() - ->with(\Mockery::on(fn (mixed $mail): bool => $mail instanceof SendContactMail && $mail->data === $data)); - - $mailer = \Mockery::mock(Mailer::class); - $mailer->shouldReceive('to') - ->once() - ->with(\Mockery::on( - fn (mixed $address): bool => $address instanceof Address - && $address->address === 'contact@example.com' - && $address->name === 'Support' - )) - ->andReturn($pendingMail); - - $storageService = \Mockery::mock(StorageService::class); - $storageService->shouldReceive('fileExistsOnDisk') - ->once() - ->with( - \Mockery::on(fn (StorageFilePath $path): bool => $path->value === 'contact-attachments/piece.pdf'), - \Mockery::on(fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), - ) - ->andReturn(true); - $storageService->shouldReceive('removeFromDisk') - ->once() - ->with( - \Mockery::on(fn (StorageFilePath $path): bool => $path->value === 'contact-attachments/piece.pdf'), - \Mockery::on(fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), - ); + /** @var StorageService&\Mockery\MockInterface $storageService */ + $storageService = \Mockery::spy(StorageService::class); + $storageService->allows('fileExistsOnDisk')->andReturn(true); // WHEN $job->handle($mailer, $storageService, $privateS3Disk); // THEN - expect(true)->toBeTrue(); + Mail::assertSent( + SendContactMail::class, + static fn (SendContactMail $mail): bool => $mail->hasTo('contact@example.com') && $mail->data === $data, + ); + $storageService->shouldHaveReceived('fileExistsOnDisk') + ->once() + ->with( + \Mockery::on(static fn (StorageFilePath $path): bool => $path->value === 'contact-attachments/piece.pdf'), + \Mockery::on(static fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), + ); + $storageService->shouldHaveReceived('removeFromDisk') + ->once() + ->with( + \Mockery::on(static fn (StorageFilePath $path): bool => $path->value === 'contact-attachments/piece.pdf'), + \Mockery::on(static fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), + ); }); it('sends SendContactMail and does not call removeFromDisk when attachment does not exist', function (): void { - /** @var \Tests\TestCase $this */ // GIVEN + Mail::fake(); + /** @var Mailer $mailer */ + $mailer = Mail::getFacadeRoot(); + $data = new ContactFormData( lastName: 'Dupont', firstName: 'Jean', @@ -92,28 +88,28 @@ describe('SendContactMailJob', function (): void { $job = new SendContactMailJob($data, 'contact@example.com'); $privateS3Disk = new PrivateS3Disk(); - $pendingMail = \Mockery::mock(PendingMail::class); - $pendingMail->shouldReceive('send')->once(); - - $mailer = \Mockery::mock(Mailer::class); - $mailer->shouldReceive('to')->once()->andReturn($pendingMail); - - $storageService = \Mockery::mock(StorageService::class); - $storageService->shouldReceive('fileExistsOnDisk') - ->once() - ->andReturn(false); - $storageService->shouldNotReceive('removeFromDisk'); + /** @var StorageService&\Mockery\MockInterface $storageService */ + $storageService = \Mockery::spy(StorageService::class); + $storageService->allows('fileExistsOnDisk')->andReturn(false); // WHEN $job->handle($mailer, $storageService, $privateS3Disk); // THEN - expect(true)->toBeTrue(); + Mail::assertSent( + SendContactMail::class, + static fn (SendContactMail $mail): bool => $mail->hasTo('contact@example.com') && $mail->data === $data, + ); + $storageService->shouldHaveReceived('fileExistsOnDisk')->once(); + $storageService->shouldNotHaveReceived('removeFromDisk'); }); it('sends SendContactMail and skips storage checks when data has no attachment', function (): void { - /** @var \Tests\TestCase $this */ // GIVEN + Mail::fake(); + /** @var Mailer $mailer */ + $mailer = Mail::getFacadeRoot(); + $data = new ContactFormData( lastName: 'Dupont', firstName: 'Jean', @@ -125,25 +121,22 @@ describe('SendContactMailJob', function (): void { $job = new SendContactMailJob($data, 'contact@example.com'); $privateS3Disk = new PrivateS3Disk(); - $pendingMail = \Mockery::mock(PendingMail::class); - $pendingMail->shouldReceive('send')->once(); - - $mailer = \Mockery::mock(Mailer::class); - $mailer->shouldReceive('to')->once()->andReturn($pendingMail); - - $storageService = \Mockery::mock(StorageService::class); - $storageService->shouldNotReceive('fileExistsOnDisk'); - $storageService->shouldNotReceive('removeFromDisk'); + /** @var StorageService&\Mockery\MockInterface $storageService */ + $storageService = \Mockery::spy(StorageService::class); // WHEN $job->handle($mailer, $storageService, $privateS3Disk); // THEN - expect(true)->toBeTrue(); + Mail::assertSent( + SendContactMail::class, + static fn (SendContactMail $mail): bool => $mail->hasTo('contact@example.com') && $mail->data === $data, + ); + $storageService->shouldNotHaveReceived('fileExistsOnDisk'); + $storageService->shouldNotHaveReceived('removeFromDisk'); }); it('idempotently deletes attachment on failed() when it exists on s3-private', function (): void { - /** @var \Tests\TestCase $this */ // GIVEN $data = new ContactFormData( lastName: 'Dupont', @@ -160,31 +153,30 @@ describe('SendContactMailJob', function (): void { $job = new SendContactMailJob($data, 'contact@example.com'); - $this->mock(StorageService::class, function ($mock): void { - $mock->shouldReceive('fileExistsOnDisk') - ->once() - ->with( - \Mockery::on(fn (StorageFilePath $path): bool => $path->value === 'contact-attachments/failed.pdf'), - \Mockery::on(fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), - ) - ->andReturn(true); - $mock->shouldReceive('removeFromDisk') - ->once() - ->with( - \Mockery::on(fn (StorageFilePath $path): bool => $path->value === 'contact-attachments/failed.pdf'), - \Mockery::on(fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), - ); - }); + /** @var StorageService&\Mockery\MockInterface $storageService */ + $storageService = \Mockery::spy(StorageService::class); + $storageService->allows('fileExistsOnDisk')->andReturn(true); + instance(StorageService::class, $storageService); // WHEN $job->failed(new \RuntimeException('SMTP failure')); // THEN - expect(true)->toBeTrue(); + $storageService->shouldHaveReceived('fileExistsOnDisk') + ->once() + ->with( + \Mockery::on(static fn (StorageFilePath $path): bool => $path->value === 'contact-attachments/failed.pdf'), + \Mockery::on(static fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), + ); + $storageService->shouldHaveReceived('removeFromDisk') + ->once() + ->with( + \Mockery::on(static fn (StorageFilePath $path): bool => $path->value === 'contact-attachments/failed.pdf'), + \Mockery::on(static fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), + ); }); it('skips removeFromDisk on failed() when attachment does not exist on s3-private', function (): void { - /** @var \Tests\TestCase $this */ // GIVEN $data = new ContactFormData( lastName: 'Dupont', @@ -201,17 +193,16 @@ describe('SendContactMailJob', function (): void { $job = new SendContactMailJob($data, 'contact@example.com'); - $this->mock(StorageService::class, function ($mock): void { - $mock->shouldReceive('fileExistsOnDisk') - ->once() - ->andReturn(false); - $mock->shouldNotReceive('removeFromDisk'); - }); + /** @var StorageService&\Mockery\MockInterface $storageService */ + $storageService = \Mockery::spy(StorageService::class); + $storageService->allows('fileExistsOnDisk')->andReturn(false); + instance(StorageService::class, $storageService); // WHEN $job->failed(new \RuntimeException('SMTP failure')); // THEN - expect(true)->toBeTrue(); + $storageService->shouldHaveReceived('fileExistsOnDisk')->once(); + $storageService->shouldNotHaveReceived('removeFromDisk'); }); }); diff --git a/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php b/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php index 460679af..e01cb739 100644 --- a/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php +++ b/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php @@ -6,24 +6,20 @@ namespace Tests\Integration\Standalones\Infra\Adapters\Repositories; use Domain\Models\Entities\Basket; use Domain\Models\ValueObjects\Entities\BasketId; -use Illuminate\Contracts\Session\Session; +use Illuminate\Session\ArraySessionHandler; +use Illuminate\Session\Store; use Infrastructure\Adapters\Repositories\SessionBasketRepository; use Infrastructure\Adapters\Serializers\BasketSerializer; use Ramsey\Uuid\Uuid; covers(SessionBasketRepository::class); -describe('SessionBasketRepository', function () { - - it('returns null if session is empty', function () { +describe('SessionBasketRepository', function (): void { + it('returns null if session is empty', function (): void { // GIVEN $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(false); - - $serializer = \Mockery::mock(BasketSerializer::class); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + $session = new Store('test', new ArraySessionHandler(120)); + $repo = new SessionBasketRepository($session, 'basket_key', new BasketSerializer()); // WHEN $basket = $repo->find($basketId); @@ -32,98 +28,64 @@ describe('SessionBasketRepository', function () { expect($basket)->toBeNull(); }); - it('returns deserialized basket if session has data', function () { + it('persists and retrieves a basket using real Store and BasketSerializer', function (): void { // GIVEN $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); - $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('{"id":"123"}'); - - $serializer = \Mockery::mock(BasketSerializer::class); - $basket = new Basket($basketId, []); - $serializer->shouldReceive('fromArray')->with(['id' => '123'])->andReturn($basket); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); - - // WHEN - $result = $repo->find($basketId); - - // THEN - expect($result)->toBe($basket); - }); - - it('returns null if session data is invalid json', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); - $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('invalid-json'); - - $serializer = \Mockery::mock(BasketSerializer::class); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); - - // WHEN - $basket = $repo->find($basketId); - - // THEN - expect($basket)->toBeNull(); - }); - - it('returns null if deserialization throws exception', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(true); - $session->shouldReceive('get')->with('basket_key' . $basketId->value->toString())->andReturn('{"id":"123"}'); - - $serializer = \Mockery::mock(BasketSerializer::class); - $serializer->shouldReceive('fromArray')->andThrow(new \Exception('error')); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); - - // WHEN - $basket = $repo->find($basketId); - - // THEN - expect($basket)->toBeNull(); - }); - - it('persists basket to session', function () { - // GIVEN - $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - - $serializer = \Mockery::mock(BasketSerializer::class); - $basket = new Basket($basketId, []); - $serializer->shouldReceive('toArray')->with($basket)->andReturn(['id' => '123']); - - $session->shouldReceive('put')->with('basket_key' . $basketId->value->toString(), '{"id":"123"}')->once(); - - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); + $basket = new Basket($basketId, []); + $session = new Store('test', new ArraySessionHandler(120)); + $repo = new SessionBasketRepository($session, 'basket_key', new BasketSerializer()); // WHEN $repo->persist($basket); + $retrieved = $repo->find($basketId); // THEN - // Expectations handled by Mockery counts automatically (the `once()` call above) + expect($session->has('basket_key' . $basketId->value->toString()))->toBeTrue() + ->and($retrieved)->toBeInstanceOf(Basket::class) + ->and($retrieved?->id->equals($basketId))->toBeTrue(); }); - it('deletes basket from session', function () { + it('returns null if session data is invalid json', function (): void { // GIVEN $basketId = new BasketId(Uuid::uuid7()); - $session = \Mockery::mock(Session::class); - $session->shouldReceive('forget')->with('basket_key' . $basketId->value->toString())->once(); + $session = new Store('test', new ArraySessionHandler(120)); + $session->put('basket_key' . $basketId->value->toString(), 'invalid-json'); + $repo = new SessionBasketRepository($session, 'basket_key', new BasketSerializer()); - $serializer = \Mockery::mock(BasketSerializer::class); + // WHEN + $basket = $repo->find($basketId); - $repo = new SessionBasketRepository($session, 'basket_key', $serializer); - $basket = new Basket($basketId, []); + // THEN + expect($basket)->toBeNull(); + }); + + it('returns null if deserialization throws exception', function (): void { + // GIVEN + $basketId = new BasketId(Uuid::uuid7()); + $session = new Store('test', new ArraySessionHandler(120)); + $session->put('basket_key' . $basketId->value->toString(), '{"invalid":"payload"}'); + $repo = new SessionBasketRepository($session, 'basket_key', new BasketSerializer()); + + // WHEN + $basket = $repo->find($basketId); + + // THEN + expect($basket)->toBeNull(); + }); + + it('deletes basket from session', function (): void { + // GIVEN + $basketId = new BasketId(Uuid::uuid7()); + $basket = new Basket($basketId, []); + $session = new Store('test', new ArraySessionHandler(120)); + $repo = new SessionBasketRepository($session, 'basket_key', new BasketSerializer()); + $repo->persist($basket); // WHEN $repo->delete($basket); // THEN - // Expectations handled by Mockery automatically + expect($session->has('basket_key' . $basketId->value->toString()))->toBeFalse() + ->and($repo->find($basketId))->toBeNull(); }); }); diff --git a/tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php b/tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php index 60b8d8e1..66f51a63 100644 --- a/tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php +++ b/tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php @@ -4,84 +4,101 @@ declare(strict_types=1); namespace Tests\Integration\Standalones\Infra\Adapters\Services; -use Domain\Builders\OrderBuilderWithBasket; -use Illuminate\Contracts\Session\Session; +use Domain\Builders\OrderBuilder; +use Domain\Models\Entities\Basket; +use Domain\Models\ValueObjects\Entities\BasketId; +use Domain\Models\ValueObjects\Entities\ShopperId; +use Illuminate\Session\ArraySessionHandler; +use Illuminate\Session\Store; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; +use Ramsey\Uuid\Uuid; -it('throws exception if session key is empty', function () { - // GIVEN - $session = \Mockery::mock(Session::class); +describe('SessionOrderBuilderManager', function (): void { + it('throws exception if session key is empty', function (): void { + // GIVEN + $session = new Store('test', new ArraySessionHandler(120)); - // WHEN - $action = fn () => new SessionOrderBuilderManager($session, ' '); + // WHEN + $action = static fn (): SessionOrderBuilderManager => new SessionOrderBuilderManager($session, ' '); - // THEN - expect($action)->toThrow(\InvalidArgumentException::class, 'Session key cannot be empty'); -}); - -it('gets order builder from session', function () { - // GIVEN - $session = \Mockery::mock(Session::class); - $builder = \Mockery::mock(OrderBuilderWithBasket::class); - $session->shouldReceive('get')->with('builder_key')->andReturn($builder); - $repo = new SessionOrderBuilderManager($session, 'builder_key'); - - // WHEN - $result = $repo->get(); - - // THEN - expect($result)->toBe($builder); -}); - -it('returns null if order builder not in session', function () { - // GIVEN - $session = \Mockery::mock(Session::class); - $session->shouldReceive('get')->with('builder_key')->andReturn(null); - $repo = new SessionOrderBuilderManager($session, 'builder_key'); - - // WHEN - $result = $repo->get(); - - // THEN - expect($result)->toBeNull(); -}); - -it('throws exception if invalid session data for order builder', function () { - // GIVEN - $session = \Mockery::mock(Session::class); - $session->shouldReceive('get')->with('builder_key')->andReturn('invalid-data'); - $repo = new SessionOrderBuilderManager($session, 'builder_key'); - - // WHEN - $action = fn () => $repo->get(); - - // THEN - expect($action)->toThrow(\UnexpectedValueException::class, 'Invalid session data for order builder'); -}); - -it('saves order builder to session', function () { - // GIVEN - $session = \Mockery::mock(Session::class); - $builder = \Mockery::mock(OrderBuilderWithBasket::class); - $session->shouldReceive('put')->with('builder_key', $builder)->once(); - $repo = new SessionOrderBuilderManager($session, 'builder_key'); - - // WHEN - $repo->save($builder); - - // THEN - expect(true)->toBeTrue(); -}); - -it('clears order builder from session', function () { - // GIVEN - $session = \Mockery::mock(Session::class); - $session->shouldReceive('forget')->with('builder_key')->once(); - $repo = new SessionOrderBuilderManager($session, 'builder_key'); - - // WHEN - $repo->clear(); - - // THEN - expect(true)->toBeTrue(); + // THEN + expect($action)->toThrow(\InvalidArgumentException::class, 'Session key cannot be empty'); + }); + + it('gets order builder from session', function (): void { + // GIVEN + $session = new Store('test', new ArraySessionHandler(120)); + $builder = OrderBuilder::fromBasket( + new Basket(new BasketId(Uuid::uuid7()), []), + new ShopperId(Uuid::uuid7()), + ); + $session->put('builder_key', $builder); + $manager = new SessionOrderBuilderManager($session, 'builder_key'); + + // WHEN + $result = $manager->get(); + + // THEN + expect($result)->toBe($builder); + }); + + it('returns null if order builder not in session', function (): void { + // GIVEN + $session = new Store('test', new ArraySessionHandler(120)); + $manager = new SessionOrderBuilderManager($session, 'builder_key'); + + // WHEN + $result = $manager->get(); + + // THEN + expect($result)->toBeNull(); + }); + + it('throws exception if invalid session data for order builder', function (): void { + // GIVEN + $session = new Store('test', new ArraySessionHandler(120)); + $session->put('builder_key', 'invalid-data'); + $manager = new SessionOrderBuilderManager($session, 'builder_key'); + + // WHEN + $action = static fn () => $manager->get(); + + // THEN + expect($action)->toThrow(\UnexpectedValueException::class, 'Invalid session data for order builder'); + }); + + it('saves order builder to session', function (): void { + // GIVEN + $session = new Store('test', new ArraySessionHandler(120)); + $builder = OrderBuilder::fromBasket( + new Basket(new BasketId(Uuid::uuid7()), []), + new ShopperId(Uuid::uuid7()), + ); + $manager = new SessionOrderBuilderManager($session, 'builder_key'); + + // WHEN + $manager->save($builder); + + // THEN + expect($session->get('builder_key'))->toBe($builder) + ->and($manager->get())->toBe($builder); + }); + + it('clears order builder from session', function (): void { + // GIVEN + $session = new Store('test', new ArraySessionHandler(120)); + $builder = OrderBuilder::fromBasket( + new Basket(new BasketId(Uuid::uuid7()), []), + new ShopperId(Uuid::uuid7()), + ); + $session->put('builder_key', $builder); + $manager = new SessionOrderBuilderManager($session, 'builder_key'); + + // WHEN + $manager->clear(); + + // THEN + expect($session->has('builder_key'))->toBeFalse() + ->and($manager->get())->toBeNull(); + }); }); diff --git a/tests/Integration/WithApp/App/Services/FlashMessageServiceTest.php b/tests/Integration/WithApp/App/Services/FlashMessageServiceTest.php index c5d1ab2f..b98d2b92 100644 --- a/tests/Integration/WithApp/App/Services/FlashMessageServiceTest.php +++ b/tests/Integration/WithApp/App/Services/FlashMessageServiceTest.php @@ -5,108 +5,92 @@ declare(strict_types=1); namespace Tests\Integration\WithApp\App\Services; use App\Services\FlashMessageService; -use Illuminate\Support\Facades\Facade; +use Illuminate\Session\ArraySessionHandler; +use Illuminate\Session\Store; use Illuminate\Support\Facades\Session; covers(FlashMessageService::class); -afterEach(function () { - \Mockery::close(); - Facade::clearResolvedInstances(); -}); +describe('FlashMessageService', function (): void { + beforeEach(function (): void { + Session::swap(new Store('test', new ArraySessionHandler(120))); + }); -describe('FlashMessageService', function () { - describe('add()', function () { - it('adds a message without erasing previous', function () { + describe('add()', function (): void { + it('adds a message without erasing previous', function (): void { // GIVEN - Session::shouldReceive('get')->with('info', [])->andReturn(['First message']); - Session::shouldReceive('flash')->with('info', ['First message', 'Second message'])->once(); - + Session::put('info', ['First message']); $service = new FlashMessageService(); // WHEN $service->add('info', 'Second message'); // THEN - expect(true)->toBeTrue(); + expect(Session::get('info'))->toBe(['First message', 'Second message']); }); - it('adds a message when existing is not an array', function () { + it('adds a message when existing is not an array', function (): void { // GIVEN - Session::shouldReceive('get')->with('info', [])->andReturn('First message'); - Session::shouldReceive('flash')->with('info', ['First message', 'Second message'])->once(); - + Session::put('info', 'First message'); $service = new FlashMessageService(); // WHEN $service->add('info', 'Second message'); // THEN - expect(true)->toBeTrue(); + expect(Session::get('info'))->toBe(['First message', 'Second message']); }); }); - describe('info()', function () { - it('adds an info message', function () { + describe('info()', function (): void { + it('adds an info message', function (): void { // GIVEN - Session::shouldReceive('get')->with('info', [])->andReturn([]); - Session::shouldReceive('flash')->with('info', ['Info msg'])->once(); - $service = new FlashMessageService(); // WHEN $service->info('Info msg'); // THEN - expect(true)->toBeTrue(); + expect(Session::get('info'))->toBe(['Info msg']); }); }); - describe('success()', function () { - it('adds a success message', function () { + describe('success()', function (): void { + it('adds a success message', function (): void { // GIVEN - Session::shouldReceive('get')->with('success', [])->andReturn([]); - Session::shouldReceive('flash')->with('success', ['Success msg'])->once(); - $service = new FlashMessageService(); // WHEN $service->success('Success msg'); // THEN - expect(true)->toBeTrue(); + expect(Session::get('success'))->toBe(['Success msg']); }); }); - describe('error()', function () { - it('adds an error message', function () { + describe('error()', function (): void { + it('adds an error message', function (): void { // GIVEN - Session::shouldReceive('get')->with('error', [])->andReturn([]); - Session::shouldReceive('flash')->with('error', ['Error msg'])->once(); - $service = new FlashMessageService(); // WHEN $service->error('Error msg'); // THEN - expect(true)->toBeTrue(); + expect(Session::get('error'))->toBe(['Error msg']); }); }); - describe('warning()', function () { - it('adds a warning message', function () { + describe('warning()', function (): void { + it('adds a warning message', function (): void { // GIVEN - Session::shouldReceive('get')->with('warning', [])->andReturn([]); - Session::shouldReceive('flash')->with('warning', ['Warning msg'])->once(); - $service = new FlashMessageService(); // WHEN $service->warning('Warning msg'); // THEN - expect(true)->toBeTrue(); + expect(Session::get('warning'))->toBe(['Warning msg']); }); }); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/LaravelTransactionManagerTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/LaravelTransactionManagerTest.php index ce48922f..5a611a88 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/LaravelTransactionManagerTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/LaravelTransactionManagerTest.php @@ -4,21 +4,39 @@ declare(strict_types=1); namespace Tests\Integration\WithApp\Infra\Adapters\Services; -use Illuminate\Support\Facades\DB; +use App\Models\Tag; use Infrastructure\Adapters\Services\LaravelTransactionManager; -it('executes callback in transaction', function () { - // GIVEN - DB::shouldReceive('transaction')->once()->andReturnUsing(function ($callback) { - return $callback(); - }); - $manager = new LaravelTransactionManager(); +describe('LaravelTransactionManager', function (): void { + it('commits database writes and returns callback result when callback succeeds', function (): void { + // GIVEN + $manager = new LaravelTransactionManager(); - // WHEN - $result = $manager->execute(function () { - return 'success'; + // WHEN + $result = $manager->execute(static function (): string { + Tag::factory()->createOne(['label' => 'Tx Committed Tag']); + + return 'success'; + }); + + // THEN + expect($result)->toBe('success') + ->and(Tag::query()->where('label', 'Tx Committed Tag')->exists())->toBeTrue(); }); - // THEN - expect($result)->toBe('success'); + it('rolls back database writes when callback throws an exception', function (): void { + // GIVEN + $manager = new LaravelTransactionManager(); + + // WHEN + $action = static fn (): mixed => $manager->execute(static function (): never { + Tag::factory()->createOne(['label' => 'Tx Rolled Back Tag']); + + throw new \RuntimeException('Transaction failure'); + }); + + // THEN + expect($action)->toThrow(\RuntimeException::class, 'Transaction failure') + ->and(Tag::query()->where('label', 'Tx Rolled Back Tag')->exists())->toBeFalse(); + }); }); From 4f2b7ba0c0f7b02391b4f6f9a4982fc8398842a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 15:07:53 +0100 Subject: [PATCH 137/183] test(tests): update ArcadiaIncoServiceTest for null safety Refactor assertions to use null-safe operator and simplify instantiation of IncoNutriscore. --- .../App/Services/ArcadiaIncoServiceTest.php | 144 ++++++++++++++---- 1 file changed, 113 insertions(+), 31 deletions(-) diff --git a/tests/Unit/App/Services/ArcadiaIncoServiceTest.php b/tests/Unit/App/Services/ArcadiaIncoServiceTest.php index 552ca91f..8bb86ac8 100644 --- a/tests/Unit/App/Services/ArcadiaIncoServiceTest.php +++ b/tests/Unit/App/Services/ArcadiaIncoServiceTest.php @@ -108,7 +108,7 @@ describe('ArcadiaIncoService', function (): void { brand: new Brand(new BrandCode('LGL01'), 'Le Gaulois'), isSeasonal: false, weight: null, - nutriscore: new IncoNutriscore('A', null), + nutriscore: new IncoNutriscore('A'), storageCondition: null, additives: [], compo: new IncoCompoId('88888'), @@ -121,31 +121,113 @@ describe('ArcadiaIncoService', function (): void { idInco: $incoId, identification: new Identification('Poulet Jaune', '27996', 'SNV'), energie: new Energie('100', '623', '149', '150', '935', '224'), - macronutrimentsRef: new MacronutrimentsRef( - '7.2', '=', '2.0', '=', '0.0', '=', '0.0', '=', '0.0', '=', '21.0', '=', '0.16', '=', '64' - ), + macronutrimentsRef: new MacronutrimentsRef('7.2', '=', '2.0', '=', '0.0', '=', '0.0', '=', '0.0', '=', '21.0', '=', '0.16', '=', '64'), macronutrimentsPortion: new MacronutrimentsPortion( - '10.8', '=', '3.0', '=', '0.0', '=', '0.0', '=', '0.0', '=', '31.5', '=', '0.24', '=', '96' + '10.8', + '=', + '3.0', + '=', + '0.0', + '=', + '0.0', + '=', + '0.0', + '=', + '31.5', + '=', + '0.24', + '=', + '96' ), fnl: new FruitLegumeNoix('0', '0', '0', '0', '0', '0', '0', '0'), apportsReference: new ApportsReference( - '11', '11', '15', '15', '0', '0', '63', '4', '150g', '2.9' + '11', + '11', + '15', + '15', + '0', + '0', + '63', + '4', + '150g', + '2.9' ), nutriScore: new CompoNutriScore( - '2', '2', '5', '5', '-3', '-3', 'A', 'A', '1', '0' + '2', + '2', + '5', + '5', + '-3', + '-3', + 'A', + 'A', + '1', + '0' ), pointsNutriScore: new PointsNutriScore('0', '0', '0', '0', '0', '0', '0'), mineraux: new Mineraux('0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'), vitamines: new Vitamines('0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'), glucidesDetail: new GlucidesDetail('0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'), acideGras: new AcideGras( - '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', - '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', - '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', - '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', - '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', - '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', - '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', + '0', ), acidesAmines: new AcidesAmines('0', '0', '0'), composesSpeciaux: new ComposesSpeciaux('0', '0', '0', '0'), @@ -161,18 +243,18 @@ describe('ArcadiaIncoService', function (): void { // THEN expect($result)->toBeInstanceOf(ArcadiaIncoDataDto::class) - ->and($result->noArt)->toBe(27996) - ->and($result->name)->toBe('POULET JAUNE FERMIER') - ->and($result->brand)->toBe('Le Gaulois') - ->and($result->nutriscore)->toBe(Nutriscore::A) - ->and($result->allergens)->toBe('Aucun allergène') - ->and($result->servings)->toBe('entre 4 et 5') - ->and($result->preparation)->toContain('Cuire à 200°C') - ->and($result->ingredients)->toContain('Poulet Jaune (100%)') - ->and($result->nutrition->kj)->toBe(623.0) - ->and($result->nutrition->kcal)->toBe(149.0) - ->and($result->nutrition->fatG)->toBe(7.2) - ->and($result->nutrition->proteinG)->toBe(21.0); + ->and($result?->noArt)->toBe(27996) + ->and($result?->name)->toBe('POULET JAUNE FERMIER') + ->and($result?->brand)->toBe('Le Gaulois') + ->and($result?->nutriscore)->toBe(Nutriscore::A) + ->and($result?->allergens)->toBe('Aucun allergène') + ->and($result?->servings)->toBe('entre 4 et 5') + ->and($result?->preparation)->toContain('Cuire à 200°C') + ->and($result?->ingredients)->toContain('Poulet Jaune (100%)') + ->and($result?->nutrition->kj)->toBe(623.0) + ->and($result?->nutrition->kcal)->toBe(149.0) + ->and($result?->nutrition->fatG)->toBe(7.2) + ->and($result?->nutrition->proteinG)->toBe(21.0); }); it('returns preview DTO correctly', function (): void { @@ -200,7 +282,7 @@ describe('ArcadiaIncoService', function (): void { brand: new Brand(new BrandCode('LGL01'), 'Le Gaulois'), isSeasonal: false, weight: null, - nutriscore: new IncoNutriscore('A', null), + nutriscore: new IncoNutriscore('A'), storageCondition: null, additives: [], compo: null, @@ -218,9 +300,9 @@ describe('ArcadiaIncoService', function (): void { // THEN expect($preview)->toBeInstanceOf(ArcadiaIncoPreviewDto::class) - ->and($preview->noArt)->toBe(27996) - ->and($preview->name)->toBe('POULET JAUNE FERMIER') - ->and($preview->brand)->toBe('Le Gaulois') - ->and($preview->nutriscore)->toBe('A'); + ->and($preview?->noArt)->toBe(27996) + ->and($preview?->name)->toBe('POULET JAUNE FERMIER') + ->and($preview?->brand)->toBe('Le Gaulois') + ->and($preview?->nutriscore)->toBe('A'); }); }); From 1c304b78b2deb6f0b8391f0ee90a78fb9487c3b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 15:12:42 +0100 Subject: [PATCH 138/183] test(decouple): remove expect(true)->toBeTrue() and move ProductPolicy INCO checks to WithApp --- .../Actions/Contact/SubmitContactFormTest.php | 37 +++--- .../Cqs/Actions/Ranges/DeleteRangeTest.php | 12 +- .../Policies/Backend/ProductPolicyTest.php | 111 ++++++++++++++++++ .../Services/AppCustomerAuthServiceTest.php | 12 +- .../Orders/EmptyBasketOnOrderPlacedTest.php | 18 +-- ...validateOrderBuilderOnBasketChangeTest.php | 14 +-- .../Policies/Backend/ProductPolicyTest.php | 69 +---------- .../Policies/CustomerOrderLimitPolicyTest.php | 24 ++-- .../Domain/Services/BasketServiceTest.php | 23 ++-- .../Services/OrderTunnelServiceTest.php | 6 +- 10 files changed, 187 insertions(+), 139 deletions(-) create mode 100644 tests/Integration/WithApp/App/Policies/Backend/ProductPolicyTest.php diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php index c384ea81..f53acd16 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php @@ -100,24 +100,11 @@ describe('SubmitContactForm action', function (): void { // GIVEN $file = UploadedFile::fake()->create('document.pdf', 100, 'application/pdf'); $storedPath = new StorageFilePath('contact-attachments/orphan.pdf'); - $storage = \Mockery::mock(StorageService::class); - $storage->shouldReceive('storeUploadedOntoDisk') - ->once() - ->andReturn($storedPath); - $storage->shouldReceive('fileExistsOnDisk') - ->once() - ->with( - \Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'contact-attachments/orphan.pdf'), - \Mockery::on(fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), - ) - ->andReturnTrue(); - $storage->shouldReceive('removeFromDisk') - ->once() - ->with( - \Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'contact-attachments/orphan.pdf'), - \Mockery::on(fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), - ) - ->andReturnTrue(); + /** @var StorageService&\Mockery\MockInterface $storage */ + $storage = \Mockery::spy(StorageService::class); + $storage->allows('storeUploadedOntoDisk')->andReturn($storedPath); + $storage->allows('fileExistsOnDisk')->andReturnTrue(); + $storage->allows('removeFromDisk')->andReturnTrue(); $action = new SubmitContactForm($storage, new PrivateS3Disk()); $input = new SubmitContactFormInput( @@ -134,6 +121,18 @@ describe('SubmitContactForm action', function (): void { $action->onFailure($input, new \RuntimeException('Mail dispatch failed')); // THEN - expect(true)->toBeTrue(); + $storage->shouldHaveReceived('storeUploadedOntoDisk')->once(); + $storage->shouldHaveReceived('fileExistsOnDisk') + ->once() + ->with( + \Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'contact-attachments/orphan.pdf'), + \Mockery::on(static fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), + ); + $storage->shouldHaveReceived('removeFromDisk') + ->once() + ->with( + \Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'contact-attachments/orphan.pdf'), + \Mockery::on(static fn (DiskName $disk): bool => $disk->value === PrivateS3Disk::DISK_NAME), + ); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php index e4ead4c8..e7628efa 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php @@ -78,8 +78,7 @@ describe('DeleteRange action', function () { $this->assertDatabaseMissing('ranges', ['id' => $range->id]); }); - test('it preserves S3 picture when DeleteRange triggers failure hook before commit', function () { - /** @var \Tests\TestCase $this */ + test('it preserves S3 picture when DeleteRange triggers failure hook before commit', function (): void { // GIVEN $range = new Range(); $range->name = 'Gamme Protégée'; @@ -89,9 +88,8 @@ describe('DeleteRange action', function () { $range->picture = new StorageFilePath('media/keep-range.jpg'); $range->save(); - $storage = \Mockery::mock(StorageService::class); - $storage->shouldNotReceive('fileExistsOnDisk'); - $storage->shouldNotReceive('removeFromDisk'); + /** @var StorageService&\Mockery\MockInterface $storage */ + $storage = \Mockery::spy(StorageService::class); $action = new DeleteRange($storage, new PublicS3Disk('https://cdn.test')); $input = new DeleteRangeInput(range: $range); @@ -101,7 +99,9 @@ describe('DeleteRange action', function () { $action->onFailure($input, new \RuntimeException('Simulated rollback')); // THEN - expect(true)->toBeTrue(); + expect(Range::query()->find($range->id))->toBeNull(); + $storage->shouldNotHaveReceived('fileExistsOnDisk'); + $storage->shouldNotHaveReceived('removeFromDisk'); }); test('it throws when an invalid input is passed', function () { diff --git a/tests/Integration/WithApp/App/Policies/Backend/ProductPolicyTest.php b/tests/Integration/WithApp/App/Policies/Backend/ProductPolicyTest.php new file mode 100644 index 00000000..2d28a64e --- /dev/null +++ b/tests/Integration/WithApp/App/Policies/Backend/ProductPolicyTest.php @@ -0,0 +1,111 @@ +name = 'Gamme Policy ' . uniqid(); + $range->status = true; + $range->order = random_int(1, 99999); + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $product = new Product(); + $product->name = 'Poulet Policy ' . uniqid(); + $product->brand = ProductBrand::loue; + $product->description = 'Description complète de test'; + $product->short_description = 'Court'; + $product->price = Money::EUR(1000); + $product->invoicing_unit = InvoicingUnit::PCE; + $product->tax_rate = TaxRate::TVA_5_5; + $product->stock = 50; + $product->weight = 1000; + $product->sell_unit = SellUnit::PCE; + $product->order_unit = OrderUnit::PCE; + $product->range_id = $range->id; + $product->status = true; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt large'; + $product->picture_large_title = 'title large'; + $product->saveOrFail(); + + return $product; +} + +describe('Backend ProductPolicy Eloquent INCO abilities', function (): void { + it('allows createInco and denies updateInco/syncInco for admin when product has no INCO', function (): void { + // GIVEN + $admin = User::factory()->createOne(['role' => UserRole::Admin]); + $product = createPolicyTestProduct(); + $policy = new ProductPolicy(new EloquentProductRepository()); + + // WHEN + $canCreate = $policy->createInco($admin, $product); + $canUpdate = $policy->updateInco($admin, $product); + $canSync = $policy->syncInco($admin, $product); + + // THEN + expect($canCreate)->toBeTrue() + ->and($canUpdate)->toBeFalse() + ->and($canSync)->toBeFalse(); + }); + + it('denies createInco and allows updateInco/syncInco for admin when product has an INCO', function (): void { + // GIVEN + $admin = User::factory()->createOne(['role' => UserRole::Admin]); + $product = createPolicyTestProduct(); + $inco = new ProductInco(); + $inco->product_id = $product->id; + $inco->no_art = 27996; + $inco->saveOrFail(); + + $policy = new ProductPolicy(new EloquentProductRepository()); + + // WHEN + $canCreate = $policy->createInco($admin, $product); + $canUpdate = $policy->updateInco($admin, $product); + $canSync = $policy->syncInco($admin, $product); + + // THEN + expect($canCreate)->toBeFalse() + ->and($canUpdate)->toBeTrue() + ->and($canSync)->toBeTrue(); + }); + + it('denies createInco, updateInco and syncInco for customer even when product exists', function (): void { + // GIVEN + $customer = new Customer(); + $product = createPolicyTestProduct(); + $policy = new ProductPolicy(new EloquentProductRepository()); + + // WHEN + $canCreate = $policy->createInco($customer, $product); + $canUpdate = $policy->updateInco($customer, $product); + $canSync = $policy->syncInco($customer, $product); + + // THEN + expect($canCreate)->toBeFalse() + ->and($canUpdate)->toBeFalse() + ->and($canSync)->toBeFalse(); + }); +}); diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php index 5ec42471..121778d0 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php @@ -63,14 +63,14 @@ describe('AppCustomerAuthService', function (): void { it('logs in customer when active', function (): void { // GIVEN - $guard = Mockery::mock(StatefulGuard::class); + /** @var StatefulGuard&\Mockery\MockInterface $guard */ + $guard = Mockery::spy(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); $customer->id = (string) Uuid::uuid7(); $shopperService->shouldReceive('canCustomerPassOrdersApp')->withAnyArgs()->andReturn(true); - $guard->shouldReceive('login')->with($customer)->once(); $service = new AppCustomerAuthService($guard, $crmService, $shopperService); @@ -78,7 +78,7 @@ describe('AppCustomerAuthService', function (): void { $service->logIn($customer); // THEN - expect(true)->toBeTrue(); + $guard->shouldHaveReceived('login')->with($customer)->once(); }); it('throws exception if logging in non-authenticatable', function (): void { @@ -102,10 +102,10 @@ describe('AppCustomerAuthService', function (): void { it('logs out', function (): void { // GIVEN - $guard = Mockery::mock(StatefulGuard::class); + /** @var StatefulGuard&\Mockery\MockInterface $guard */ + $guard = Mockery::spy(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); $shopperService = Mockery::mock(ShopperService::class); - $guard->shouldReceive('logout')->once(); $service = new AppCustomerAuthService($guard, $crmService, $shopperService); @@ -113,7 +113,7 @@ describe('AppCustomerAuthService', function (): void { $service->logout(); // THEN - expect(true)->toBeTrue(); + $guard->shouldHaveReceived('logout')->once(); }); it('checks if user is logged in', function (): void { diff --git a/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php b/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php index f1ac0501..363625cc 100644 --- a/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php +++ b/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php @@ -35,17 +35,15 @@ describe('EmptyBasketOnOrderPlaced', function (): void { $sessionUuid = Uuid::uuid7(); $basket = new Basket(new BasketId($sessionUuid)); - $basketRepository = \Mockery::mock(BasketRepository::class); - $basketRepository->shouldReceive('find')->once()->andReturn($basket); - $basketRepository->shouldReceive('delete')->once()->with($basket); + /** @var BasketRepository&\Mockery\MockInterface $basketRepository */ + $basketRepository = \Mockery::spy(BasketRepository::class); + $basketRepository->allows('find')->andReturn($basket); $sessionService = \Mockery::mock(SessionService::class); $sessionService->shouldReceive('get')->once()->andReturn(new SessionId($sessionUuid)); - $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); - $eventDispatcher->shouldReceive('dispatch') - ->once() - ->with(\Mockery::on(fn (BasketRemoved $event): bool => $event->basketId->equals($basket->id))); + /** @var DomainEventDispatcher&\Mockery\MockInterface $eventDispatcher */ + $eventDispatcher = \Mockery::spy(DomainEventDispatcher::class); $basketService = new BasketService( $basketRepository, @@ -92,6 +90,10 @@ describe('EmptyBasketOnOrderPlaced', function (): void { $listener->handle($event); // THEN - expect(true)->toBeTrue(); + $basketRepository->shouldHaveReceived('find')->once(); + $basketRepository->shouldHaveReceived('delete')->once()->with($basket); + $eventDispatcher->shouldHaveReceived('dispatch') + ->once() + ->with(\Mockery::on(static fn (BasketRemoved $event): bool => $event->basketId->equals($basket->id))); }); }); diff --git a/tests/Unit/App/Listeners/Orders/InvalidateOrderBuilderOnBasketChangeTest.php b/tests/Unit/App/Listeners/Orders/InvalidateOrderBuilderOnBasketChangeTest.php index 6709f8a4..8f5727c3 100644 --- a/tests/Unit/App/Listeners/Orders/InvalidateOrderBuilderOnBasketChangeTest.php +++ b/tests/Unit/App/Listeners/Orders/InvalidateOrderBuilderOnBasketChangeTest.php @@ -14,9 +14,8 @@ use Ramsey\Uuid\Uuid; describe('InvalidateOrderBuilderOnBasketChange', function (): void { it('clears the order builder session manager when basket is modified', function (): void { // GIVEN - $manager = \Mockery::mock(OrderBuilderSessionManager::class); - $manager->shouldReceive('clear')->once(); - + /** @var OrderBuilderSessionManager&\Mockery\MockInterface $manager */ + $manager = \Mockery::spy(OrderBuilderSessionManager::class); $listener = new InvalidateOrderBuilderOnBasketChange($manager); $event = new BasketHasBeenModified(new BasketId(Uuid::uuid7())); @@ -24,14 +23,13 @@ describe('InvalidateOrderBuilderOnBasketChange', function (): void { $listener->handle($event); // THEN - expect(true)->toBeTrue(); + $manager->shouldHaveReceived('clear')->once(); }); it('clears the order builder session manager when basket is removed', function (): void { // GIVEN - $manager = \Mockery::mock(OrderBuilderSessionManager::class); - $manager->shouldReceive('clear')->once(); - + /** @var OrderBuilderSessionManager&\Mockery\MockInterface $manager */ + $manager = \Mockery::spy(OrderBuilderSessionManager::class); $listener = new InvalidateOrderBuilderOnBasketChange($manager); $event = new BasketRemoved(new BasketId(Uuid::uuid7())); @@ -39,6 +37,6 @@ describe('InvalidateOrderBuilderOnBasketChange', function (): void { $listener->handle($event); // THEN - expect(true)->toBeTrue(); + $manager->shouldHaveReceived('clear')->once(); }); }); diff --git a/tests/Unit/App/Policies/Backend/ProductPolicyTest.php b/tests/Unit/App/Policies/Backend/ProductPolicyTest.php index 0fef3a31..fed9c41f 100644 --- a/tests/Unit/App/Policies/Backend/ProductPolicyTest.php +++ b/tests/Unit/App/Policies/Backend/ProductPolicyTest.php @@ -15,19 +15,18 @@ use Domain\Enums\UserRole; use Domain\Models\Entities\Product as DomainProduct; use Domain\Models\ValueObjects\Entities\ProductId; use Domain\Ports\Repositories\ProductRepository; -use Illuminate\Database\Eloquent\Relations\HasOne; use Money\Money; use Ramsey\Uuid\Uuid; describe('ProductPolicy', function () { - function getProductPolicy($repo = null) + function getProductPolicy(?ProductRepository $repo = null): ProductPolicy { return new ProductPolicy( $repo ?? \Mockery::mock(ProductRepository::class) ); } - function createDomainProduct(bool $status = true) + function createDomainProduct(bool $status = true): DomainProduct { return new DomainProduct( new ProductId(Uuid::uuid7()), @@ -236,38 +235,6 @@ describe('ProductPolicy', function () { // THEN expect($result)->toBeFalse(); }); - test('createInco returns true for admin when inco does not exist', function () { - // GIVEN - $user = new User(); - $user->role = UserRole::Admin; - $product = \Mockery::mock(Product::class); - $incoMock = \Mockery::mock(HasOne::class); - $incoMock->shouldReceive('exists')->andReturn(false); - $product->shouldReceive('inco')->andReturn($incoMock); - $policy = getProductPolicy(); - - // WHEN - $result = $policy->createInco($user, $product); - - // THEN - expect($result)->toBeTrue(); - }); - test('createInco returns false for admin when inco exists', function () { - // GIVEN - $user = new User(); - $user->role = UserRole::Admin; - $product = \Mockery::mock(Product::class); - $incoMock = \Mockery::mock(HasOne::class); - $incoMock->shouldReceive('exists')->andReturn(true); - $product->shouldReceive('inco')->andReturn($incoMock); - $policy = getProductPolicy(); - - // WHEN - $result = $policy->createInco($user, $product); - - // THEN - expect($result)->toBeFalse(); - }); // updateInco test('updateInco returns false for customer', function () { @@ -282,38 +249,6 @@ describe('ProductPolicy', function () { // THEN expect($result)->toBeFalse(); }); - test('updateInco returns false for admin when inco does not exist', function () { - // GIVEN - $user = new User(); - $user->role = UserRole::Admin; - $product = \Mockery::mock(Product::class); - $incoMock = \Mockery::mock(HasOne::class); - $incoMock->shouldReceive('exists')->andReturn(false); - $product->shouldReceive('inco')->andReturn($incoMock); - $policy = getProductPolicy(); - - // WHEN - $result = $policy->updateInco($user, $product); - - // THEN - expect($result)->toBeFalse(); - }); - test('updateInco returns true for admin when inco exists', function () { - // GIVEN - $user = new User(); - $user->role = UserRole::Admin; - $product = \Mockery::mock(Product::class); - $incoMock = \Mockery::mock(HasOne::class); - $incoMock->shouldReceive('exists')->andReturn(true); - $product->shouldReceive('inco')->andReturn($incoMock); - $policy = getProductPolicy(); - - // WHEN - $result = $policy->updateInco($user, $product); - - // THEN - expect($result)->toBeTrue(); - }); // viewPublished test('viewPublished returns false when product not found in domain repo', function () { diff --git a/tests/Unit/Domain/Policies/CustomerOrderLimitPolicyTest.php b/tests/Unit/Domain/Policies/CustomerOrderLimitPolicyTest.php index 8216b77e..515ddf89 100644 --- a/tests/Unit/Domain/Policies/CustomerOrderLimitPolicyTest.php +++ b/tests/Unit/Domain/Policies/CustomerOrderLimitPolicyTest.php @@ -11,28 +11,28 @@ use Money\Currency; use Money\Money; describe('CustomerOrderLimitPolicy', function () { - it('asserts can place order successfully when below limit', function () { + it('asserts can place order successfully when below limit', function (): void { // GIVEN $policy = new CustomerOrderLimitPolicy(20000, 20000, new Currency('EUR')); $basketTotal = new Money(19999, new Currency('EUR')); // WHEN - $policy->assertCanPlaceOrder($basketTotal); + $action = static fn () => $policy->assertCanPlaceOrder($basketTotal); // THEN - expect(true)->toBeTrue(); + expect($action)->not->toThrow(OrderLimitExceededException::class); }); - it('asserts can place order successfully when exactly at limit', function () { + it('asserts can place order successfully when exactly at limit', function (): void { // GIVEN $policy = new CustomerOrderLimitPolicy(20000, 20000, new Currency('EUR')); $basketTotal = new Money(20000, new Currency('EUR')); // WHEN - $policy->assertCanPlaceOrder($basketTotal); + $action = static fn () => $policy->assertCanPlaceOrder($basketTotal); // THEN - expect(true)->toBeTrue(); + expect($action)->not->toThrow(OrderLimitExceededException::class); }); it('throws OrderLimitExceededException when above limit', function () { @@ -47,30 +47,30 @@ describe('CustomerOrderLimitPolicy', function () { expect($action)->toThrow(OrderLimitExceededException::class); }); - it('asserts can place weekly order successfully when below limit', function () { + it('asserts can place weekly order successfully when below limit', function (): void { // GIVEN $policy = new CustomerOrderLimitPolicy(20000, 30000, new Currency('EUR')); $basketTotal = new Money(10000, new Currency('EUR')); $weeklyTotal = new Money(19999, new Currency('EUR')); // WHEN - $policy->assertCanPlaceWeeklyOrder($basketTotal, $weeklyTotal); + $action = static fn () => $policy->assertCanPlaceWeeklyOrder($basketTotal, $weeklyTotal); // THEN - expect(true)->toBeTrue(); + expect($action)->not->toThrow(WeeklyLimitExceededException::class); }); - it('asserts can place weekly order successfully when exactly at limit', function () { + it('asserts can place weekly order successfully when exactly at limit', function (): void { // GIVEN $policy = new CustomerOrderLimitPolicy(20000, 30000, new Currency('EUR')); $basketTotal = new Money(10000, new Currency('EUR')); $weeklyTotal = new Money(20000, new Currency('EUR')); // WHEN - $policy->assertCanPlaceWeeklyOrder($basketTotal, $weeklyTotal); + $action = static fn () => $policy->assertCanPlaceWeeklyOrder($basketTotal, $weeklyTotal); // THEN - expect(true)->toBeTrue(); + expect($action)->not->toThrow(WeeklyLimitExceededException::class); }); it('throws WeeklyLimitExceededException when above limit', function () { diff --git a/tests/Unit/Domain/Services/BasketServiceTest.php b/tests/Unit/Domain/Services/BasketServiceTest.php index 8f949330..7ab56682 100644 --- a/tests/Unit/Domain/Services/BasketServiceTest.php +++ b/tests/Unit/Domain/Services/BasketServiceTest.php @@ -26,6 +26,7 @@ use Ramsey\Uuid\Uuid; use Shared\DDD\DomainEventDispatcher; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; +/** @param array $overrides */ function makeBasketProduct(array $overrides = []): BasketProduct { $data = array_merge([ @@ -178,19 +179,18 @@ describe('BasketService', function (): void { it('empties the basket by destroying it from repository and dispatches BasketRemoved', function (): void { // GIVEN - $basket = new Basket(new BasketId(Uuid::uuid7())); - $basketRepository = Mockery::mock(BasketRepository::class); - $sessionService = Mockery::mock(SessionService::class); + $basket = new Basket(new BasketId(Uuid::uuid7())); + /** @var BasketRepository&\Mockery\MockInterface $basketRepository */ + $basketRepository = Mockery::spy(BasketRepository::class); + $basketRepository->allows('find')->andReturn($basket); + + $sessionService = Mockery::mock(SessionService::class); $sessionService->shouldReceive('get')->andReturn(new SessionId(Uuid::uuid7()))->byDefault(); - $basketRepository->shouldReceive('find')->once()->andReturn($basket); - $basketRepository->shouldReceive('delete')->once()->with($basket); $productRepository = Mockery::mock(ProductRepository::class); - $eventDispatcher = Mockery::mock(DomainEventDispatcher::class); - $eventDispatcher->shouldReceive('dispatch') - ->once() - ->with(Mockery::on(fn (BasketRemoved $event): bool => $event->basketId->equals($basket->id))); + /** @var DomainEventDispatcher&\Mockery\MockInterface $eventDispatcher */ + $eventDispatcher = Mockery::spy(DomainEventDispatcher::class); $service = new BasketService($basketRepository, $productRepository, $sessionService, $eventDispatcher); @@ -198,7 +198,10 @@ describe('BasketService', function (): void { $service->empty(); // THEN - expect(true)->toBeTrue(); + $basketRepository->shouldHaveReceived('delete')->once()->with($basket); + $eventDispatcher->shouldHaveReceived('dispatch') + ->once() + ->with(Mockery::on(static fn (BasketRemoved $event): bool => $event->basketId->equals($basket->id))); }); it('gets the basket from repository without dispatching events', function (): void { diff --git a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php index 12ba95e9..d12eec6a 100644 --- a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php +++ b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php @@ -385,8 +385,8 @@ describe('OrderTunnelService', function (): void { $basket = createTestBasket(1); $customerId = new ShopperId(Uuid::uuid7()); - $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); - $orderBuilderRepo->shouldReceive('save')->once(); + /** @var OrderBuilderSessionManager&\Mockery\MockInterface $orderBuilderRepo */ + $orderBuilderRepo = \Mockery::spy(OrderBuilderSessionManager::class); $service = createOrderTunnelService(orderBuilderSessionManager: $orderBuilderRepo); @@ -394,7 +394,7 @@ describe('OrderTunnelService', function (): void { $service->initializeFromBasket($basket, $customerId); // THEN - expect(true)->toBeTrue(); + $orderBuilderRepo->shouldHaveReceived('save')->once(); }); it('gets builder from basket or fail', function (): void { From 1f642b185ed08562441e44124ad795b0335ed138 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 15:19:01 +0100 Subject: [PATCH 139/183] test(requests): overhaul BO Tags/Slides/Ranges/Products request tests and failure responses --- .../Controllers/Bo/ProductsControllerTest.php | 26 +++ .../Controllers/Bo/RangesControllerTest.php | 37 ++++ .../Controllers/Bo/SlidesControllerTest.php | 69 ++++++ .../Controllers/Bo/TagsControllerTest.php | 60 ++++++ .../Bo/Products/IndexProductRequestTest.php | 102 ++++----- .../Bo/Products/StoreProductRequestTest.php | 164 +++++++------- .../Bo/Ranges/StoreRangeRequestTest.php | 109 ++++++---- .../Bo/Slides/StoreSlideRequestTest.php | 202 +++++++++++------- .../Requests/Bo/Tags/StoreTagRequestTest.php | 67 +++--- 9 files changed, 547 insertions(+), 289 deletions(-) diff --git a/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php index 65431daf..4d4db005 100644 --- a/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php @@ -23,7 +23,9 @@ use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Gate; use Money\Money; +use function Pest\Laravel\from; use function Pest\Laravel\patch; +use function Pest\Laravel\postJson; describe('ProductsController', function () { @@ -756,4 +758,28 @@ describe('ProductsController', function () { $response->assertForbidden(); }); }); + + it('redirects back with session validation errors on invalid web store payload', function (): void { + // WHEN + $response = from('/bo/products/create')->post('/bo/products', [ + 'name' => 'AB', + 'client_timezone' => 'Europe/Paris', + ]); + + // THEN + $response->assertRedirect('/bo/products/create') + ->assertSessionHasErrors(['name', 'brand', 'short_description', 'description', 'price', 'range_id']); + }); + + it('returns 422 JSON validation errors on invalid JSON store payload', function (): void { + // WHEN + $response = postJson('/bo/products', [ + 'name' => 'AB', + 'client_timezone' => 'Europe/Paris', + ]); + + // THEN + $response->assertUnprocessable() + ->assertJsonValidationErrors(['name', 'brand', 'short_description', 'description', 'price', 'range_id']); + }); }); diff --git a/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php index e0426cd2..a3f6ed50 100644 --- a/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php @@ -15,8 +15,10 @@ use Illuminate\Support\Facades\Gate; use Uwil\Storage\Contracts\StorageService; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; +use function Pest\Laravel\from; use function Pest\Laravel\get; use function Pest\Laravel\patch; +use function Pest\Laravel\postJson; uses(RefreshDatabase::class); @@ -259,4 +261,39 @@ describe('RangesController', function () { // THEN $response->assertForbidden(); }); + + it('redirects unauthenticated guest to login', function (): void { + // GIVEN + auth('backend')->logout(); + + // WHEN + $response = get(route('bo.ranges.index')); + + // THEN + $response->assertRedirect('/bo/login'); + }); + + it('redirects back with session validation errors on invalid web store payload', function (): void { + // WHEN + $response = from('/bo/ranges/create')->post('/bo/ranges', [ + 'name' => 'A', + 'status' => true, + ]); + + // THEN + $response->assertRedirect('/bo/ranges/create') + ->assertSessionHasErrors('name'); + }); + + it('returns 422 JSON validation errors on invalid JSON store payload', function (): void { + // WHEN + $response = postJson('/bo/ranges', [ + 'name' => 'A', + 'status' => true, + ]); + + // THEN + $response->assertUnprocessable() + ->assertJsonValidationErrors('name'); + }); }); diff --git a/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php index d4f53324..47e4059c 100644 --- a/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php @@ -9,6 +9,12 @@ use App\Http\Requests\Bo\Slides\StoreSlideRequest; use App\Models\Slide; use App\Models\User; use Domain\Enums\UserRole; +use Illuminate\Support\Facades\Gate; + +use function Pest\Laravel\from; +use function Pest\Laravel\get; +use function Pest\Laravel\post; +use function Pest\Laravel\postJson; describe('SlidesController', function (): void { beforeEach(function (): void { @@ -150,4 +156,67 @@ describe('SlidesController', function (): void { ->and($slide2->order)->toBe(1); $response->assertRedirect('/bo/slides'); }); + + it('redirects unauthenticated guest to login', function (): void { + // GIVEN + auth('backend')->logout(); + + // WHEN + $response = get('/bo/slides'); + + // THEN + $response->assertRedirect('/bo/login'); + }); + + it('forbids create and store when policy denies access', function (): void { + // GIVEN + $deniedPolicy = new class () + { + public function create(): bool + { + return false; + } + }; + Gate::policy(Slide::class, $deniedPolicy::class); + + // WHEN + $createResponse = get('/bo/slides/create'); + $storeResponse = post('/bo/slides', [ + 'title' => 'Slide interdit', + 'text' => 'Contenu valide du slide', + 'link_new_tab' => false, + 'connected' => false, + 'client_timezone' => 'Europe/Paris', + ]); + + // THEN + $createResponse->assertForbidden(); + $storeResponse->assertForbidden(); + }); + + it('redirects back with session validation errors on invalid web store payload', function (): void { + // WHEN + $response = from('/bo/slides/create')->post('/bo/slides', [ + 'title' => 'AB', + 'text' => '', + 'client_timezone' => 'Europe/Paris', + ]); + + // THEN + $response->assertRedirect('/bo/slides/create') + ->assertSessionHasErrors(['title', 'text']); + }); + + it('returns 422 JSON validation errors on invalid JSON store payload', function (): void { + // WHEN + $response = postJson('/bo/slides', [ + 'title' => 'AB', + 'text' => '', + 'client_timezone' => 'Europe/Paris', + ]); + + // THEN + $response->assertUnprocessable() + ->assertJsonValidationErrors(['title', 'text']); + }); }); diff --git a/tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php index b39e9e55..f165722e 100644 --- a/tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php @@ -7,8 +7,13 @@ namespace Tests\Feature\App\Http\Controllers\Bo; use App\Models\Tag; use App\Models\User; use Domain\Enums\UserRole; +use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Gate; use function Pest\Laravel\from; +use function Pest\Laravel\get; +use function Pest\Laravel\post; +use function Pest\Laravel\postJson; describe('TagsController', function (): void { beforeEach(function (): void { @@ -133,4 +138,59 @@ describe('TagsController', function (): void { ->and($tag2->order)->toBe(1); $response->assertRedirect('/bo/tags'); }); + + it('redirects unauthenticated guest to login', function (): void { + // GIVEN + Auth::guard('backend')->logout(); + + // WHEN + $response = get('/bo/tags'); + + // THEN + $response->assertRedirect('/bo/login'); + }); + + it('forbids create and store when policy denies access', function (): void { + // GIVEN + $deniedPolicy = new class () + { + public function create(): bool + { + return false; + } + }; + Gate::policy(Tag::class, $deniedPolicy::class); + + // WHEN + $createResponse = get('/bo/tags/create'); + $storeResponse = post('/bo/tags', ['label' => 'Volaille', 'status' => true]); + + // THEN + $createResponse->assertForbidden(); + $storeResponse->assertForbidden(); + }); + + it('redirects back with session validation errors on invalid web store payload', function (): void { + // WHEN + $response = from('/bo/tags/create')->post('/bo/tags', [ + 'label' => 'A', + 'status' => true, + ]); + + // THEN + $response->assertRedirect('/bo/tags/create') + ->assertSessionHasErrors('label'); + }); + + it('returns 422 JSON validation errors on invalid JSON store payload', function (): void { + // WHEN + $response = postJson('/bo/tags', [ + 'label' => 'A', + 'status' => true, + ]); + + // THEN + $response->assertUnprocessable() + ->assertJsonValidationErrors('label'); + }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php index 40f156ab..4f027f96 100644 --- a/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php @@ -5,83 +5,83 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Bo\Products; use App\Http\Requests\Bo\Products\IndexProductRequest; +use Illuminate\Session\ArraySessionHandler; +use Illuminate\Session\Store; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; -use function Pest\Laravel\mock; - -describe('IndexProductRequest', function () { - it('authorizes via auth service', function () { +describe('IndexProductRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new IndexProductRequest($authService); - - // WHEN $request->initialize(); + // WHEN + $authorized = $request->authorize(); + $denied = $request->authorize(); + // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('returns rules', function () { + it('validates filter rules', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new IndexProductRequest($authService); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new IndexProductRequest($authService)->rules(); // WHEN - $request->initialize(); + $invalid = Validator::make(['brand' => 'ab', 'star' => 'not-bool'], $rules); + $valid = Validator::make(['brand' => 'loue', 'star' => true, 'discount' => '0'], $rules); // THEN - expect($request->rules())->toBeArray(); + expect($invalid->errors()->has('brand'))->toBeTrue() + ->and($invalid->errors()->has('star'))->toBeTrue() + ->and($valid->passes())->toBeTrue(); }); - it('returns attributes', function () { + it('resolves discount filter correctly in toGetBoPaginatedProductsQueryInput', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new IndexProductRequest($authService); - - // WHEN - $request->initialize(); - - // THEN - expect($request->attributes())->toBeArray(); - }); - - it('prepares for validation', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new IndexProductRequest($authService); - $request->initialize(); - $method = new \ReflectionMethod($request, 'prepareForValidation'); - $method->setAccessible(true); - - // WHEN - $method->invoke($request); - - // THEN - expect(true)->toBeTrue(); - }); - - it('resolves discount filter correctly in toGetBoPaginatedProductsQueryInput', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new IndexProductRequest($authService); $request->initialize(['discount' => '0']); - // WHEN - $input = $request->toGetBoPaginatedProductsQueryInput(); - - // THEN - expect($input->discount)->toBe('0'); - - // GIVEN $requestWithId = new IndexProductRequest($authService); $requestWithId->initialize(['discount' => '42']); // WHEN + $input = $request->toGetBoPaginatedProductsQueryInput(); $inputWithId = $requestWithId->toGetBoPaginatedProductsQueryInput(); // THEN - expect($inputWithId->discount)->toBe('42'); + expect($input->discount)->toBe('0') + ->and($inputWithId->discount)->toBe('42'); + }); + + it('persists and clears session filters in toGetBoPaginatedProductsQueryInput', function (): void { + // GIVEN + $authService = \Mockery::mock(AppAdminAuthService::class); + $session = new Store('test', new ArraySessionHandler(120)); + + $firstRequest = new IndexProductRequest($authService); + $firstRequest->setLaravelSession($session); + $firstRequest->initialize(['brand' => 'loue', 'star' => '1']); + + // WHEN + $firstInput = $firstRequest->toGetBoPaginatedProductsQueryInput(); + + $followUpRequest = new IndexProductRequest($authService); + $followUpRequest->setLaravelSession($session); + $followUpRequest->initialize(['brand' => '']); + $clearedInput = $followUpRequest->toGetBoPaginatedProductsQueryInput(); + + // THEN + expect($firstInput->brand)->toBe('loue') + ->and($firstInput->starred)->toBeTrue() + ->and($clearedInput->brand)->toBeNull() + ->and($clearedInput->starred)->toBeFalse() + ->and($session->has('products.filter.brand'))->toBeFalse(); }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Products/StoreProductRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Products/StoreProductRequestTest.php index 232d463b..ddb0fa43 100644 --- a/tests/Feature/App/Http/Requests/Bo/Products/StoreProductRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Products/StoreProductRequestTest.php @@ -6,83 +6,35 @@ namespace Tests\Feature\App\Http\Requests\Bo\Products; use App\Http\Requests\Bo\Products\StoreProductRequest; use Domain\Enums\ProductBrand; +use Domain\Enums\SellUnit; +use Domain\Enums\TaxRate; +use Domain\Enums\Units\InvoicingUnit; +use Domain\Enums\Units\OrderUnit; use Illuminate\Http\UploadedFile; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; use Money\Currency; -use function Pest\Laravel\mock; - -describe('StoreProductRequest', function () { - it('authorizes via auth service', function () { +describe('StoreProductRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new StoreProductRequest($authService, new Currency('EUR')); - - // WHEN $request->initialize(); - // THEN - expect($request->authorize())->toBeTrue(); - }); - - it('returns rules', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreProductRequest($authService, new Currency('EUR')); - // WHEN - $request->initialize(); + $authorized = $request->authorize(); + $denied = $request->authorize(); // THEN - expect($request->rules())->toBeArray(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('returns attributes', function () { + it('builds Money price using the injected currency', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreProductRequest($authService, new Currency('EUR')); - - // WHEN - $request->initialize(); - - // THEN - expect($request->attributes())->toBeArray(); - }); - - it('prepares for validation', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreProductRequest($authService, new Currency('EUR')); - $request->initialize(); - $method = new \ReflectionMethod($request, 'prepareForValidation'); - $method->setAccessible(true); - - // WHEN - $method->invoke($request); - - // THEN - expect(true)->toBeTrue(); // just making sure it runs without exception - }); - - it('passes validation', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreProductRequest($authService, new Currency('EUR')); - $request->initialize(); - $method = new \ReflectionMethod($request, 'passedValidation'); - $method->setAccessible(true); - - // WHEN - $method->invoke($request); - - // THEN - expect(true)->toBeTrue(); - }); - - it('builds Money price using the injected currency', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new StoreProductRequest($authService, new Currency('USD')); $request->initialize(); $request->merge(['price' => 1250]); @@ -95,11 +47,10 @@ describe('StoreProductRequest', function () { ->and($price->getCurrency()->getCode())->toBe('USD'); }); - it('rejects product pictures when extension and mime type do not match or are disallowed', function () { + it('rejects product pictures when extension and mime type do not match or are disallowed', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreProductRequest($authService, new Currency('EUR')); - $rules = $request->rules(); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new StoreProductRequest($authService, new Currency('EUR'))->rules(); $pngSmall = UploadedFile::fake()->image('small.png', StoreProductRequest::PICTURE_WIDTH, StoreProductRequest::PICTURE_HEIGHT); $mismatchedSmall = new UploadedFile( path: $pngSmall->getRealPath(), @@ -115,25 +66,36 @@ describe('StoreProductRequest', function () { ); // WHEN - $smallValidator = validator(['picture' => $mismatchedSmall], ['picture' => $rules['picture']]); - $largeValidator = validator(['picture_large' => $disallowedLarge], ['picture_large' => $rules['picture_large']]); + $smallValidator = Validator::make(['picture' => $mismatchedSmall], ['picture' => $rules['picture']]); + $largeValidator = Validator::make(['picture_large' => $disallowedLarge], ['picture_large' => $rules['picture_large']]); // THEN expect($smallValidator->errors()->has('picture'))->toBeTrue() ->and($largeValidator->errors()->has('picture_large'))->toBeTrue(); }); - it('requires a valid ProductBrand enum value for brand and validates picture alt/title lengths', function () { + it('requires a valid ProductBrand enum value and validates picture alt/title lengths and orderable dates', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreProductRequest($authService, new Currency('EUR')); - $rules = $request->rules(); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new StoreProductRequest($authService, new Currency('EUR'))->rules(); // WHEN - $invalidBrandValidator = validator(['brand' => 'unknown-brand'], ['brand' => $rules['brand']]); - $nullBrandValidator = validator(['brand' => null], ['brand' => $rules['brand']]); - $validBrandValidator = validator(['brand' => ProductBrand::loue->value], ['brand' => $rules['brand']]); - $tooLongAltValidator = validator([ + $invalidBrandValidator = Validator::make(['brand' => 'unknown-brand'], ['brand' => $rules['brand']]); + $nullBrandValidator = Validator::make(['brand' => null], ['brand' => $rules['brand']]); + $validBrandValidator = Validator::make(['brand' => ProductBrand::loue->value], ['brand' => $rules['brand']]); + $invalidDateValidator = Validator::make( + [ + 'orderable_start' => '2026-06-15T18:00', + 'orderable_end' => '2026-06-15T10:00', + 'range_id' => 999999, + ], + [ + 'orderable_start' => $rules['orderable_start'], + 'orderable_end' => $rules['orderable_end'], + 'range_id' => $rules['range_id'], + ], + ); + $tooLongAltValidator = Validator::make([ 'picture_alt' => str_repeat('a', 256), 'picture_title' => str_repeat('b', 256), 'picture_large_alt' => str_repeat('c', 256), @@ -149,9 +111,57 @@ describe('StoreProductRequest', function () { expect($invalidBrandValidator->fails())->toBeTrue() ->and($nullBrandValidator->fails())->toBeTrue() ->and($validBrandValidator->passes())->toBeTrue() + ->and($invalidDateValidator->errors()->has('orderable_end'))->toBeTrue() + ->and($invalidDateValidator->errors()->has('range_id'))->toBeTrue() ->and($tooLongAltValidator->errors()->has('picture_alt'))->toBeTrue() ->and($tooLongAltValidator->errors()->has('picture_title'))->toBeTrue() ->and($tooLongAltValidator->errors()->has('picture_large_alt'))->toBeTrue() ->and($tooLongAltValidator->errors()->has('picture_large_title'))->toBeTrue(); }); + + it('maps request data into CreateProductInput and filters non-scalar associated products', function (): void { + // GIVEN + $authService = \Mockery::mock(AppAdminAuthService::class); + $request = new StoreProductRequest($authService, new Currency('EUR')); + $request->initialize( + request: [ + 'name' => 'Poulet Fermier', + 'short_description' => 'Poulet élevé en plein air', + 'description' => 'Description complète du poulet fermier de Loué.', + 'price' => 1490, + 'invoicing_unit' => InvoicingUnit::PCE->value, + 'stock' => 15, + 'range_id' => 3, + 'sell_unit' => SellUnit::PCE->value, + 'order_unit' => OrderUnit::PCE->value, + 'tax_rate' => TaxRate::TVA_5_5->value, + 'brand' => ProductBrand::loue->value, + 'weight' => 1500, + 'weight_variable' => '1', + 'star' => '0', + 'status' => '1', + 'tags' => [['id' => 7, 'label' => 'Label Rouge']], + 'associated_products' => ['uuid-1', 42, ['nested'], null], + ], + server: ['REQUEST_METHOD' => 'POST'], + ); + + // WHEN + $input = $request->toCreateProductInput(); + + // THEN + expect($input->name)->toBe('Poulet Fermier') + ->and($input->price->getAmount())->toBe('1490') + ->and($input->invoicingUnit)->toBe(InvoicingUnit::PCE) + ->and($input->sellUnit)->toBe(SellUnit::PCE) + ->and($input->orderUnit)->toBe(OrderUnit::PCE) + ->and($input->taxRate)->toBe(TaxRate::TVA_5_5) + ->and($input->brand)->toBe(ProductBrand::loue) + ->and($input->weight)->toBe(1500) + ->and($input->weightVariable)->toBeTrue() + ->and($input->star)->toBeFalse() + ->and($input->status)->toBeTrue() + ->and($input->tags)->toBe([['id' => '7', 'label' => 'Label Rouge']]) + ->and($input->associatedProductsIds)->toBe(['uuid-1', '42']); + }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Ranges/StoreRangeRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Ranges/StoreRangeRequestTest.php index a7631084..c6c04790 100644 --- a/tests/Feature/App/Http/Requests/Bo/Ranges/StoreRangeRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Ranges/StoreRangeRequestTest.php @@ -6,68 +6,57 @@ namespace Tests\Feature\App\Http\Requests\Bo\Ranges; use App\Http\Requests\Bo\Ranges\StoreRangeRequest; use Illuminate\Http\UploadedFile; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; -use function Pest\Laravel\mock; - -describe('StoreRangeRequest', function () { - it('authorizes via auth service', function () { +describe('StoreRangeRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new StoreRangeRequest($authService); - - // WHEN $request->initialize(); + // WHEN + $authorized = $request->authorize(); + $denied = $request->authorize(); + // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('returns rules', function () { + it('validates name length constraints and requires picture metadata when picture is provided', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreRangeRequest($authService); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new StoreRangeRequest($authService)->rules(); + $picture = UploadedFile::fake()->image('range.jpg', StoreRangeRequest::PICTURE_WIDTH, StoreRangeRequest::PICTURE_HEIGHT); // WHEN - $request->initialize(); + $invalid = Validator::make([ + 'name' => 'A', + 'picture' => $picture, + 'status' => true, + ], $rules); + $valid = Validator::make([ + 'name' => 'Volailles Fermières', + 'picture' => $picture, + 'picture_alt' => 'Volailles fermières alt', + 'picture_title' => 'Volailles fermières titre', + 'status' => true, + ], $rules); // THEN - expect($request->rules())->toBeArray(); + expect($invalid->errors()->has('name'))->toBeTrue() + ->and($invalid->errors()->has('picture_alt'))->toBeTrue() + ->and($invalid->errors()->has('picture_title'))->toBeTrue() + ->and($valid->passes())->toBeTrue(); }); - it('returns attributes', function () { + it('rejects a range image when extension and mime type do not match or are disallowed', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreRangeRequest($authService); - - // WHEN - $request->initialize(); - - // THEN - expect($request->attributes())->toBeArray(); - }); - - it('prepares for validation', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreRangeRequest($authService); - $request->initialize(); - $method = new \ReflectionMethod($request, 'prepareForValidation'); - $method->setAccessible(true); - - // WHEN - $method->invoke($request); - - // THEN - expect(true)->toBeTrue(); // just making sure it runs without exception - }); - - it('rejects a range image when extension and mime type do not match or are disallowed', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreRangeRequest($authService); - $rules = $request->rules(); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new StoreRangeRequest($authService)->rules(); $pngSource = UploadedFile::fake()->image('cropped.png', StoreRangeRequest::PICTURE_WIDTH, StoreRangeRequest::PICTURE_HEIGHT); $mismatched = new UploadedFile( path: $pngSource->getRealPath(), @@ -79,11 +68,37 @@ describe('StoreRangeRequest', function () { $disallowedWebp = UploadedFile::fake()->image('range.webp', StoreRangeRequest::PICTURE_WIDTH, StoreRangeRequest::PICTURE_HEIGHT); // WHEN - $mismatchValidator = validator(['picture' => $mismatched], ['picture' => $rules['picture']]); - $webpValidator = validator(['picture' => $disallowedWebp], ['picture' => $rules['picture']]); + $mismatchValidator = Validator::make(['picture' => $mismatched], ['picture' => $rules['picture']]); + $webpValidator = Validator::make(['picture' => $disallowedWebp], ['picture' => $rules['picture']]); // THEN expect($mismatchValidator->errors()->has('picture'))->toBeTrue() ->and($webpValidator->errors()->has('picture'))->toBeTrue(); }); + + it('maps request data into CreateRangeInput with PictureMetadata', function (): void { + // GIVEN + $authService = \Mockery::mock(AppAdminAuthService::class); + $request = new StoreRangeRequest($authService); + $request->initialize( + request: [ + 'name' => 'Rôtisserie', + 'description' => 'Nos produits rôtis', + 'picture_alt' => 'Alt gamme', + 'picture_title' => 'Titre gamme', + 'status' => '1', + ], + server: ['REQUEST_METHOD' => 'POST'], + ); + + // WHEN + $input = $request->toCreateRangeInput(); + + // THEN + expect($input->name)->toBe('Rôtisserie') + ->and($input->description)->toBe('Nos produits rôtis') + ->and($input->pictureMetadata->alt)->toBe('Alt gamme') + ->and($input->pictureMetadata->title)->toBe('Titre gamme') + ->and($input->status)->toBeTrue(); + }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Slides/StoreSlideRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Slides/StoreSlideRequestTest.php index f293e8f1..c821435e 100644 --- a/tests/Feature/App/Http/Requests/Bo/Slides/StoreSlideRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Slides/StoreSlideRequestTest.php @@ -5,102 +5,83 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Bo\Slides; use App\Http\Requests\Bo\Slides\StoreSlideRequest; +use App\Models\Slide; +use App\Models\User; +use Domain\Enums\UserRole; use Illuminate\Http\UploadedFile; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; -use function Pest\Laravel\mock; +use function Pest\Laravel\actingAs; +use function Pest\Laravel\post; -describe('StoreSlideRequest', function () { - it('authorizes via auth service', function () { +describe('StoreSlideRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new StoreSlideRequest($authService); - - // WHEN $request->initialize(); - // THEN - expect($request->authorize())->toBeTrue(); - }); - - it('returns rules', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreSlideRequest($authService); - // WHEN - $request->initialize(); + $authorized = $request->authorize(); + $denied = $request->authorize(); // THEN - expect($request->rules())->toBeArray(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('returns attributes', function () { + it('normalizes empty HTML text to null during HTTP submission when no picture is sent', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreSlideRequest($authService); + $admin = User::factory()->createOne(['role' => UserRole::SuperAdmin]); + actingAs($admin, 'backend'); // WHEN - $request->initialize(); + $response = post(route('bo.slides.store'), [ + 'title' => 'Slide sans image', + 'text' => '


', + 'link_new_tab' => false, + 'connected' => false, + 'client_timezone' => 'Europe/Paris', + ]); // THEN - expect($request->attributes())->toBeArray(); + $response->assertRedirect() + ->assertSessionHasErrors('text'); + expect(Slide::query()->where('title', 'Slide sans image')->exists())->toBeFalse(); }); - it('prepares for validation', function () { + it('converts local date_start and date_end to UTC via passedValidation on store', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreSlideRequest($authService); - $request->initialize(); - $method = new \ReflectionMethod($request, 'prepareForValidation'); - $method->setAccessible(true); + $admin = User::factory()->createOne(['role' => UserRole::SuperAdmin]); + actingAs($admin, 'backend'); // WHEN - $method->invoke($request); + $response = post(route('bo.slides.store'), [ + 'title' => 'Slide UTC Convert', + 'text' => 'Texte de présentation du slide', + 'link_new_tab' => false, + 'connected' => false, + 'date_start' => '2026-06-15T10:00', + 'date_end' => '2026-06-15T18:30', + 'client_timezone' => 'Europe/Paris', + ]); // THEN - expect(true)->toBeTrue(); // just making sure it runs without exception + $slide = Slide::query()->where('title', 'Slide UTC Convert')->firstOrFail(); + $response->assertRedirect(route('bo.slides.edit', $slide)); + expect($slide->date_start?->format('Y-m-d H:i'))->toBe('2026-06-15 08:00') + ->and($slide->date_end?->format('Y-m-d H:i'))->toBe('2026-06-15 16:30'); }); - it('passes validation', function () { + it('allows empty text when picture is present', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreSlideRequest($authService); - $request->initialize(); - $method = new \ReflectionMethod($request, 'passedValidation'); - $method->setAccessible(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new StoreSlideRequest($authService)->rules(); // WHEN - $method->invoke($request); - - // THEN - expect(true)->toBeTrue(); - }); - - it('normalizes empty text to null in prepareForValidation', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreSlideRequest($authService); - $request->initialize(request: ['text' => '


']); - $method = new \ReflectionMethod($request, 'prepareForValidation'); - $method->setAccessible(true); - - // WHEN - $method->invoke($request); - - // THEN - expect($request->input('text'))->toBeNull(); - }); - - it('allows empty text when picture is present', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreSlideRequest($authService); - $rules = $request->rules(); - - // WHEN - $validator = validator( + $validator = Validator::make( [ 'title' => 'Slide Title', 'picture' => 'some/picture.jpg', @@ -111,24 +92,23 @@ describe('StoreSlideRequest', function () { 'connected' => false, 'client_timezone' => 'Europe/Paris', ], - $rules + $rules, ); // THEN expect($validator->errors()->has('text'))->toBeFalse(); }); - it('accepts a 3MB slide image matching required dimensions', function () { + it('accepts a 3MB slide image matching required dimensions', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreSlideRequest($authService); - $rules = $request->rules(); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new StoreSlideRequest($authService)->rules(); $picture = UploadedFile::fake() ->image('slide.jpg', StoreSlideRequest::PICTURE_WIDTH, StoreSlideRequest::PICTURE_HEIGHT) ->size(3072); // WHEN - $validator = validator( + $validator = Validator::make( [ 'title' => 'Slide Title', 'picture' => $picture, @@ -139,18 +119,17 @@ describe('StoreSlideRequest', function () { 'connected' => false, 'client_timezone' => 'Europe/Paris', ], - $rules + $rules, ); // THEN expect($validator->fails())->toBeFalse(); }); - it('rejects a slide image when extension and mime type do not match or are disallowed', function () { + it('rejects a slide image when extension and mime type do not match or are disallowed', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreSlideRequest($authService); - $rules = $request->rules(); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new StoreSlideRequest($authService)->rules(); $pngSource = UploadedFile::fake()->image('cropped.png', StoreSlideRequest::PICTURE_WIDTH, StoreSlideRequest::PICTURE_HEIGHT); $mismatched = new UploadedFile( path: $pngSource->getRealPath(), @@ -162,7 +141,7 @@ describe('StoreSlideRequest', function () { $disallowedWebp = UploadedFile::fake()->image('slide.webp', StoreSlideRequest::PICTURE_WIDTH, StoreSlideRequest::PICTURE_HEIGHT); // WHEN - $mismatchValidator = validator( + $mismatchValidator = Validator::make( [ 'title' => 'Slide Title', 'picture' => $mismatched, @@ -173,9 +152,9 @@ describe('StoreSlideRequest', function () { 'connected' => false, 'client_timezone' => 'Europe/Paris', ], - $rules + $rules, ); - $webpValidator = validator( + $webpValidator = Validator::make( [ 'title' => 'Slide Title', 'picture' => $disallowedWebp, @@ -186,11 +165,72 @@ describe('StoreSlideRequest', function () { 'connected' => false, 'client_timezone' => 'Europe/Paris', ], - $rules + $rules, ); // THEN expect($mismatchValidator->errors()->has('picture'))->toBeTrue() ->and($webpValidator->errors()->has('picture'))->toBeTrue(); }); + + it('rejects non-https link and date_end before date_start', function (): void { + // GIVEN + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new StoreSlideRequest($authService)->rules(); + + // WHEN + $validator = Validator::make( + [ + 'title' => 'Slide Title', + 'text' => 'Valid text content', + 'link' => 'http://insecure.example.com', + 'link_new_tab' => false, + 'connected' => false, + 'date_start' => '2026-06-15T18:00', + 'date_end' => '2026-06-15T10:00', + 'client_timezone' => 'Europe/Paris', + ], + $rules, + ); + + // THEN + expect($validator->errors()->has('link'))->toBeTrue() + ->and($validator->errors()->has('date_end'))->toBeTrue(); + }); + + it('maps request data into CreateSlideInput', function (): void { + // GIVEN + $authService = \Mockery::mock(AppAdminAuthService::class); + $request = new StoreSlideRequest($authService); + $request->initialize( + request: [ + 'title' => 'Promo Noël', + 'text' => 'Texte promotionnel', + 'link' => 'https://example.com/noel', + 'link_label' => 'Découvrir', + 'link_new_tab' => '1', + 'connected' => '0', + 'picture_alt' => 'Image Noël', + 'picture_title' => 'Bannière Noël', + 'date_start' => '2026-12-01 08:00:00', + 'date_end' => '2026-12-25 18:00:00', + ], + server: ['REQUEST_METHOD' => 'POST'], + ); + + // WHEN + $input = $request->toCreateSlideInput(); + + // THEN + expect($input->title)->toBe('Promo Noël') + ->and($input->text)->toBe('Texte promotionnel') + ->and($input->link)->toBe('https://example.com/noel') + ->and($input->linkLabel)->toBe('Découvrir') + ->and($input->linkNewTab)->toBeTrue() + ->and($input->connected)->toBeFalse() + ->and($input->pictureAlt)->toBe('Image Noël') + ->and($input->pictureTitle)->toBe('Bannière Noël') + ->and($input->period->start?->format('Y-m-d H:i'))->toBe('2026-12-01 08:00') + ->and($input->period->end?->format('Y-m-d H:i'))->toBe('2026-12-25 18:00'); + }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Tags/StoreTagRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Tags/StoreTagRequestTest.php index 2b633a20..8bdb9a37 100644 --- a/tests/Feature/App/Http/Requests/Bo/Tags/StoreTagRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Tags/StoreTagRequestTest.php @@ -5,60 +5,61 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Bo\Tags; use App\Http\Requests\Bo\Tags\StoreTagRequest; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; -use function Pest\Laravel\mock; - -describe('StoreTagRequest', function () { - it('authorizes via auth service', function () { +describe('StoreTagRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new StoreTagRequest($authService); - - // WHEN $request->initialize(); + // WHEN + $authorized = $request->authorize(); + $denied = $request->authorize(); + // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('returns rules', function () { + it('validates label length constraints and strict boolean status', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreTagRequest($authService); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new StoreTagRequest($authService)->rules(); // WHEN - $request->initialize(); + $tooShort = Validator::make(['label' => 'A', 'status' => true], $rules); + $tooLong = Validator::make(['label' => str_repeat('a', 46), 'status' => true], $rules); + $nonBool = Validator::make(['label' => 'Volaille', 'status' => 'invalid'], $rules); + $valid = Validator::make(['label' => 'Volaille', 'status' => true], $rules); // THEN - expect($request->rules())->toBeArray(); + expect($tooShort->errors()->has('label'))->toBeTrue() + ->and($tooLong->errors()->has('label'))->toBeTrue() + ->and($nonBool->errors()->has('status'))->toBeTrue() + ->and($valid->passes())->toBeTrue(); }); - it('returns attributes', function () { + it('maps request data into CreateTagInput', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new StoreTagRequest($authService); + $request->initialize( + request: [ + 'label' => 'Promotion', + 'status' => '1', + ], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN - $request->initialize(); + $input = $request->toCreateTagInput(); // THEN - expect($request->attributes())->toBeArray(); - }); - - it('prepares for validation', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreTagRequest($authService); - $request->initialize(); - $method = new \ReflectionMethod($request, 'prepareForValidation'); - $method->setAccessible(true); - - // WHEN - $method->invoke($request); - - // THEN - expect(true)->toBeTrue(); + expect($input->label)->toBe('Promotion') + ->and($input->status)->toBeTrue(); }); }); From 6f81d946484a731596553e52fa39b736da466326 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 15:23:40 +0100 Subject: [PATCH 140/183] test(requests): overhaul Basket and remaining BO request tests with controller failure checks --- .../Bo/DiscountsControllerTest.php | 57 ++++ .../Controllers/Bo/FaqsControllerTest.php | 64 +++++ .../Controllers/Bo/PageControllerTest.php | 66 +++++ .../Bo/PickupExceptionsControllerTest.php | 64 +++++ .../Controllers/Bo/ShopsControllerTest.php | 66 +++++ .../Requests/Basket/AddBasketRequestTest.php | 16 +- .../Basket/RemoveBasketRequestTest.php | 4 +- .../Bo/Dashboard/DashboardRequestTest.php | 84 +++--- .../Bo/Discounts/StoreDiscountRequestTest.php | 257 ++++++++---------- .../Requests/Bo/Faqs/StoreFaqRequestTest.php | 128 +++------ .../Requests/Bo/MassActionRequestTest.php | 87 ++---- .../Bo/Orders/IndexOrdersRequestTest.php | 220 ++++++--------- .../Bo/Pages/UpdatePageRequestTest.php | 66 +++-- .../StorePickupExceptionRequestTest.php | 142 +++++----- .../Bo/Shops/IndexShopRequestTest.php | 153 ++++------- .../Bo/Shops/StoreShopRequestTest.php | 130 +++++---- .../UpdateShopPickupExceptionsRequestTest.php | 108 +++----- 17 files changed, 899 insertions(+), 813 deletions(-) diff --git a/tests/Feature/App/Http/Controllers/Bo/DiscountsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/DiscountsControllerTest.php index 57b22010..cfbf5039 100644 --- a/tests/Feature/App/Http/Controllers/Bo/DiscountsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/DiscountsControllerTest.php @@ -17,8 +17,14 @@ use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; use Domain\Enums\UserRole; use Domain\Models\ValueObjects\DiscountValue; +use Illuminate\Support\Facades\Gate; use Money\Money; +use function Pest\Laravel\from; +use function Pest\Laravel\get; +use function Pest\Laravel\post; +use function Pest\Laravel\postJson; + describe('DiscountsController', function (): void { beforeEach(function (): void { /** @var \Tests\TestCase $this */ @@ -221,5 +227,56 @@ describe('DiscountsController', function (): void { // THEN $response->assertRedirect('/bo/login'); }); + + it('forbids create and store when policy denies access', function (): void { + // GIVEN + $deniedPolicy = new class () + { + public function create(): bool + { + return false; + } + }; + Gate::policy(Discount::class, $deniedPolicy::class); + + // WHEN + $createResponse = get('/bo/discounts/create'); + $storeResponse = post('/bo/discounts', [ + 'type' => DiscountType::PERCENT->value, + 'value' => 10, + 'is_old_price_displayed' => true, + 'client_timezone' => 'Europe/Paris', + ]); + + // THEN + $createResponse->assertForbidden(); + $storeResponse->assertForbidden(); + }); + }); + + it('redirects back with session validation errors on invalid web store payload', function (): void { + // WHEN + $response = from('/bo/discounts/create')->post('/bo/discounts', [ + 'type' => DiscountType::PERCENT->value, + 'value' => 150, + 'client_timezone' => 'Europe/Paris', + ]); + + // THEN + $response->assertRedirect('/bo/discounts/create') + ->assertSessionHasErrors('value'); + }); + + it('returns 422 JSON validation errors on invalid JSON store payload', function (): void { + // WHEN + $response = postJson('/bo/discounts', [ + 'type' => DiscountType::PERCENT->value, + 'value' => 150, + 'client_timezone' => 'Europe/Paris', + ]); + + // THEN + $response->assertUnprocessable() + ->assertJsonValidationErrors('value'); }); }); diff --git a/tests/Feature/App/Http/Controllers/Bo/FaqsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/FaqsControllerTest.php index d4be13ac..c784d470 100644 --- a/tests/Feature/App/Http/Controllers/Bo/FaqsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/FaqsControllerTest.php @@ -7,6 +7,12 @@ namespace Tests\Feature\App\Http\Controllers\Bo; use App\Models\Faq; use App\Models\User; use Domain\Enums\UserRole; +use Illuminate\Support\Facades\Gate; + +use function Pest\Laravel\from; +use function Pest\Laravel\get; +use function Pest\Laravel\post; +use function Pest\Laravel\postJson; describe('FaqsController', function (): void { beforeEach(function (): void { @@ -125,4 +131,62 @@ describe('FaqsController', function (): void { // THEN expect($response->status())->toBe(302); }); + + it('redirects unauthenticated guest to login', function (): void { + // GIVEN + auth('backend')->logout(); + + // WHEN + $response = get('/bo/faqs'); + + // THEN + $response->assertRedirect('/bo/login'); + }); + + it('forbids create and store when policy denies access', function (): void { + // GIVEN + $deniedPolicy = new class () + { + public function create(): bool + { + return false; + } + }; + Gate::policy(Faq::class, $deniedPolicy::class); + + // WHEN + $createResponse = get('/bo/faqs/create'); + $storeResponse = post('/bo/faqs', [ + 'question' => 'Question autorisée ?', + 'answer' => 'Réponse autorisée.', + ]); + + // THEN + $createResponse->assertForbidden(); + $storeResponse->assertForbidden(); + }); + + it('redirects back with session validation errors on invalid web store payload', function (): void { + // WHEN + $response = from('/bo/faqs/create')->post('/bo/faqs', [ + 'question' => 'abc', + 'answer' => 'abc', + ]); + + // THEN + $response->assertRedirect('/bo/faqs/create') + ->assertSessionHasErrors(['question', 'answer']); + }); + + it('returns 422 JSON validation errors on invalid JSON store payload', function (): void { + // WHEN + $response = postJson('/bo/faqs', [ + 'question' => 'abc', + 'answer' => 'abc', + ]); + + // THEN + $response->assertUnprocessable() + ->assertJsonValidationErrors(['question', 'answer']); + }); }); diff --git a/tests/Feature/App/Http/Controllers/Bo/PageControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/PageControllerTest.php index e39612c7..9fc0e33b 100644 --- a/tests/Feature/App/Http/Controllers/Bo/PageControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/PageControllerTest.php @@ -9,6 +9,10 @@ use App\Models\Page; use App\Models\User; use Domain\Enums\StaticPageSlug; use Domain\Enums\UserRole; +use Illuminate\Support\Facades\Gate; + +use function Pest\Laravel\get; +use function Pest\Laravel\putJson; describe('Bo\PageController', function (): void { beforeEach(function (): void { @@ -86,4 +90,66 @@ describe('Bo\PageController', function (): void { // THEN $response->assertSessionHasErrors(['seo_title', 'seo_description', 'content']); }); + + it('redirects unauthenticated guest to login', function (): void { + // GIVEN + $page = new Page(); + $page->slug = StaticPageSlug::TERMS; + $page->seo_title = 'Titre SEO pour un accès invité non authentifié'; + $page->seo_description = 'Description SEO suffisamment longue pour le test invité.'; + $page->title = 'CGV'; + $page->content = '

Contenu

'; + $page->saveOrFail(); + auth('backend')->logout(); + + // WHEN + $response = get('/bo/pages/cgv/edit'); + + // THEN + $response->assertRedirect('/bo/login'); + }); + + it('forbids update when policy denies access', function (): void { + // GIVEN + $page = new Page(); + $page->slug = StaticPageSlug::TERMS; + $page->seo_title = 'Titre SEO pour un test de politique refusée sur page'; + $page->seo_description = 'Description SEO suffisamment longue pour le test politique.'; + $page->title = 'CGV'; + $page->content = '

Contenu

'; + $page->saveOrFail(); + + $deniedPolicy = new class () + { + public function update(): bool + { + return false; + } + }; + Gate::policy(Page::class, $deniedPolicy::class); + + // WHEN + $response = get('/bo/pages/cgv/edit'); + + // THEN + $response->assertForbidden(); + }); + + it('returns 422 JSON validation errors on invalid JSON update payload', function (): void { + // GIVEN + $page = new Page(); + $page->slug = StaticPageSlug::PRIVACY; + $page->seo_title = 'Politique de Confidentialité Titre SEO pour la validation'; + $page->seo_description = 'Politique de Confidentialité Description SEO pour la validation requise'; + $page->title = 'Confidentialité'; + $page->content = '

Contenu

'; + $page->saveOrFail(); + + // WHEN + $response = putJson('/bo/pages/confidentialite', []); + + // THEN + $response->assertUnprocessable() + ->assertJsonValidationErrors(['seo_title', 'seo_description', 'content']); + }); }); diff --git a/tests/Feature/App/Http/Controllers/Bo/PickupExceptionsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/PickupExceptionsControllerTest.php index 103664b0..cf77ddc2 100644 --- a/tests/Feature/App/Http/Controllers/Bo/PickupExceptionsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/PickupExceptionsControllerTest.php @@ -11,7 +11,10 @@ use Domain\Enums\RepeatFrequency; use Domain\Enums\UserRole; use Illuminate\Support\Facades\Gate; +use function Pest\Laravel\from; use function Pest\Laravel\get; +use function Pest\Laravel\post; +use function Pest\Laravel\postJson; describe('PickupExceptionsController', function () { beforeEach(function () { @@ -155,4 +158,65 @@ describe('PickupExceptionsController', function () { $responseWhenPickupExceptionCreateDenied->assertOk(); $responseWhenPickupExceptionCreateDenied->assertDontSee(route('bo.pickup-exceptions.create')); }); + + it('redirects unauthenticated guest to login', function (): void { + // GIVEN + auth('backend')->logout(); + + // WHEN + $response = get('/bo/pickup-exceptions'); + + // THEN + $response->assertRedirect('/bo/login'); + }); + + it('forbids create and store when policy denies access', function (): void { + // GIVEN + $deniedPolicy = new class () + { + public function create(): bool + { + return false; + } + }; + Gate::policy(PickupException::class, $deniedPolicy::class); + + // WHEN + $createResponse = get('/bo/pickup-exceptions/create'); + $storeResponse = post('/bo/pickup-exceptions', [ + 'date' => '2026-12-25', + 'label' => 'Noël', + 'repeatable' => false, + ]); + + // THEN + $createResponse->assertForbidden(); + $storeResponse->assertForbidden(); + }); + + it('redirects back with session validation errors on invalid web store payload', function (): void { + // WHEN + $response = from('/bo/pickup-exceptions/create')->post('/bo/pickup-exceptions', [ + 'date' => 'not-a-date', + 'label' => '', + 'repeatable' => true, + ]); + + // THEN + $response->assertRedirect('/bo/pickup-exceptions/create') + ->assertSessionHasErrors(['date', 'label', 'repeat_frequency']); + }); + + it('returns 422 JSON validation errors on invalid JSON store payload', function (): void { + // WHEN + $response = postJson('/bo/pickup-exceptions', [ + 'date' => 'not-a-date', + 'label' => '', + 'repeatable' => true, + ]); + + // THEN + $response->assertUnprocessable() + ->assertJsonValidationErrors(['date', 'label', 'repeat_frequency']); + }); }); diff --git a/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php index f5f26a89..7a96d708 100644 --- a/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php @@ -9,6 +9,12 @@ use App\Models\PickupException; use App\Models\Shop; use App\Models\User; use Domain\Enums\UserRole; +use Illuminate\Support\Facades\Gate; + +use function Pest\Laravel\from; +use function Pest\Laravel\get; +use function Pest\Laravel\post; +use function Pest\Laravel\postJson; describe('ShopsController', function () { @@ -206,4 +212,64 @@ describe('ShopsController', function () { 'replacement_date' => null, ]); }); + + it('redirects unauthenticated guest to login', function (): void { + // GIVEN + auth('backend')->logout(); + + // WHEN + $response = get('/bo/shops'); + + // THEN + $response->assertRedirect('/bo/login'); + }); + + it('forbids create and store when policy denies access', function (): void { + // GIVEN + $deniedPolicy = new class () + { + public function create(): bool + { + return false; + } + }; + Gate::policy(Shop::class, $deniedPolicy::class); + + // WHEN + $createResponse = get('/bo/shops/create'); + $storeResponse = post('/bo/shops', [ + 'name' => 'Boutique Test', + 'address' => '1 rue Test', + 'postcode' => '75001', + 'city' => 'Paris', + ]); + + // THEN + $createResponse->assertForbidden(); + $storeResponse->assertForbidden(); + }); + + it('redirects back with session validation errors on invalid web store payload', function (): void { + // WHEN + $response = from('/bo/shops/create')->post('/bo/shops', [ + 'name' => '', + 'postcode' => 'INVALID', + ]); + + // THEN + $response->assertRedirect('/bo/shops/create') + ->assertSessionHasErrors(['name', 'address', 'postcode', 'city']); + }); + + it('returns 422 JSON validation errors on invalid JSON store payload', function (): void { + // WHEN + $response = postJson('/bo/shops', [ + 'name' => '', + 'postcode' => 'INVALID', + ]); + + // THEN + $response->assertUnprocessable() + ->assertJsonValidationErrors(['name', 'address', 'postcode', 'city']); + }); }); diff --git a/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php b/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php index 6a11b545..3410854e 100644 --- a/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php +++ b/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Basket; use App\Cqs\Queries\Products\GetProductWithPricingQuery; +use App\Dto\ProductWithPricingDto; use App\Http\Requests\Basket\AddBasketRequest; use App\Models\Product; use App\Models\Range; @@ -14,8 +15,6 @@ use Domain\Enums\ProductBrand; use Domain\Enums\SellUnit; use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; -use Domain\Models\ValueObjects\Entities\ProductId; -use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; @@ -31,7 +30,7 @@ function makeAddBasketRequest(): AddBasketRequest $executor = new ActionExecutorService( lock: \Mockery::mock(Lock::class), logger: new NullLogger(), - eventDispatcher: new LaravelDomainEventDispatcher(\Mockery::mock(Dispatcher::class)), + eventDispatcher: new LaravelDomainEventDispatcher(), ); $query = new GetProductWithPricingQuery( new ProductDtoAssemblerService(new EloquentProductRepository()), @@ -44,7 +43,7 @@ describe('AddBasketRequest', function () { it('authorizes when product exists and gate allows', function () { // GIVEN $range = Range::query()->first() ?? Range::query()->forceCreate(['name' => 'Test', 'slug' => 'test', 'order' => 1, 'picture_alt' => '', 'picture_title' => '']); - $product = Product::forceCreate([ + $product = Product::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'name' => 'Test', 'slug' => Uuid::uuid7()->toString(), @@ -66,7 +65,7 @@ describe('AddBasketRequest', function () { ]); Gate::shouldReceive('allows') - ->with('addToBasket', \Mockery::on(fn ($p) => $p->product->id === $product->id)) + ->with('addToBasket', \Mockery::on(fn (mixed $p): bool => $p instanceof ProductWithPricingDto && $p->product->id === $product->id)) ->andReturn(true); $request = makeAddBasketRequest(); @@ -94,7 +93,7 @@ describe('AddBasketRequest', function () { it('does not authorize when gate denies', function () { // GIVEN $range = Range::query()->first() ?? Range::query()->forceCreate(['name' => 'Test', 'slug' => 'test', 'order' => 1, 'picture_alt' => '', 'picture_title' => '']); - $product = Product::forceCreate([ + $product = Product::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'name' => 'Test', 'slug' => Uuid::uuid7()->toString(), @@ -132,7 +131,7 @@ describe('AddBasketRequest', function () { it('validates correct rules', function () { // GIVEN $range = Range::query()->first() ?? Range::query()->forceCreate(['name' => 'Test', 'slug' => 'test', 'order' => 1, 'picture_alt' => '', 'picture_title' => '']); - $product = Product::forceCreate([ + $product = Product::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'name' => 'Test', 'slug' => Uuid::uuid7()->toString(), @@ -195,7 +194,6 @@ describe('AddBasketRequest', function () { $productId = $request->getProductId(); // THEN - expect($productId)->toBeInstanceOf(ProductId::class) - ->and($productId->value->toString())->toBe($uuid); + expect($productId->value->toString())->toBe($uuid); }); }); diff --git a/tests/Feature/App/Http/Requests/Basket/RemoveBasketRequestTest.php b/tests/Feature/App/Http/Requests/Basket/RemoveBasketRequestTest.php index 8c62d6c9..269bca07 100644 --- a/tests/Feature/App/Http/Requests/Basket/RemoveBasketRequestTest.php +++ b/tests/Feature/App/Http/Requests/Basket/RemoveBasketRequestTest.php @@ -5,7 +5,6 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Basket; use App\Http\Requests\Basket\RemoveBasketRequest; -use Domain\Models\ValueObjects\Entities\ProductId; use Illuminate\Support\Facades\Validator; use Ramsey\Uuid\Uuid; @@ -65,7 +64,6 @@ describe('RemoveBasketRequest', function () { $productId = $request->getProductId(); // THEN - expect($productId)->toBeInstanceOf(ProductId::class) - ->and($productId->value->toString())->toBe($uuid); + expect($productId->value->toString())->toBe($uuid); }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Dashboard/DashboardRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Dashboard/DashboardRequestTest.php index 704ff800..e2fb37d3 100644 --- a/tests/Feature/App/Http/Requests/Bo/Dashboard/DashboardRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Dashboard/DashboardRequestTest.php @@ -4,73 +4,64 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Bo\Dashboard; -use App\Cqs\Queries\Dashboard\GetBoDashboardQueryInput; use App\Http\Requests\Bo\Dashboard\DashboardRequest; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; -use function Pest\Laravel\mock; - -describe('DashboardRequest', function () { - it('authorizes via auth service', function () { +describe('DashboardRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new DashboardRequest($authService); - - // WHEN $request->initialize(); + // WHEN + $authorized = $request->authorize(); + $denied = $request->authorize(); + // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('returns rules', function () { + it('validates paired start and end date parameters', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new DashboardRequest($authService)->rules(); + + // WHEN + $missingStart = Validator::make(['end' => '2026-01-31'], $rules); + $invalidDate = Validator::make(['start' => 'not-a-date', 'end' => '2026-01-31'], $rules); + $valid = Validator::make(['start' => '2026-01-01', 'end' => '2026-01-31'], $rules); + + // THEN + expect($missingStart->errors()->has('start'))->toBeTrue() + ->and($invalidDate->errors()->has('start'))->toBeTrue() + ->and($valid->passes())->toBeTrue(); + }); + + it('gets start and end dates when present', function (): void { + // GIVEN + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new DashboardRequest($authService); $request->initialize(); - // WHEN - $rules = $request->rules(); - - // THEN - expect($rules)->toHaveKeys(['start', 'end']); - }); - - it('gets start date', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new DashboardRequest($authService); - $request->initialize(); - - expect($request->getStart())->toBeNull(); + expect($request->getStart())->toBeNull() + ->and($request->getEnd())->toBeNull(); // WHEN - $request->merge(['start' => '2023-01-01']); + $request->merge(['start' => '2023-01-01', 'end' => '2023-12-31']); // THEN - expect($request->getStart()->format('Y-m-d'))->toBe('2023-01-01'); + expect($request->getStart()?->format('Y-m-d'))->toBe('2023-01-01') + ->and($request->getEnd()?->format('Y-m-d'))->toBe('2023-12-31'); }); - it('gets end date', function () { + it('maps to GetBoDashboardQueryInput', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new DashboardRequest($authService); - $request->initialize(); - - expect($request->getEnd())->toBeNull(); - - // WHEN - $request->merge(['end' => '2023-12-31']); - - // THEN - expect($request->getEnd()->format('Y-m-d'))->toBe('2023-12-31'); - }); - - it('maps to GetBoDashboardQueryInput', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new DashboardRequest($authService); $request->initialize(query: [ 'start' => '2026-01-01', @@ -81,8 +72,7 @@ describe('DashboardRequest', function () { $input = $request->toGetBoDashboardQueryInput(); // THEN - expect($input)->toBeInstanceOf(GetBoDashboardQueryInput::class) - ->and($input->start?->format('Y-m-d'))->toBe('2026-01-01') + expect($input->start?->format('Y-m-d'))->toBe('2026-01-01') ->and($input->end?->format('Y-m-d'))->toBe('2026-01-31'); }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php index eb00e66a..eaf8218f 100644 --- a/tests/Feature/App/Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php @@ -5,185 +5,154 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Bo\Discounts; use App\Http\Requests\Bo\Discounts\StoreDiscountRequest; -use Carbon\Exceptions\InvalidFormatException; +use App\Models\Discount; +use App\Models\User; use Domain\Enums\DiscountType; +use Domain\Enums\UserRole; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; use Money\Currency; -use function Pest\Laravel\mock; +use function Pest\Laravel\actingAs; +use function Pest\Laravel\post; -describe('StoreDiscountRequest', function () { - it('authorizes via auth service', function () { +describe('StoreDiscountRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new StoreDiscountRequest($authService, new Currency('EUR')); + $request->initialize(); // WHEN - $request->initialize(); + $authorized = $request->authorize(); + $denied = $request->authorize(); // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('prepares for validation', function () { + it('enforces max 100 only for percent discounts and checks date_end after date_start', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreDiscountRequest($authService, new Currency('EUR')); - $request->initialize(); + $authService = \Mockery::mock(AppAdminAuthService::class); + $percentRequest = new StoreDiscountRequest($authService, new Currency('EUR')); + $percentRequest->initialize(request: ['type' => DiscountType::PERCENT->value], server: ['REQUEST_METHOD' => 'POST']); + + $amountRequest = new StoreDiscountRequest($authService, new Currency('EUR')); + $amountRequest->initialize(request: ['type' => DiscountType::AMOUNT->value], server: ['REQUEST_METHOD' => 'POST']); // WHEN - $request->merge([ + $tooHighPercent = Validator::make([ + 'type' => DiscountType::PERCENT->value, + 'value' => 150, + 'is_old_price_displayed' => true, + 'date_start' => '2026-06-15T18:00', + 'date_end' => '2026-06-15T10:00', + 'client_timezone' => 'Europe/Paris', + 'associated_products' => [], + ], $percentRequest->rules()); + + $validAmount = Validator::make([ + 'type' => DiscountType::AMOUNT->value, + 'value' => 500, + 'is_old_price_displayed' => true, + 'date_start' => '2026-06-15T10:00', + 'date_end' => '2026-06-15T18:00', + 'client_timezone' => 'Europe/Paris', + 'associated_products' => [], + ], $amountRequest->rules()); + + // THEN + expect($tooHighPercent->errors()->has('value'))->toBeTrue() + ->and($tooHighPercent->errors()->has('date_end'))->toBeTrue() + ->and($validAmount->passes())->toBeTrue(); + }); + + it('normalizes booleans and converts local dates to UTC during HTTP store', function (): void { + // GIVEN + $admin = User::factory()->createOne(['role' => UserRole::SuperAdmin]); + actingAs($admin, 'backend'); + + // WHEN + $response = post(route('bo.discounts.store'), [ + 'type' => DiscountType::PERCENT->value, + 'value' => 15, 'is_old_price_displayed' => '1', - 'associated_products' => ['1', '2'], - ]); - - $reflection = new \ReflectionClass($request); - $prepareMethod = $reflection->getMethod('prepareForValidation'); - $prepareMethod->setAccessible(true); - $prepareMethod->invoke($request); - - // THEN - expect($request->input('is_old_price_displayed'))->toBeTrue() - ->and($request->input('associated_products'))->toBe(['1', '2']); - }); - - it('gets associated products ids', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreDiscountRequest($authService, new Currency('EUR')); - $request->initialize(); - - // WHEN - $request->merge(['associated_products' => [1, 2]]); - - // THEN - expect($request->getAssociatedProductsIds())->toBe(['1', '2']); - }); - - it('gets discount value for percent', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreDiscountRequest($authService, new Currency('EUR')); - $request->initialize(); - $request->merge([ - 'type' => DiscountType::PERCENT->value, - 'value' => 10, - ]); - - // WHEN - $value = $request->getDiscountValue(); - - // THEN - expect($value->type)->toBe(DiscountType::PERCENT); - }); - - it('gets discount value for amount', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreDiscountRequest($authService, new Currency('EUR')); - $request->initialize(); - $request->merge([ - 'type' => DiscountType::AMOUNT->value, - 'value' => 1000, // 10.00 - ]); - - // WHEN - $value = $request->getDiscountValue(); - - // THEN - expect($value->type)->toBe(DiscountType::AMOUNT); - }); - - it('passes validation formats dates', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreDiscountRequest($authService, new Currency('EUR')); - $request->initialize(); - - // WHEN - $request->merge([ - 'date_start' => '2023-01-01T10:00', - 'date_end' => '2023-01-02T10:00', - 'client_timezone' => 'Europe/Paris', - ]); - - $reflection = new \ReflectionClass($request); - $passedMethod = $reflection->getMethod('passedValidation'); - $passedMethod->setAccessible(true); - $passedMethod->invoke($request); - - // THEN - expect($request->input('date_start'))->toBe('2023-01-01 09:00:00') // Paris is UTC+1 in winter - ->and($request->input('date_end'))->toBe('2023-01-02 09:00:00'); - }); - - it('throws exception if invalid date_start or date_end provided in passedValidation', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreDiscountRequest($authService, new Currency('EUR')); - $request->initialize(); - - $request->merge([ - 'date_start' => 'invalid', - 'client_timezone' => 'Europe/Paris', - ]); - - $reflection = new \ReflectionClass($request); - $passedMethod = $reflection->getMethod('passedValidation'); - $passedMethod->setAccessible(true); - - expect(fn () => $passedMethod->invoke($request))->toThrow(InvalidFormatException::class, ''); - - // WHEN - $request->merge([ - 'date_start' => null, - 'date_end' => 'invalid', + 'date_start' => '2023-01-01T10:00', + 'date_end' => '2023-01-02T10:00', + 'client_timezone' => 'Europe/Paris', ]); // THEN - expect(fn () => $passedMethod->invoke($request))->toThrow(InvalidFormatException::class, ''); + $discount = Discount::query()->latest('id')->firstOrFail(); + $response->assertRedirect(route('bo.discounts.edit', $discount)); + expect($discount->is_old_price_displayed)->toBeTrue() + ->and($discount->date_start?->format('Y-m-d H:i:s'))->toBe('2023-01-01 09:00:00') + ->and($discount->date_end?->format('Y-m-d H:i:s'))->toBe('2023-01-02 09:00:00'); }); - it('returns rules and attributes', function () { + it('builds associated products ids and discount values for percent and amount', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreDiscountRequest($authService, new Currency('EUR')); - $request->initialize(); + $authService = \Mockery::mock(AppAdminAuthService::class); + $percentRequest = new StoreDiscountRequest($authService, new Currency('EUR')); + $percentRequest->initialize( + request: [ + 'type' => DiscountType::PERCENT->value, + 'value' => 10, + 'associated_products' => [1, 2], + ], + server: ['REQUEST_METHOD' => 'POST'], + ); + + $amountRequest = new StoreDiscountRequest($authService, new Currency('EUR')); + $amountRequest->initialize( + request: [ + 'type' => DiscountType::AMOUNT->value, + 'value' => 1000, + ], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN - $request->merge(['type' => DiscountType::PERCENT->value]); + $ids = $percentRequest->getAssociatedProductsIds(); + $percentVal = $percentRequest->getDiscountValue(); + $amountValue = $amountRequest->getDiscountValue(); // THEN - expect($request->rules())->toHaveKeys(['type', 'value', 'is_old_price_displayed', 'date_start', 'date_end', 'associated_products']) - ->and($request->attributes())->toHaveKeys(['type', 'value', 'is_old_price_displayed', 'date_start', 'date_end', 'associated_products']); + expect($ids)->toBe(['1', '2']) + ->and($percentVal->type)->toBe(DiscountType::PERCENT) + ->and($percentVal->getPercentage())->toBe(10) + ->and($amountValue->type)->toBe(DiscountType::AMOUNT) + ->and($amountValue->getAmount()->getAmount())->toBe('1000'); }); - it('returns domain Value Objects and typed properties via to* methods', function () { + it('maps request data into CreateDiscountInput', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new StoreDiscountRequest($authService, new Currency('EUR')); - $request->initialize(); - $request->merge([ - 'type' => DiscountType::PERCENT->value, - 'value' => 25, - 'associated_products' => ['prod-1', 'prod-2'], - 'date_start' => '2026-06-01 10:00:00', - 'date_end' => '2026-06-30 20:00:00', - ]); + $request->initialize( + request: [ + 'type' => DiscountType::PERCENT->value, + 'value' => 25, + 'is_old_price_displayed' => '1', + 'associated_products' => ['prod-1', 'prod-2'], + 'date_start' => '2026-06-01 10:00:00', + 'date_end' => '2026-06-30 20:00:00', + ], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN - $type = $request->toDiscountType(); - $value = $request->toDiscountValue(); - $productIds = $request->toAssociatedProductsIds(); - $period = $request->toDatePeriod(); + $input = $request->toCreateDiscountInput(); // THEN - expect($type)->toBe(DiscountType::PERCENT) - ->and($value->getPercentage())->toBe(25) - ->and($productIds)->toBe(['prod-1', 'prod-2']) - ->and($period->start?->format('Y-m-d H:i:s'))->toBe('2026-06-01 10:00:00') - ->and($period->end?->format('Y-m-d H:i:s'))->toBe('2026-06-30 20:00:00'); + expect($input->type)->toBe(DiscountType::PERCENT) + ->and($input->value->getPercentage())->toBe(25) + ->and($input->is_old_price_displayed)->toBeTrue() + ->and($input->associatedProductsIds)->toBe(['prod-1', 'prod-2']) + ->and($input->period->start?->format('Y-m-d H:i:s'))->toBe('2026-06-01 10:00:00') + ->and($input->period->end?->format('Y-m-d H:i:s'))->toBe('2026-06-30 20:00:00'); }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Faqs/StoreFaqRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Faqs/StoreFaqRequestTest.php index bc48d50f..8d427d44 100644 --- a/tests/Feature/App/Http/Requests/Bo/Faqs/StoreFaqRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Faqs/StoreFaqRequestTest.php @@ -8,119 +8,61 @@ use App\Http\Requests\Bo\Faqs\StoreFaqRequest; use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; -use function Pest\Laravel\mock; - -describe('StoreFaqRequest', function () { - it('authorizes via auth service', function () { +describe('StoreFaqRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new StoreFaqRequest($authService); - - // WHEN $request->initialize(); + // WHEN + $authorized = $request->authorize(); + $denied = $request->authorize(); + // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('fails authorization if auth service returns false', function () { + it('validates question and answer constraints', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(false); - - $request = new StoreFaqRequest($authService); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new StoreFaqRequest($authService)->rules(); // WHEN - $request->initialize(); + $missing = Validator::make([], $rules); + $questionShort = Validator::make(['question' => 'abc', 'answer' => 'Valid answer'], $rules); + $questionLong = Validator::make(['question' => str_repeat('a', 256), 'answer' => 'Valid answer'], $rules); + $answerShort = Validator::make(['question' => 'Valid question', 'answer' => 'abc'], $rules); + $valid = Validator::make(['question' => 'What is Pest?', 'answer' => 'A testing framework.'], $rules); // THEN - expect($request->authorize())->toBeFalse(); + expect($missing->errors()->keys())->toContain('question', 'answer') + ->and($questionShort->errors()->has('question'))->toBeTrue() + ->and($questionLong->errors()->has('question'))->toBeTrue() + ->and($answerShort->errors()->has('answer'))->toBeTrue() + ->and($valid->passes())->toBeTrue(); }); - it('validates question and answer', function () { + it('maps request data into CreateFaqInput', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new StoreFaqRequest($authService); - $request->initialize(); - - $rules = $request->rules(); - - expect($rules)->toHaveKeys(['question', 'answer']); + $request->initialize( + request: [ + 'question' => 'Quels sont vos horaires ?', + 'answer' => 'Du lundi au samedi de 8h à 19h.', + ], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN - $validator = Validator::make([ - 'question' => 'What is Pest?', - 'answer' => 'A testing framework.', - ], $rules); + $input = $request->toCreateFaqInput(); // THEN - expect($validator->passes())->toBeTrue(); - }); - - it('fails validation if required fields are missing', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreFaqRequest($authService); - $request->initialize(); - - // WHEN - $validator = Validator::make([], $request->rules()); - - // THEN - expect($validator->fails())->toBeTrue() - ->and($validator->errors()->keys())->toContain('question', 'answer'); - }); - - it('fails validation if question is too short or too long', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreFaqRequest($authService); - $request->initialize(); - - // WHEN - $rules = $request->rules(); - - $validatorShort = Validator::make(['question' => 'abc', 'answer' => 'Valid answer'], $rules); - expect($validatorShort->fails())->toBeTrue() - ->and($validatorShort->errors()->keys())->toContain('question'); - - $validatorLong = Validator::make(['question' => str_repeat('a', 256), 'answer' => 'Valid answer'], $rules); - - // THEN - expect($validatorLong->fails())->toBeTrue() - ->and($validatorLong->errors()->keys())->toContain('question'); - }); - - it('fails validation if answer is too short', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreFaqRequest($authService); - $request->initialize(); - - // WHEN - $rules = $request->rules(); - - $validatorShort = Validator::make(['question' => 'Valid question', 'answer' => 'abc'], $rules); - - // THEN - expect($validatorShort->fails())->toBeTrue() - ->and($validatorShort->errors()->keys())->toContain('answer'); - }); - - it('returns correct custom attributes', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreFaqRequest($authService); - $request->initialize(); - - // WHEN - $attributes = $request->attributes(); - - // THEN - expect($attributes)->toHaveKeys(['question', 'answer']) - ->and($attributes['question'])->toBe(trans('validation.custom.attributes.question')) - ->and($attributes['answer'])->toBe(trans('validation.custom.attributes.answer')); + expect($input->question)->toBe('Quels sont vos horaires ?') + ->and($input->answer)->toBe('Du lundi au samedi de 8h à 19h.'); }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/MassActionRequestTest.php b/tests/Feature/App/Http/Requests/Bo/MassActionRequestTest.php index a8be7efc..506383e5 100644 --- a/tests/Feature/App/Http/Requests/Bo/MassActionRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/MassActionRequestTest.php @@ -4,94 +4,63 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Bo; -use App\Cqs\Actions\Common\ExecuteMassActionInput; use App\Enums\MassActionType; use App\Http\Requests\Bo\MassActionRequest; use App\Models\Product; use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; -use function Pest\Laravel\mock; - -describe('MassActionRequest', function () { - it('authorizes via auth service', function () { +describe('MassActionRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new MassActionRequest($authService); + $request->initialize(); // WHEN - $request->initialize(); + $authorized = $request->authorize(); + $denied = $request->authorize(); // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('validates with action field and model list', function () { + it('validates action enum and models list', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new MassActionRequest($authService); - $request->initialize(); - $request->merge([ - 'action' => 'publish', - 'models' => ['1', '2'], - ]); - - $rules = $request->rules(); - expect($rules)->toHaveKeys(['action', 'models', 'models.*']); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new MassActionRequest($authService)->rules(); // WHEN - $validator = Validator::make($request->all(), $rules); + $valid = Validator::make(['action' => 'publish', 'models' => ['1', '2']], $rules); + $invalid = Validator::make(['action' => 'invalid-value', 'models' => ['1']], $rules); // THEN - expect($validator->passes())->toBeTrue(); + expect($valid->passes())->toBeTrue() + ->and($invalid->fails())->toBeTrue() + ->and($invalid->errors()->has('action'))->toBeTrue(); }); - it('fails validation with an invalid action value', function () { + it('resolves MassActionType and builds ExecuteMassActionInput', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new MassActionRequest($authService); - $request->initialize(); - $request->merge([ - 'action' => 'invalid-value', - 'models' => ['1'], - ]); - - // WHEN - $validator = Validator::make($request->all(), $request->rules()); - - // THEN - expect($validator->fails())->toBeTrue() - ->and($validator->errors()->has('action'))->toBeTrue(); - }); - - it('resolves MassActionType via getMassActionType()', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new MassActionRequest($authService); - $request->initialize(); - $request->merge(['action' => 'star', 'models' => ['1']]); - - // WHEN & THEN - expect($request->getMassActionType())->toBe(MassActionType::Star); - }); - - it('builds ExecuteMassActionInput via toExecuteMassActionInput()', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new MassActionRequest($authService); - $request->initialize(); - $request->merge([ - 'action' => 'unpublish', - 'models' => ['10', '20'], - ]); + $request->initialize( + request: [ + 'action' => 'unpublish', + 'models' => ['10', '20'], + ], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN + $type = $request->getMassActionType(); $input = $request->toExecuteMassActionInput(Product::class); // THEN - expect($input)->toBeInstanceOf(ExecuteMassActionInput::class) + expect($type)->toBe(MassActionType::Unpublish) ->and($input->modelClass)->toBe(Product::class) ->and($input->action)->toBe(MassActionType::Unpublish) ->and($input->modelKeyList)->toBe(['10', '20']); diff --git a/tests/Feature/App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php index 2d46bbb0..804d1d20 100644 --- a/tests/Feature/App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php @@ -4,169 +4,113 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Bo\Orders; -use App\Cqs\Queries\Orders\GetBoPaginatedOrdersQueryInput; use App\Http\Requests\Bo\Orders\IndexOrdersRequest; +use App\Models\User; use Domain\Enums\OrderStatus; +use Domain\Enums\UserRole; +use Illuminate\Session\ArraySessionHandler; +use Illuminate\Session\Store; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; -use function Pest\Laravel\mock; +use function Pest\Laravel\actingAs; +use function Pest\Laravel\get; -describe('IndexOrdersRequest', function () { - it('authorizes via auth service', function () { +describe('IndexOrdersRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new IndexOrdersRequest($authService); + $request->initialize(); // WHEN - $request->initialize(); + $authorized = $request->authorize(); + $denied = $request->authorize(); // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('prepares for validation by removing empty filter values while preserving other parameters', function () { + it('accepts empty filter query parameters over HTTP via prepareForValidation', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); + $admin = User::factory()->createOne(['role' => UserRole::SuperAdmin]); + actingAs($admin, 'backend'); + + // WHEN + $response = get(route('bo.orders.index', [ + 'order_date_start' => '', + 'order_date_end' => '', + 'order_pickup_start' => '', + 'order_pickup_end' => '', + 'status' => '', + ])); + + // THEN + $response->assertOk() + ->assertSessionHasNoErrors(); + }); + + it('validates status enum and date ordering constraints', function (): void { + // GIVEN + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new IndexOrdersRequest($authService)->rules(); + + // WHEN + $invalid = Validator::make([ + 'status' => 'not-a-status', + 'order_date_start' => '2026-06-15', + 'order_date_end' => '2026-06-10', + ], $rules); + $valid = Validator::make([ + 'status' => OrderStatus::WAITING->value, + 'order_date_start' => '2026-06-10', + 'order_date_end' => '2026-06-15', + ], $rules); + + // THEN + expect($invalid->errors()->has('status'))->toBeTrue() + ->and($invalid->errors()->has('order_date_end'))->toBeTrue() + ->and($valid->passes())->toBeTrue(); + }); + + it('resolves status and filter dates', function (): void { + // GIVEN + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new IndexOrdersRequest($authService); $request->initialize(); + expect($request->getStatus())->toBeNull() + ->and($request->getOrderDateStart())->toBeNull() + ->and($request->getOrderDateEnd())->toBeNull() + ->and($request->getOrderPickupStart())->toBeNull() + ->and($request->getOrderPickupEnd())->toBeNull(); + // WHEN $request->merge([ + 'status' => OrderStatus::WAITING->value, 'order_date_start' => '2023-01-01', - 'order_date_end' => '', - 'order_pickup_start' => null, - 'status' => 'pending', - 'page' => '3', - 'other_field' => 'value', + 'order_date_end' => '2023-01-02', + 'order_pickup_start' => '2023-01-03', + 'order_pickup_end' => '2023-01-04', ]); - $reflection = new \ReflectionClass($request); - $prepareMethod = $reflection->getMethod('prepareForValidation'); - $prepareMethod->setAccessible(true); - $prepareMethod->invoke($request); - // THEN - expect($request->all())->toBe([ - 'order_date_start' => '2023-01-01', - 'status' => 'pending', - 'page' => '3', - 'other_field' => 'value', - ]); + expect($request->getStatus())->toBe(OrderStatus::WAITING) + ->and($request->getOrderDateStart()?->format('Y-m-d'))->toBe('2023-01-01') + ->and($request->getOrderDateEnd()?->format('Y-m-d'))->toBe('2023-01-02') + ->and($request->getOrderPickupStart()?->format('Y-m-d'))->toBe('2023-01-03') + ->and($request->getOrderPickupEnd()?->format('Y-m-d'))->toBe('2023-01-04'); }); - it('gets status', function () { + it('maps to GetBoPaginatedOrdersQueryInput and syncs status in session', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new IndexOrdersRequest($authService); - $request->initialize(); - - expect($request->getStatus())->toBeNull(); - - // WHEN - $request->merge(['status' => OrderStatus::WAITING->value]); - - // THEN - expect($request->getStatus())->toBe(OrderStatus::WAITING); - }); - - it('gets order date start', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new IndexOrdersRequest($authService); - $request->initialize(); - expect($request->getOrderDateStart())->toBeNull(); - - // WHEN - $request->merge(['order_date_start' => '2023-01-01']); - - // THEN - expect($request->getOrderDateStart()->format('Y-m-d'))->toBe('2023-01-01'); - }); - - it('gets order date end', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new IndexOrdersRequest($authService); - $request->initialize(); - expect($request->getOrderDateEnd())->toBeNull(); - - // WHEN - $request->merge(['order_date_end' => '2023-01-02']); - - // THEN - expect($request->getOrderDateEnd()->format('Y-m-d'))->toBe('2023-01-02'); - }); - - it('gets order pickup start', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new IndexOrdersRequest($authService); - $request->initialize(); - expect($request->getOrderPickupStart())->toBeNull(); - - // WHEN - $request->merge(['order_pickup_start' => '2023-01-03']); - - // THEN - expect($request->getOrderPickupStart()->format('Y-m-d'))->toBe('2023-01-03'); - }); - - it('gets order pickup end', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new IndexOrdersRequest($authService); - $request->initialize(); - expect($request->getOrderPickupEnd())->toBeNull(); - - // WHEN - $request->merge(['order_pickup_end' => '2023-01-04']); - - // THEN - expect($request->getOrderPickupEnd()->format('Y-m-d'))->toBe('2023-01-04'); - }); - - it('validates rules', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new IndexOrdersRequest($authService); - - // WHEN - $request->initialize(); - - // THEN - expect($request->rules())->toHaveKeys([ - 'status', - 'order_date_start', - 'order_date_end', - 'order_pickup_start', - 'order_pickup_end', - ]); - }); - - it('returns attributes', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new IndexOrdersRequest($authService); - - // WHEN - $request->initialize(); - - // THEN - expect($request->attributes())->toHaveKeys([ - 'status', - 'order_date_start', - 'order_date_end', - 'order_pickup_start', - 'order_pickup_end', - ]); - }); - - it('maps to GetBoPaginatedOrdersQueryInput', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); + $session = new Store('test', new ArraySessionHandler(120)); $request = new IndexOrdersRequest($authService); + $request->setLaravelSession($session); $request->initialize(query: [ 'page' => 3, 'search' => 'TEST-REF', @@ -177,9 +121,9 @@ describe('IndexOrdersRequest', function () { $input = $request->toGetBoPaginatedOrdersQueryInput(); // THEN - expect($input)->toBeInstanceOf(GetBoPaginatedOrdersQueryInput::class) - ->and($input->pagination->pageNumber()->value())->toBe(3) + expect($input->pagination->pageNumber()->value())->toBe(3) ->and($input->search)->toBe('TEST-REF') - ->and($input->status)->toBe(OrderStatus::VALIDATED); + ->and($input->status)->toBe(OrderStatus::VALIDATED) + ->and($session->get('orders.filter.status'))->toBe(OrderStatus::VALIDATED); }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Pages/UpdatePageRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Pages/UpdatePageRequestTest.php index eea03e24..a82ca8f4 100644 --- a/tests/Feature/App/Http/Requests/Bo/Pages/UpdatePageRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Pages/UpdatePageRequestTest.php @@ -5,48 +5,74 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Bo\Pages; use App\Http\Requests\Bo\Pages\UpdatePageRequest; +use App\Models\Page; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; -use function Pest\Laravel\mock; - -describe('UpdatePageRequest', function () { - it('authorizes via auth service', function () { +describe('UpdatePageRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new UpdatePageRequest($authService); - - // WHEN $request->initialize(); + // WHEN + $authorized = $request->authorize(); + $denied = $request->authorize(); + // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('validates rules', function () { + it('validates SEO length bounds and required content', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new UpdatePageRequest($authService); - $request->initialize(); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new UpdatePageRequest($authService)->rules(); // WHEN - $rules = $request->rules(); + $invalid = Validator::make([ + 'seo_title' => 'Trop court', + 'seo_description' => 'Trop courte aussi', + 'content' => '', + ], $rules); + $valid = Validator::make([ + 'seo_title' => str_repeat('a', 50), + 'seo_description' => str_repeat('b', 80), + 'title' => 'Conditions générales', + 'content' => '

Contenu valide.

', + ], $rules); // THEN - expect($rules)->toHaveKeys(['seo_title', 'seo_description', 'title', 'content']); + expect($invalid->errors()->keys())->toContain('seo_title', 'seo_description', 'content') + ->and($valid->passes())->toBeTrue(); }); - it('returns attributes', function () { + it('maps request data into UpdatePageInput', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); + $page = new Page(); $request = new UpdatePageRequest($authService); - $request->initialize(); + $request->initialize( + request: [ + 'seo_title' => str_repeat('T', 50), + 'seo_description' => str_repeat('D', 80), + 'title' => 'Mentions légales', + 'content' => '

Texte légal

', + ], + server: ['REQUEST_METHOD' => 'PUT'], + ); // WHEN - $attributes = $request->attributes(); + $input = $request->toUpdatePageInput($page); // THEN - expect($attributes)->toHaveKeys(['seo_title', 'seo_description', 'title', 'content']); + expect($input->page)->toBe($page) + ->and($input->seo->title)->toBe(str_repeat('T', 50)) + ->and($input->seo->description)->toBe(str_repeat('D', 80)) + ->and($input->title)->toBe('Mentions légales') + ->and($input->content)->toBe('

Texte légal

'); }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/PickupExceptions/StorePickupExceptionRequestTest.php b/tests/Feature/App/Http/Requests/Bo/PickupExceptions/StorePickupExceptionRequestTest.php index e9cff09a..f5670370 100644 --- a/tests/Feature/App/Http/Requests/Bo/PickupExceptions/StorePickupExceptionRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/PickupExceptions/StorePickupExceptionRequestTest.php @@ -5,109 +5,99 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Bo\PickupExceptions; use App\Http\Requests\Bo\PickupExceptions\StorePickupExceptionRequest; +use App\Models\PickupException; +use App\Models\User; use Domain\Enums\RepeatFrequency; +use Domain\Enums\UserRole; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; -use function Pest\Laravel\mock; +use function Pest\Laravel\actingAs; +use function Pest\Laravel\post; -describe('StorePickupExceptionRequest', function () { - it('authorizes via auth service', function () { +describe('StorePickupExceptionRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new StorePickupExceptionRequest($authService); + $request->initialize(); // WHEN - $request->initialize(); + $authorized = $request->authorize(); + $denied = $request->authorize(); // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('prepares for validation', function () { + it('requires valid date format, label and repeat_frequency when repeatable is true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StorePickupExceptionRequest($authService); - $request->initialize(); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new StorePickupExceptionRequest($authService)->rules(); // WHEN - $request->merge(['repeatable' => '1']); - - $reflection = new \ReflectionClass($request); - $prepareMethod = $reflection->getMethod('prepareForValidation'); - $prepareMethod->setAccessible(true); - $prepareMethod->invoke($request); - - // THEN - expect($request->input('repeatable'))->toBeTrue(); - }); - - it('passes validation resets repeat frequency to Weekly if not repeatable', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StorePickupExceptionRequest($authService); - $request->initialize(); - - // WHEN - $request->merge([ - 'repeatable' => false, - 'repeat_frequency' => RepeatFrequency::WEEKLY->value, - ]); - - $reflection = new \ReflectionClass($request); - $passedMethod = $reflection->getMethod('passedValidation'); - $passedMethod->setAccessible(true); - $passedMethod->invoke($request); - - // THEN - expect($request->input('repeat_frequency'))->toBe(RepeatFrequency::WEEKLY->value); - }); - - it('passes validation keeps repeat frequency if repeatable', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StorePickupExceptionRequest($authService); - $request->initialize(); - - // WHEN - $request->merge([ + $invalid = Validator::make([ + 'date' => '15/08/2026', + 'label' => '', 'repeatable' => true, - 'repeat_frequency' => RepeatFrequency::WEEKLY->value, + 'repeat_frequency' => null, + ], $rules); + $valid = Validator::make([ + 'date' => '2026-08-15', + 'label' => 'Assomption', + 'repeatable' => true, + 'repeat_frequency' => RepeatFrequency::YEARLY->value, + ], $rules); + + // THEN + expect($invalid->errors()->keys())->toContain('date', 'label', 'repeat_frequency') + ->and($valid->passes())->toBeTrue(); + }); + + it('normalizes repeat_frequency to weekly during HTTP store when repeatable is false', function (): void { + // GIVEN + $admin = User::factory()->createOne(['role' => UserRole::SuperAdmin]); + actingAs($admin, 'backend'); + + // WHEN + $response = post(route('bo.pickup-exceptions.store'), [ + 'date' => '2026-07-14', + 'label' => 'Fête nationale', + 'repeatable' => '0', + 'repeat_frequency' => RepeatFrequency::MONTHLY->value, ]); - $reflection = new \ReflectionClass($request); - $passedMethod = $reflection->getMethod('passedValidation'); - $passedMethod->setAccessible(true); - $passedMethod->invoke($request); - // THEN - expect($request->input('repeat_frequency'))->toBe(RepeatFrequency::WEEKLY->value); + $exception = PickupException::query()->where('label', 'Fête nationale')->firstOrFail(); + $response->assertRedirect(route('bo.pickup-exceptions.edit', $exception)); + expect($exception->repeatable)->toBeFalse() + ->and($exception->repeat_frequency)->toBe(RepeatFrequency::WEEKLY); }); - it('returns rules', function () { + it('maps request data into CreatePickupExceptionInput', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new StorePickupExceptionRequest($authService); - $request->initialize(); + $request->initialize( + request: [ + 'date' => '2026-12-25', + 'label' => 'Noël', + 'repeatable' => '1', + 'repeat_frequency' => RepeatFrequency::YEARLY->value, + ], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN - $rules = $request->rules(); + $input = $request->toCreatePickupExceptionInput(); // THEN - expect($rules)->toHaveKeys(['date', 'label', 'repeatable', 'repeat_frequency']); - }); - - it('returns attributes', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StorePickupExceptionRequest($authService); - $request->initialize(); - - // WHEN - $attributes = $request->attributes(); - - // THEN - expect($attributes)->toHaveKeys(['date', 'label', 'repeatable', 'repeat_frequency']); + expect($input->date)->toBe('2026-12-25') + ->and($input->label)->toBe('Noël') + ->and($input->repeatable)->toBeTrue() + ->and($input->repeat_frequency)->toBe(RepeatFrequency::YEARLY); }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php index 6789a2d4..da332046 100644 --- a/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php @@ -5,152 +5,101 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Bo\Shops; use App\Http\Requests\Bo\Shops\IndexShopRequest; +use App\Models\User; +use Domain\Enums\UserRole; use Domain\Models\ValueObjects\Entities\PickupExceptionId; -use Illuminate\Contracts\Session\Session; +use Illuminate\Session\ArraySessionHandler; +use Illuminate\Session\Store; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; use Ramsey\Uuid\Uuid; -use function Pest\Laravel\mock; +use function Pest\Laravel\actingAs; +use function Pest\Laravel\get; -describe('IndexShopRequest', function () { - it('authorizes via auth service', function () { +describe('IndexShopRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); - $request = new IndexShopRequest($authService); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); - // WHEN + $request = new IndexShopRequest($authService); $request->initialize(); + // WHEN + $authorized = $request->authorize(); + $denied = $request->authorize(); + // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('returns rules', function () { + it('validates pickup-exception parameter as uuid', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new IndexShopRequest($authService); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new IndexShopRequest($authService)->rules(); // WHEN - $request->initialize(); + $invalid = Validator::make(['pickup-exception' => 'not-a-uuid'], $rules); + $valid = Validator::make(['pickup-exception' => Uuid::uuid7()->toString()], $rules); // THEN - expect($request->rules())->toBeArray() - ->and($request->rules())->toHaveKey('pickup-exception'); + expect($invalid->errors()->has('pickup-exception'))->toBeTrue() + ->and($valid->passes())->toBeTrue(); }); - it('prepares for validation and updates session', function () { + it('stores and clears pickup-exception filter in session over HTTP', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $session = mock(Session::class); - $uuid = Uuid::uuid7()->toString(); - - $session->shouldReceive('put') - ->once() - ->with(IndexShopRequest::SESSION_KEY, $uuid); - - $request = new IndexShopRequest($authService); - $request->initialize(query: ['pickup-exception' => $uuid]); - $request->setLaravelSession($session); - - $method = new \ReflectionMethod($request, 'prepareForValidation'); - $method->setAccessible(true); + $admin = User::factory()->createOne(['role' => UserRole::SuperAdmin]); + actingAs($admin, 'backend'); + $uuid = Uuid::uuid7()->toString(); // WHEN - $method->invoke($request); + $withFilter = get(route('bo.shops.index', ['pickup-exception' => $uuid])); // THEN - expect(true)->toBeTrue(); - }); - - it('prepares for validation and forgets session when pickup-exception is empty', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $session = mock(Session::class); - - $session->shouldReceive('forget') - ->once() - ->with(IndexShopRequest::SESSION_KEY); - - $request = new IndexShopRequest($authService); - $request->initialize(query: ['pickup-exception' => '']); - $request->setLaravelSession($session); - - $method = new \ReflectionMethod($request, 'prepareForValidation'); - $method->setAccessible(true); + $withFilter->assertOk() + ->assertSessionHas(IndexShopRequest::SESSION_KEY, $uuid); // WHEN - $method->invoke($request); + $cleared = get(route('bo.shops.index', ['pickup-exception' => ''])); // THEN - expect(true)->toBeTrue(); + $cleared->assertOk() + ->assertSessionMissing(IndexShopRequest::SESSION_KEY); }); - it('getPickupExceptionId returns PickupExceptionId from session', function () { + it('resolves PickupExceptionId only for a valid UUIDv7 in session', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $session = mock(Session::class); - $uuid = Uuid::uuid7(); - - $session->shouldReceive('get') - ->once() - ->with(IndexShopRequest::SESSION_KEY) - ->andReturn($uuid->toString()); + $authService = \Mockery::mock(AppAdminAuthService::class); + $session = new Store('test', new ArraySessionHandler(120)); + $uuidV7 = Uuid::uuid7()->toString(); + $session->put(IndexShopRequest::SESSION_KEY, $uuidV7); $request = new IndexShopRequest($authService); $request->initialize(); $request->setLaravelSession($session); // WHEN - $id = $request->getPickupExceptionId(); + $resolved = $request->toPickupExceptionId(); // THEN - expect($id)->toBeInstanceOf(PickupExceptionId::class) - ->and((string) $id)->toBe($uuid->toString()); - }); + expect($resolved)->toBeInstanceOf(PickupExceptionId::class) + ->and((string) $resolved)->toBe($uuidV7) + ->and((string) $request->getPickupExceptionId())->toBe($uuidV7); - it('getPickupExceptionId returns null when session is empty or invalid', function () { // GIVEN - $authService = mock(AppAdminAuthService::class); - $session = mock(Session::class); + $session->put(IndexShopRequest::SESSION_KEY, Uuid::uuid4()->toString()); - $session->shouldReceive('get') - ->twice() - ->with(IndexShopRequest::SESSION_KEY) - ->andReturn(null); + // WHEN & THEN + expect($request->toPickupExceptionId())->toBeNull(); - $request = new IndexShopRequest($authService); - $request->initialize(); - $request->setLaravelSession($session); - - // WHEN - $id = $request->getPickupExceptionId(); - - // THEN - expect($id)->toBeNull() - ->and($request->toPickupExceptionId())->toBeNull(); - }); - - it('toPickupExceptionId returns PickupExceptionId from valid session', function () { // GIVEN - $authService = mock(AppAdminAuthService::class); - $session = mock(Session::class); - $uuid = Uuid::uuid7(); + $session->forget(IndexShopRequest::SESSION_KEY); - $session->shouldReceive('get') - ->once() - ->with(IndexShopRequest::SESSION_KEY) - ->andReturn($uuid->toString()); - - $request = new IndexShopRequest($authService); - $request->initialize(); - $request->setLaravelSession($session); - - // WHEN - $id = $request->toPickupExceptionId(); - - // THEN - expect($id)->toBeInstanceOf(PickupExceptionId::class) - ->and((string) $id)->toBe($uuid->toString()); + // WHEN & THEN + expect($request->toPickupExceptionId())->toBeNull() + ->and($request->getPickupExceptionId())->toBeNull(); }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Shops/StoreShopRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Shops/StoreShopRequestTest.php index 1fae861b..7bfe86dd 100644 --- a/tests/Feature/App/Http/Requests/Bo/Shops/StoreShopRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Shops/StoreShopRequestTest.php @@ -5,89 +5,113 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Bo\Shops; use App\Http\Requests\Bo\Shops\StoreShopRequest; +use App\Models\Shop; +use App\Models\User; +use Domain\Enums\UserRole; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; -use function Pest\Laravel\mock; +use function Pest\Laravel\actingAs; +use function Pest\Laravel\post; -describe('StoreShopRequest', function () { - it('authorizes via auth service', function () { +describe('StoreShopRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); + $request = new StoreShopRequest($authService); - - // WHEN $request->initialize(); + // WHEN + $authorized = $request->authorize(); + $denied = $request->authorize(); + // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('returns rules', function () { + it('validates French postal code and phone format', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreShopRequest($authService); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new StoreShopRequest($authService)->rules(); // WHEN - $request->initialize(); + $invalid = Validator::make([ + 'name' => 'Boutique Test', + 'address' => '1 rue du Test', + 'postcode' => 'INVALID', + 'city' => 'Paris', + 'default' => false, + 'phone' => 'not-a-phone', + ], $rules); + $valid = Validator::make([ + 'name' => 'Boutique Test', + 'address' => '1 rue du Test', + 'postcode' => '75001', + 'city' => 'Paris', + 'default' => false, + 'phone' => '01 02 03 04 05', + ], $rules); // THEN - expect($request->rules())->toBeArray(); + expect($invalid->errors()->has('postcode'))->toBeTrue() + ->and($invalid->errors()->has('phone'))->toBeTrue() + ->and($valid->passes())->toBeTrue(); }); - it('returns attributes', function () { + it('normalizes phone number and boolean default over HTTP store', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreShopRequest($authService); + $admin = User::factory()->createOne(['role' => UserRole::SuperAdmin]); + actingAs($admin, 'backend'); // WHEN - $request->initialize(); + $response = post(route('bo.shops.store'), [ + 'name' => 'Boutique Mans', + 'address' => '10 avenue Bollée', + 'postcode' => '72000', + 'city' => 'Le Mans', + 'phone' => '02 43 01 02 03', + 'default' => '1', + ]); // THEN - expect($request->attributes())->toBeArray(); + $shop = Shop::query()->where('name', 'Boutique Mans')->firstOrFail(); + $response->assertRedirect(route('bo.shops.edit', $shop)); + expect($shop->default)->toBeTrue() + ->and($shop->phone)->toBe('tel:+33-2-43-01-02-03'); }); - it('prepares for validation', function () { + it('converts coordinates and phone number to Value Objects and maps CreateShopInput', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new StoreShopRequest($authService); - $request->initialize(); - $method = new \ReflectionMethod($request, 'prepareForValidation'); - $method->setAccessible(true); - - // WHEN - $method->invoke($request); - - // THEN - expect(true)->toBeTrue(); // just making sure it runs without exception - }); - - it('converts to coordinates', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreShopRequest($authService); - $request->initialize(query: ['latitude' => '48.8566', 'longitude' => '2.3522']); + $request->initialize( + request: [ + 'name' => 'Boutique Paris', + 'address' => '12 rue de Rivoli', + 'postcode' => '75001', + 'city' => 'Paris', + 'latitude' => '48.8566', + 'longitude' => '2.3522', + 'phone' => '+33102030405', + 'default' => '1', + ], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN $coords = $request->toCoordinates(); + $phone = $request->toPhoneNumber(); + $input = $request->toCreateShopInput(); // THEN - expect($coords)->not->toBeNull() - ->and($coords?->latitude)->toBe(48.8566) - ->and($coords?->longitude)->toBe(2.3522); - }); - - it('converts to phone number', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreShopRequest($authService); - $request->initialize(query: ['phone' => '+33102030405']); - - // WHEN - $phone = $request->toPhoneNumber(); - - // THEN - expect($phone)->not->toBeNull() - ->and((string) $phone)->toBe('tel:+33-1-02-03-04-05'); + expect($coords?->latitude)->toBe(48.8566) + ->and($coords?->longitude)->toBe(2.3522) + ->and((string) $phone)->toBe('tel:+33-1-02-03-04-05') + ->and($input->name)->toBe('Boutique Paris') + ->and($input->default)->toBeTrue() + ->and((string) $input->phone)->toBe('tel:+33-1-02-03-04-05'); }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequestTest.php index b73b5c14..d59ddaf3 100644 --- a/tests/Feature/App/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequestTest.php @@ -6,62 +6,33 @@ namespace Tests\Feature\App\Http\Requests\Bo\Shops; use App\Http\Requests\Bo\Shops\UpdateShopPickupExceptionsRequest; use App\Models\PickupException; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; -use function Pest\Laravel\mock; - -uses(RefreshDatabase::class); - -describe('UpdateShopPickupExceptionsRequest', function () { - it('authorizes via auth service', function () { +describe('UpdateShopPickupExceptionsRequest', function (): void { + it('authorizes only when admin auth service returns true', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); - $request = new UpdateShopPickupExceptionsRequest($authService); + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); - // WHEN + $request = new UpdateShopPickupExceptionsRequest($authService); $request->initialize(); - // THEN - expect($request->authorize())->toBeTrue(); - }); - - it('returns rules with uuid and exists for pickup-exceptions', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new UpdateShopPickupExceptionsRequest($authService); - // WHEN - $rules = $request->rules(); + $authorized = $request->authorize(); + $denied = $request->authorize(); // THEN - expect($rules)->toHaveKey('pickup-exceptions') - ->and($rules['pickup-exceptions.*'])->toContain('uuid') - ->and($rules['pickup-exceptions.*'])->toContain('exists:pickup_exceptions,id') - ->and($rules['pickup-exceptions.*'])->not->toContain('integer'); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('returns human friendly attributes', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new UpdateShopPickupExceptionsRequest($authService); - - // WHEN - $attributes = $request->attributes(); - - // THEN - expect($attributes)->toHaveKey('pickup-exceptions.*') - ->and($attributes['pickup-exceptions.*'])->toBe('fermeture exceptionnelle'); - }); - - it('validates successfully with valid pickup exceptions and dates', function () { + it('validates successfully with valid pickup exceptions and dates', function (): void { // GIVEN $exception1 = PickupException::factory()->create(); $exception2 = PickupException::factory()->create(); - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new UpdateShopPickupExceptionsRequest($authService); $data = [ @@ -84,9 +55,9 @@ describe('UpdateShopPickupExceptionsRequest', function () { expect($validator->passes())->toBeTrue(); }); - it('rejects invalid uuid with non cryptic message', function () { + it('rejects invalid uuid with non cryptic message', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new UpdateShopPickupExceptionsRequest($authService); $data = [ @@ -103,9 +74,9 @@ describe('UpdateShopPickupExceptionsRequest', function () { expect($errors[0])->toBe('Le champ fermeture exceptionnelle doit être un UUID valide.'); }); - it('rejects nonexistent uuid with non cryptic message', function () { + it('rejects nonexistent uuid with non cryptic message', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new UpdateShopPickupExceptionsRequest($authService); $data = [ @@ -122,11 +93,10 @@ describe('UpdateShopPickupExceptionsRequest', function () { expect($errors[0])->toBe('Le champ fermeture exceptionnelle sélectionné est invalide.'); }); - it('rejects order deadline after replacement date with human friendly message', function () { + it('rejects order deadline after replacement date with human friendly message', function (): void { // GIVEN - $exception = PickupException::factory()->create(); - - $authService = mock(AppAdminAuthService::class); + $exception = PickupException::factory()->create(); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new UpdateShopPickupExceptionsRequest($authService); $data = [ @@ -149,11 +119,10 @@ describe('UpdateShopPickupExceptionsRequest', function () { expect($errors)->toContain('Le champ date limite de commande doit être une date antérieure au jour de remplacement.'); }); - it('rejects order deadline equal to replacement date with human friendly message', function () { + it('rejects order deadline equal to replacement date with human friendly message', function (): void { // GIVEN - $exception = PickupException::factory()->create(); - - $authService = mock(AppAdminAuthService::class); + $exception = PickupException::factory()->create(); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new UpdateShopPickupExceptionsRequest($authService); $data = [ @@ -176,11 +145,10 @@ describe('UpdateShopPickupExceptionsRequest', function () { expect($errors)->toContain('Le champ date limite de commande doit être une date antérieure au jour de remplacement.'); }); - it('rejects order deadline without replacement date with human friendly message', function () { + it('rejects order deadline without replacement date with human friendly message', function (): void { // GIVEN - $exception = PickupException::factory()->create(); - - $authService = mock(AppAdminAuthService::class); + $exception = PickupException::factory()->create(); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new UpdateShopPickupExceptionsRequest($authService); $data = [ @@ -203,22 +171,24 @@ describe('UpdateShopPickupExceptionsRequest', function () { expect($errors)->toContain('Le champ jour de remplacement est obligatoire quand date limite de commande est présent.'); }); - it('transforms data to sync data format correctly', function () { + it('transforms data to sync data format correctly', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new UpdateShopPickupExceptionsRequest($authService); - $request->initialize(); - $request->merge([ - 'pickup-exceptions' => ['uuid-1', 'uuid-2'], - 'replacement_date' => [ - 'uuid-1' => '2026-10-15', - 'uuid-2' => '', + $request->initialize( + request: [ + 'pickup-exceptions' => ['uuid-1', 'uuid-2'], + 'replacement_date' => [ + 'uuid-1' => '2026-10-15', + 'uuid-2' => '', + ], + 'order_deadline_at' => [ + 'uuid-1' => '2026-10-14 16:00:00', + 'uuid-2' => '', + ], ], - 'order_deadline_at' => [ - 'uuid-1' => '2026-10-14 16:00:00', - 'uuid-2' => '', - ], - ]); + server: ['REQUEST_METHOD' => 'PUT'], + ); // WHEN $syncData = $request->toSyncData(); From 7ad5acebd3ff08b247e32da1b30f6393418b1fb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 15:31:41 +0100 Subject: [PATCH 141/183] test(requests): overhaul FO request tests and lock Architecture rules --- tests/Architecture/CodingStandardsTest.php | 49 ++++ .../Fo/Ajax/FilterProductsRequestTest.php | 129 ++++------- .../Requests/Fo/Auth/RegisterRequestTest.php | 156 ++++--------- .../Requests/Fo/ContactFormRequestTest.php | 26 +-- .../Fo/Customer/UpdateInfosRequestTest.php | 211 +++++++----------- .../Fo/Customer/UpdatePasswordRequestTest.php | 55 +++-- .../Fo/Orders/ConfirmOrderRequestTest.php | 55 ++--- .../Fo/Orders/PickTimeSlotRequestTest.php | 155 +++++-------- .../Fo/Orders/ValidateSummaryRequestTest.php | 63 ++---- .../Fo/UnsubscribeNewsletterRequestTest.php | 4 +- .../Frontend/OrderTunnelStepPolicyTest.php | 2 +- 11 files changed, 373 insertions(+), 532 deletions(-) rename tests/{Unit => Integration/WithApp}/App/Policies/Frontend/OrderTunnelStepPolicyTest.php (99%) diff --git a/tests/Architecture/CodingStandardsTest.php b/tests/Architecture/CodingStandardsTest.php index be85ba3d..040ab5f4 100644 --- a/tests/Architecture/CodingStandardsTest.php +++ b/tests/Architecture/CodingStandardsTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Tests\Architecture; use Shared\Filesystem\TemporaryFileFactory; +use Symfony\Component\Finder\Finder; // Coding standards arch()->preset()->php(); @@ -59,3 +60,51 @@ arch('all shared source files use strict types') arch('all infrastructure source files use strict types') ->expect('Infrastructure') ->toUseStrictTypes(); + +it('enforces PSR-4 namespaces and bans anti-patterns across tests', function (): void { + // GIVEN + $testRoot = dirname(__DIR__); + $finder = Finder::create() + ->files() + ->in([$testRoot . '/Unit', $testRoot . '/Integration', $testRoot . '/Feature']) + ->name('*Test.php'); + + // WHEN & THEN + foreach ($finder as $file) { + $relativePath = str_replace($testRoot . DIRECTORY_SEPARATOR, '', $file->getRealPath()); + $expectedNs = 'Tests\\' . str_replace(DIRECTORY_SEPARATOR, '\\', dirname($relativePath)); + $contents = $file->getContents(); + + expect($contents)->toContain("namespace {$expectedNs};") + ->and($contents)->not->toContain('expect(true)->toBeTrue()') + ->and($contents)->not->toContain('newInstanceWithoutConstructor') + ->and($contents)->not->toContain('Schema::create('); + } +}); + +it('keeps unit tests isolated from Laravel runtime helpers and facades', function (): void { + // GIVEN + $unitFinder = Finder::create() + ->files() + ->in(dirname(__DIR__) . '/Unit') + ->name('*Test.php'); + + $forbiddenPatterns = [ + 'uses(TestCase::class)', + 'uses(RefreshDatabase::class)', + 'Illuminate\\Support\\Facades\\', + 'Pest\\Laravel\\', + 'UploadedFile::fake', + ]; + + // WHEN & THEN + foreach ($unitFinder as $file) { + $contents = $file->getContents(); + + foreach ($forbiddenPatterns as $pattern) { + expect($contents)->not->toContain($pattern); + } + + expect(preg_match('/(?\w$-])(app|resolve|now|collect)\s*\(/', $contents))->toBe(0); + } +}); diff --git a/tests/Feature/App/Http/Requests/Fo/Ajax/FilterProductsRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Ajax/FilterProductsRequestTest.php index 0f9eb206..9a4ab204 100644 --- a/tests/Feature/App/Http/Requests/Fo/Ajax/FilterProductsRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Ajax/FilterProductsRequestTest.php @@ -7,112 +7,73 @@ namespace Tests\Feature\App\Http\Requests\Fo\Ajax; use App\Http\Requests\Fo\Ajax\FilterProductsRequest; use Illuminate\Support\Facades\Validator; -describe('FilterProductsRequest', function () { - it('merges default values in prepareForValidation', function () { - // GIVEN - $request = new FilterProductsRequest(); - $request->initialize(); - - $reflection = new \ReflectionClass($request); - $method = $reflection->getMethod('prepareForValidation'); - $method->setAccessible(true); +use function Pest\Laravel\getJson; +describe('FilterProductsRequest', function (): void { + it('applies default pagination and empty filter arrays over HTTP via prepareForValidation', function (): void { // WHEN - $method->invoke($request); + $response = getJson(route('ajax.products.filter')); // THEN - expect($request->all())->toHaveKeys(['ranges', 'tags', 'brands', 'isDiscounted', 'page', 'perPage']) - ->and($request->input('ranges'))->toBeArray()->toBeEmpty() - ->and($request->input('tags'))->toBeArray()->toBeEmpty() - ->and($request->input('brands'))->toBeArray()->toBeEmpty() - ->and($request->input('isDiscounted'))->toBeFalse() - ->and($request->input('page'))->toBe(1) - ->and($request->input('perPage'))->toBe(6); - }); - - it('merges provided values in prepareForValidation', function () { - // GIVEN - $request = new FilterProductsRequest(); - $request->initialize(); - $request->merge([ - 'ranges' => ['1', '2'], - 'tags' => ['3'], - 'brands' => ['brand1'], - 'isDiscounted' => '1', - 'page' => '2', - 'perPage' => '12', - ]); - - $reflection = new \ReflectionClass($request); - $method = $reflection->getMethod('prepareForValidation'); - $method->setAccessible(true); + $response->assertOk(); // WHEN - $method->invoke($request); + $invalidBrand = getJson(route('ajax.products.filter', ['brands' => ['unknown-brand']])); // THEN - expect($request->input('ranges'))->toBe(['1', '2']) - ->and($request->input('tags'))->toBe(['3']) - ->and($request->input('brands'))->toBe(['brand1']) - ->and($request->input('isDiscounted'))->toBeTrue() - ->and($request->input('page'))->toBe(2) - ->and($request->input('perPage'))->toBe(12); + $invalidBrand->assertUnprocessable() + ->assertJsonValidationErrors('brands.0'); }); - it('validates correct rules', function () { + it('validates filter arrays and pagination bounds', function (): void { // GIVEN - $request = new FilterProductsRequest(); - $request->initialize(); - $request->merge([ - 'search' => 'test', + $rules = new FilterProductsRequest()->rules(); + + // WHEN + $valid = Validator::make([ + 'search' => 'poulet', 'ranges' => [], 'tags' => [], 'brands' => [], 'page' => 1, 'perPage' => 10, - ]); - - // WHEN - $validator = Validator::make($request->all(), $request->rules()); - - // THEN - expect($validator->passes())->toBeTrue(); - }); - - it('fails validation on incorrect rules', function () { - // GIVEN - $request = new FilterProductsRequest(); - $request->initialize(); - $request->merge([ + ], $rules); + $invalid = Validator::make([ 'search' => '', - 'page' => 0, + 'brands' => ['unknown-brand'], + 'page' => 1, 'perPage' => 100, + ], $rules); + + // THEN + expect($valid->passes())->toBeTrue() + ->and($invalid->fails())->toBeTrue() + ->and($invalid->errors()->keys())->toContain('ranges', 'tags', 'brands.0'); + }); + + it('maps request filters and pagination into GetFoFilteredProductsQueryInput', function (): void { + // GIVEN + $request = new FilterProductsRequest(); + $request->initialize(query: [ + 'search' => 'rôti', + 'ranges' => ['1', ['nested'], '2'], + 'tags' => ['3'], + 'brands' => ['loue'], + 'isDiscounted' => '1', + 'page' => '2', + 'perPage' => '12', ]); // WHEN - $validator = Validator::make($request->all(), $request->rules()); + $input = $request->toGetFoFilteredProductsQueryInput(); // THEN - expect($validator->passes())->toBeFalse() - ->and($validator->errors()->keys())->toContain('ranges', 'tags', 'brands'); - }); - - it('returns custom attributes', function () { - // GIVEN - $request = new FilterProductsRequest(); - - // WHEN - $request->initialize(); - - // THEN - expect($request->attributes())->toBeArray() - ->and($request->attributes())->toHaveKeys([ - 'search', - 'tags', - 'ranges', - 'brands', - 'page', - 'perPage', - ]); + expect($input->search)->toBe('rôti') + ->and($input->ranges)->toBe([0 => 1, 2 => 2]) + ->and($input->tags)->toBe([3]) + ->and($input->brands)->toBe(['loue']) + ->and($input->isDiscounted)->toBeTrue() + ->and($input->pagination->pageNumber()->value())->toBe(2) + ->and($input->pagination->pageSize()->value())->toBe(12); }); }); diff --git a/tests/Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php index 0731ba49..d11dca6f 100644 --- a/tests/Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Fo\Auth; -use App\Cqs\Actions\Customers\RegisterCustomerInput; use App\Http\Requests\Fo\Auth\RegisterRequest; use App\Models\Customer; use App\Models\Employee; @@ -14,141 +13,74 @@ use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; +use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppCustomerAuthService; use Ramsey\Uuid\Uuid; use Shared\ValueObjects\CrmHashcode; -describe('RegisterRequest', function () { - it('authorizes when guest', function () { +describe('RegisterRequest', function (): void { + it('authorizes only when customer is a guest', function (): void { // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); - $authService->shouldReceive('guest')->once()->andReturn(true); + $authService->shouldReceive('guest')->twice()->andReturn(true, false); $request = new RegisterRequest($authService); - - // WHEN $request->initialize(); - // THEN - expect($request->authorize())->toBeTrue(); - }); - - it('does not authorize when not guest', function () { - // GIVEN - $authService = \Mockery::mock(AppCustomerAuthService::class); - $authService->shouldReceive('guest')->once()->andReturn(false); - - $request = new RegisterRequest($authService); - // WHEN - $request->initialize(); + $authorized = $request->authorize(); + $denied = $request->authorize(); // THEN - expect($request->authorize())->toBeFalse(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('validates rules', function () { + it('builds RegisterCustomerInput via toRegisterCustomerInput()', function (): void { // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); $request = new RegisterRequest($authService); - - // WHEN - $request->initialize(); - - // THEN - expect($request->rules())->toBeArray() - ->and($request->rules())->toHaveKeys([ - 'matricule', - 'code', - 'lastname', - 'firstname', - 'phone', - 'address', - 'postal_code', - 'city', - 'email', - 'password', - 'ok_cgv', - 'optin', - 'birth_date', - ]); - }); - - it('builds RegisterCustomerInput via toRegisterCustomerInput()', function () { - // GIVEN - $authService = \Mockery::mock(AppCustomerAuthService::class); - $request = new RegisterRequest($authService); - $request->initialize(); - $request->merge([ - 'matricule' => '1234567', - 'code' => 'ABCDEF', - 'lastname' => 'Doe', - 'firstname' => 'John', - 'postal_code' => '75000', - 'city' => 'Paris', - 'email' => 'john.doe@example.com', - 'password' => 'secret', - 'optin' => '1', - 'birth_date' => '1990-01-01', - ]); - - $reflection = new \ReflectionClass($request); - $method = $reflection->getMethod('prepareForValidation'); - $method->setAccessible(true); - $method->invoke($request); + $request->initialize( + request: [ + 'matricule' => '1234567', + 'code' => 'ABCDEF', + 'lastname' => 'Doe', + 'firstname' => 'John', + 'postal_code' => '75000', + 'city' => 'Paris', + 'email' => 'john.doe@example.com', + 'password' => 'secret', + 'optin' => '1', + 'birth_date' => '1990-01-01', + ], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN $input = $request->toRegisterCustomerInput(); // THEN - expect($input)->toBeInstanceOf(RegisterCustomerInput::class) - ->and($input->email->value)->toBe('john.doe@example.com') + expect($input->email->value)->toBe('john.doe@example.com') ->and($input->firstname)->toBe('John') ->and($input->birthDate->format('Y-m-d'))->toBe('1990-01-01') ->and($input->optIn)->toBeTrue(); }); - it('throws InvalidArgumentException for invalid birth date in toRegisterCustomerInput()', function () { + it('throws InvalidArgumentException for invalid birth date in toRegisterCustomerInput()', function (): void { // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); $request = new RegisterRequest($authService); - $request->initialize(); - $request->merge([ - 'birth_date' => 'invalid-date', - ]); + $request->initialize( + request: ['birth_date' => 'invalid-date'], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN & THEN $request->toRegisterCustomerInput(); })->throws(\InvalidArgumentException::class, 'Invalid birth date format'); - it('returns custom attributes', function () { - $authService = \Mockery::mock(AppCustomerAuthService::class); - // GIVEN - $request = new RegisterRequest($authService); - - // WHEN - $request->initialize(); - - // THEN - expect($request->attributes())->toBeArray() - ->and($request->attributes())->toHaveKeys([ - 'firstname', - 'lastname', - 'birth_date', - 'address', - 'phone', - 'city', - 'postcode', - 'password', - 'matricule', - 'code', - 'ok_cgv', - 'optin', - ]); - }); - it('rejects matricule and code when employee already has a customer_id', function (): void { // GIVEN $customer = new Customer(['email' => new Email('existing@example.com')]); @@ -168,11 +100,13 @@ describe('RegisterRequest', function () { $authService = \Mockery::mock(AppCustomerAuthService::class); $request = new RegisterRequest($authService); - $request->initialize(); - $request->merge([ - 'matricule' => '1234567', - 'code' => 'ABCDEF', - ]); + $request->initialize( + request: [ + 'matricule' => '1234567', + 'code' => 'ABCDEF', + ], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN $validator = Validator::make( @@ -203,11 +137,13 @@ describe('RegisterRequest', function () { $authService = \Mockery::mock(AppCustomerAuthService::class); $request = new RegisterRequest($authService); - $request->initialize(); - $request->merge([ - 'matricule' => '7654321', - 'code' => 'FGHJKM', - ]); + $request->initialize( + request: [ + 'matricule' => '7654321', + 'code' => 'FGHJKM', + ], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN $validator = Validator::make( @@ -253,7 +189,7 @@ describe('RegisterRequest', function () { $endedEmployee->code = new Code('FGHJK2'); $endedEmployee->nom = 'Doe'; $endedEmployee->prenom = 'Ended'; - $endedEmployee->end_date = '2026-06-15'; + $endedEmployee->end_date = Carbon::parse('2026-06-15'); $endedEmployee->etablissement = new ShopperEstablishmentCode('ETAB01'); $endedEmployee->site = new ShopperSiteCode('SITE'); $endedEmployee->service = new ShopperServiceCode('1'); @@ -264,7 +200,7 @@ describe('RegisterRequest', function () { $futureEmployee->code = new Code('FGHJK3'); $futureEmployee->nom = 'Doe'; $futureEmployee->prenom = 'Future'; - $futureEmployee->start_date = '2026-06-16'; + $futureEmployee->start_date = Carbon::parse('2026-06-16'); $futureEmployee->etablissement = new ShopperEstablishmentCode('ETAB01'); $futureEmployee->site = new ShopperSiteCode('SITE'); $futureEmployee->service = new ShopperServiceCode('1'); diff --git a/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php b/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php index 752e9e99..2f28960a 100644 --- a/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php @@ -4,10 +4,8 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Fo; -use App\Cqs\Actions\Contact\SubmitContactFormInput; use App\Http\Requests\Fo\ContactFormRequest; use Domain\Models\ValueObjects\OrderReference; -use Illuminate\Filesystem\FilesystemAdapter; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; @@ -126,8 +124,7 @@ describe('ContactFormRequest', function () { $input = $request->toSubmitContactFormInput(); // THEN - expect($input)->toBeInstanceOf(SubmitContactFormInput::class) - ->and($input->lastName)->toBe('Doe') + expect($input->lastName)->toBe('Doe') ->and($input->firstName)->toBe('John') ->and($input->email)->toBe('john.doe@gmail.com') ->and($input->subject)->toBe('Help') @@ -144,7 +141,7 @@ describe('ContactFormRequest', function () { $disk = Storage::disk('s3-private'); // THEN - expect($disk)->toBeInstanceOf(FilesystemAdapter::class); + expect($disk->getConfig())->toHaveKey('driver', 's3'); }); it('converts to action input with file', function () { @@ -166,23 +163,6 @@ describe('ContactFormRequest', function () { $input = $request->toSubmitContactFormInput(); // THEN - expect($input)->toBeInstanceOf(SubmitContactFormInput::class) - ->and($input->file)->toBe($file); - }); - - it('returns custom messages', function () { - // GIVEN - $request = new ContactFormRequest(); - - // WHEN - $request->initialize(); - - // THEN - expect($request->messages())->toBeArray() - ->and($request->messages())->toHaveKeys([ - 'ok_cgv.accepted', - 'file.max', - 'file.mimes', - ]); + expect($input->file)->toBe($file); }); }); diff --git a/tests/Feature/App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php index e7c403cd..64e1bb19 100644 --- a/tests/Feature/App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php @@ -4,79 +4,99 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Fo\Customer; -use App\Cqs\Actions\Crm\UpdateCustomerInput; use App\Http\Requests\Fo\Customer\UpdateInfosRequest; +use Illuminate\Support\Facades\Date; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppCustomerAuthService; -describe('UpdateInfosRequest', function () { - it('authorizes when user is logged in', function () { +describe('UpdateInfosRequest', function (): void { + it('authorizes only when customer auth service returns true', function (): void { // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new UpdateInfosRequest($authService); - - // WHEN $request->initialize(); + // WHEN + $authorized = $request->authorize(); + $denied = $request->authorize(); + // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('does not authorize when user is not logged in', function () { + it('validates adult birth_date, French postal code and phone with custom attributes and messages', function (): void { // GIVEN - $authService = \Mockery::mock(AppCustomerAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(false); + Date::setTestNow(Date::parse('2026-06-15 10:00:00', 'Europe/Paris')); - $request = new UpdateInfosRequest($authService); + try { + $authService = \Mockery::mock(AppCustomerAuthService::class); + $request = new UpdateInfosRequest($authService); - // WHEN - $request->initialize(); + // WHEN + $invalid = Validator::make( + [ + 'firstname' => '', + 'lastname' => 'Doe', + 'birth_date' => '2012-01-01', + 'phone' => 'invalid', + 'city' => 'Paris', + 'postcode' => 'ABCDE', + 'opt_in' => true, + ], + $request->rules(), + $request->messages(), + $request->attributes(), + ); + $valid = Validator::make( + [ + 'firstname' => 'John', + 'lastname' => 'Doe', + 'birth_date' => '1990-01-01', + 'phone' => '01 02 03 04 05', + 'city' => 'Paris', + 'postcode' => '75001', + 'opt_in' => true, + ], + $request->rules(), + $request->messages(), + $request->attributes(), + ); - // THEN - expect($request->authorize())->toBeFalse(); + // THEN + expect($invalid->errors()->keys())->toContain('firstname', 'birth_date', 'phone', 'postcode') + ->and($invalid->errors()->first('birth_date'))->toBe(trans('validation.custom.birth_date.before_or_equal')) + ->and($valid->passes())->toBeTrue(); + } finally { + Date::setTestNow(); + } }); - it('merges opt_in in prepareForValidation', function () { + it('converts request data into UpdateCustomerInput with nullable phone and address', function (): void { // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); $request = new UpdateInfosRequest($authService); - $request->initialize(); - $request->merge(['opt_in' => '1']); - - $reflection = new \ReflectionClass($request); - $method = $reflection->getMethod('prepareForValidation'); - $method->setAccessible(true); - - // WHEN - $method->invoke($request); - - // THEN - expect($request->input('opt_in'))->toBeTrue(); - }); - - it('converts to UpdateCustomerInput', function () { - // GIVEN - $authService = \Mockery::mock(AppCustomerAuthService::class); - $request = new UpdateInfosRequest($authService); - $request->initialize(); - $request->merge([ - 'firstname' => 'John', - 'lastname' => 'Doe', - 'birth_date' => '1990-01-01', - 'phone' => '0102030405', - 'city' => 'Paris', - 'postcode' => '75000', - 'address' => '123 Main St', - 'opt_in' => true, - ]); + $request->initialize( + request: [ + 'firstname' => 'John', + 'lastname' => 'Doe', + 'birth_date' => '1990-01-01', + 'phone' => '0102030405', + 'city' => 'Paris', + 'postcode' => '75000', + 'address' => '123 Main St', + 'opt_in' => '1', + ], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN $input = $request->toUpdateCustomerInput(); // THEN - expect($input)->toBeInstanceOf(UpdateCustomerInput::class) - ->and($input->firstname)->toBe('John') + expect($input->firstname)->toBe('John') ->and($input->lastname)->toBe('Doe') ->and($input->birthDate)->toBe('1990-01-01') ->and($input->phone)->toBe('0102030405') @@ -84,90 +104,29 @@ describe('UpdateInfosRequest', function () { ->and($input->postcode)->toBe('75000') ->and($input->address)->toBe('123 Main St') ->and($input->optIn)->toBeTrue(); - }); - it('converts to UpdateCustomerInput with empty address and phone as null', function () { // GIVEN - $authService = \Mockery::mock(AppCustomerAuthService::class); - $request = new UpdateInfosRequest($authService); - $request->initialize(); - $request->merge([ - 'firstname' => 'John', - 'lastname' => 'Doe', - 'birth_date' => '1990-01-01', - 'phone' => '', - 'city' => 'Paris', - 'postcode' => '75000', - 'address' => '', - 'opt_in' => false, - ]); + $emptyRequest = new UpdateInfosRequest($authService); + $emptyRequest->initialize( + request: [ + 'firstname' => 'John', + 'lastname' => 'Doe', + 'birth_date' => '1990-01-01', + 'phone' => '', + 'city' => 'Paris', + 'postcode' => '75000', + 'address' => '', + 'opt_in' => false, + ], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN - $input = $request->toUpdateCustomerInput(); + $emptyInput = $emptyRequest->toUpdateCustomerInput(); // THEN - expect($input)->toBeInstanceOf(UpdateCustomerInput::class) - ->and($input->phone)->toBeNull() - ->and($input->address)->toBeNull(); - }); - - it('validates rules', function () { - // GIVEN - $authService = \Mockery::mock(AppCustomerAuthService::class); - $request = new UpdateInfosRequest($authService); - - // WHEN - $request->initialize(); - - // THEN - expect($request->rules())->toBeArray() - ->and($request->rules())->toHaveKeys([ - 'firstname', - 'lastname', - 'birth_date', - 'address', - 'phone', - 'city', - 'postcode', - 'opt_in', - ]); - }); - - it('returns custom messages', function () { - // GIVEN - $authService = \Mockery::mock(AppCustomerAuthService::class); - $request = new UpdateInfosRequest($authService); - - // WHEN - $request->initialize(); - - // THEN - expect($request->messages())->toBeArray() - ->and($request->messages())->toHaveKeys([ - 'birth_date.before_or_equal', - 'birth_date.date', - 'birth_date.date_format', - ]); - }); - - it('returns custom attributes', function () { - // GIVEN - $authService = \Mockery::mock(AppCustomerAuthService::class); - $request = new UpdateInfosRequest($authService); - - // WHEN - $request->initialize(); - - // THEN - expect($request->attributes())->toBeArray() - ->and($request->attributes())->toHaveKeys([ - 'firstname', - 'lastname', - 'birth_date', - 'address', - 'phone', - 'city', - 'postcode', - ]); + expect($emptyInput->phone)->toBeNull() + ->and($emptyInput->address)->toBeNull() + ->and($emptyInput->optIn)->toBeFalse(); }); }); diff --git a/tests/Feature/App/Http/Requests/Fo/Customer/UpdatePasswordRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Customer/UpdatePasswordRequestTest.php index dbb75d3e..52e9c21b 100644 --- a/tests/Feature/App/Http/Requests/Fo/Customer/UpdatePasswordRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Customer/UpdatePasswordRequestTest.php @@ -5,47 +5,70 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Fo\Customer; use App\Http\Requests\Fo\Customer\UpdatePasswordRequest; +use Illuminate\Support\Facades\Http; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppCustomerAuthService; -describe('UpdatePasswordRequest', function () { - it('authorizes when user is logged in', function () { +describe('UpdatePasswordRequest', function (): void { + it('authorizes only when customer auth service returns true', function (): void { // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new UpdatePasswordRequest($authService); - - // WHEN $request->initialize(); + // WHEN + $authorized = $request->authorize(); + $denied = $request->authorize(); + // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('does not authorize when user is not logged in', function () { + it('validates old password presence and strong confirmed new password', function (): void { // GIVEN + Http::fake([ + 'api.pwnedpasswords.com/*' => Http::response('', 200), + ]); $authService = \Mockery::mock(AppCustomerAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(false); - - $request = new UpdatePasswordRequest($authService); + $rules = new UpdatePasswordRequest($authService)->rules(); // WHEN - $request->initialize(); + $invalid = Validator::make([ + 'password_old' => '', + 'password' => 'weak', + 'password_confirmation' => 'mismatch', + ], $rules); + $valid = Validator::make([ + 'password_old' => 'OldPass123!', + 'password' => 'NewStr0ng!Pass#2026', + 'password_confirmation' => 'NewStr0ng!Pass#2026', + ], $rules); // THEN - expect($request->authorize())->toBeFalse(); + expect($invalid->errors()->keys())->toContain('password_old', 'password') + ->and($valid->passes())->toBeTrue(); }); - it('validates rules', function () { + it('maps request data into UpdateCustomerPasswordInput', function (): void { // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); $request = new UpdatePasswordRequest($authService); + $request->initialize( + request: [ + 'password_old' => 'CurrentPass!1', + 'password' => 'NextPass!2026', + ], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN - $request->initialize(); + $input = $request->toUpdateCustomerPasswordInput(); // THEN - expect($request->rules())->toBeArray() - ->and($request->rules())->toHaveKeys(['password_old', 'password']); + expect($input->currentPassword)->toBe('CurrentPass!1') + ->and($input->newPassword)->toBe('NextPass!2026'); }); }); diff --git a/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php index 6e4acb0a..2e19b5ee 100644 --- a/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php @@ -4,60 +4,52 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Fo\Orders; -use App\Cqs\Actions\Orders\PlacePendingOrderInput; use App\Http\Requests\Fo\Orders\ConfirmOrderRequest; use App\Models\Customer; use Domain\Models\ValueObjects\Entities\ShopperId; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppCustomerAuthService; use Ramsey\Uuid\Uuid; -describe('ConfirmOrderRequest', function () { - it('authorizes when user is logged in', function () { +describe('ConfirmOrderRequest', function (): void { + it('authorizes only when customer auth service returns true', function (): void { // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new ConfirmOrderRequest($authService); - - // WHEN $request->initialize(); + // WHEN + $authorized = $request->authorize(); + $denied = $request->authorize(); + // THEN - expect($request->authorize())->toBeTrue(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('does not authorize when user is not logged in', function () { + it('requires cgv acceptance in validation rules', function (): void { // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(false); - - $request = new ConfirmOrderRequest($authService); + $rules = new ConfirmOrderRequest($authService)->rules(); // WHEN - $request->initialize(); + $missing = Validator::make([], $rules); + $rejected = Validator::make(['ok_cgv' => false], $rules); + $accepted = Validator::make(['ok_cgv' => true], $rules); // THEN - expect($request->authorize())->toBeFalse(); + expect($missing->errors()->has('ok_cgv'))->toBeTrue() + ->and($rejected->errors()->has('ok_cgv'))->toBeTrue() + ->and($accepted->passes())->toBeTrue(); }); - it('has required rules for cgv acceptance', function () { + it('maps to PlacePendingOrderInput', function (): void { // GIVEN - $authService = \Mockery::mock(AppCustomerAuthService::class); - $request = new ConfirmOrderRequest($authService); - - // WHEN - $rules = $request->rules(); - - // THEN - expect($rules)->toHaveKey('ok_cgv') - ->and($rules['ok_cgv'])->toContain('accepted'); - }); - - it('maps to PlacePendingOrderInput', function () { - // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); - $customer = \Mockery::mock(Customer::class); - $customer->shouldReceive('getId')->once()->andReturn($shopperId); + $shopperId = new ShopperId(Uuid::uuid7()); + $customer = new Customer(); + $customer->id = $shopperId->value->toString(); $authService = \Mockery::mock(AppCustomerAuthService::class); $authService->shouldReceive('getCustomerAsMandatory')->once()->andReturn($customer); @@ -69,7 +61,6 @@ describe('ConfirmOrderRequest', function () { $input = $request->toPlacePendingOrderInput(); // THEN - expect($input)->toBeInstanceOf(PlacePendingOrderInput::class) - ->and($input->shopperId)->toBe($shopperId); + expect($input->shopperId?->value->toString())->toBe($shopperId->value->toString()); }); }); diff --git a/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php index 226746f2..eb6b4ab2 100644 --- a/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php @@ -4,9 +4,9 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Fo\Orders; -use App\Cqs\Actions\Orders\ApplyPickTimeSlotInput; use App\Http\Requests\Fo\Orders\PickTimeSlotRequest; use App\Models\Customer; +use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Domain\Builders\OrderBuilderWithBasket; use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException; @@ -21,49 +21,35 @@ use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Ports\Repositories\ShopperRepository; use Domain\Services\OrderTunnelService; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppCustomerAuthService; use Ramsey\Uuid\Uuid; const VALID_TIMESLOT_DATE = '2023-10-15'; -describe('PickTimeSlotRequest', function () { - it('authorizes when user is logged in', function () { +describe('PickTimeSlotRequest', function (): void { + it('authorizes only when customer auth service returns true', function (): void { // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new PickTimeSlotRequest( $authService, \Mockery::mock(ShopperRepository::class), \Mockery::mock(OrderTunnelService::class), ); - - // WHEN $request->initialize(); - // THEN - expect($request->authorize())->toBeTrue(); - }); - - it('does not authorize when user is not logged in', function () { - // GIVEN - $authService = \Mockery::mock(AppCustomerAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(false); - - $request = new PickTimeSlotRequest( - $authService, - \Mockery::mock(ShopperRepository::class), - \Mockery::mock(OrderTunnelService::class), - ); - // WHEN - $request->initialize(); + $authorized = $request->authorize(); + $denied = $request->authorize(); // THEN - expect($request->authorize())->toBeFalse(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('gets timeslot successfully', function () { + it('gets timeslot successfully', function (): void { // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); $request = new PickTimeSlotRequest( @@ -71,70 +57,40 @@ describe('PickTimeSlotRequest', function () { \Mockery::mock(ShopperRepository::class), \Mockery::mock(OrderTunnelService::class), ); - $request->initialize(); - $request->merge(['timeslot' => VALID_TIMESLOT_DATE]); + $request->initialize( + request: ['timeslot' => VALID_TIMESLOT_DATE], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN $timeslot = $request->getTimeslot(); // THEN - expect($timeslot)->toBeInstanceOf(CarbonInterface::class) - ->and($timeslot->format('Y-m-d H:i:s'))->toBe(VALID_TIMESLOT_DATE . ' 00:00:00'); + expect($timeslot->format('Y-m-d H:i:s'))->toBe(VALID_TIMESLOT_DATE . ' 00:00:00'); }); - it('throws exception on invalid timeslot format', function () { + it('throws exception on invalid timeslot format', function (): void { + // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); $request = new PickTimeSlotRequest( $authService, \Mockery::mock(ShopperRepository::class), \Mockery::mock(OrderTunnelService::class), ); - $request->initialize(); - $request->merge(['timeslot' => 'invalid-date']); + $request->initialize( + request: ['timeslot' => 'invalid-date'], + server: ['REQUEST_METHOD' => 'POST'], + ); + // WHEN & THEN $request->getTimeslot(); })->throws(\InvalidArgumentException::class); - it('validates rules', function () { - $authService = \Mockery::mock(AppCustomerAuthService::class); + it('fails basketTotal validation when weekly limit is exceeded', function (): void { // GIVEN - $request = new PickTimeSlotRequest( - $authService, - \Mockery::mock(ShopperRepository::class), - \Mockery::mock(OrderTunnelService::class), - ); - - // WHEN - $request->initialize(); - - // THEN - expect($request->rules())->toBeArray() - ->and($request->rules())->toHaveKeys(['timeslot']); - }); - - it('returns custom attributes', function () { - // GIVEN - $authService = \Mockery::mock(AppCustomerAuthService::class); - $request = new PickTimeSlotRequest( - $authService, - \Mockery::mock(ShopperRepository::class), - \Mockery::mock(OrderTunnelService::class), - ); - - // WHEN - $request->initialize(); - - // THEN - expect($request->attributes())->toBeArray() - ->and($request->attributes())->toHaveKeys(['timeslot']); - }); - - it('fails basketTotal rule when weekly limit is exceeded', function () { - // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); - - $customer = \Mockery::mock(Customer::class); - $customer->shouldReceive('getId')->once()->andReturn($shopperId); + $shopperId = new ShopperId(Uuid::uuid7()); + $customer = new Customer(); + $customer->id = $shopperId->value->toString(); $basket = new Basket(new BasketId(Uuid::uuid7()), []); $shopper = new Shopper( @@ -143,7 +99,7 @@ describe('PickTimeSlotRequest', function () { new Matricule('1234567'), 'Nom', 'Prenom', - now(), + CarbonImmutable::parse('2023-10-01 10:00:00'), null, new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), @@ -157,16 +113,25 @@ describe('PickTimeSlotRequest', function () { $builder->shouldReceive('getBasket')->once()->andReturn($basket); $shopperRepository = \Mockery::mock(ShopperRepository::class); - $shopperRepository->shouldReceive('getByIdOrFail')->once()->with($shopperId)->andReturn($shopper); + $shopperRepository->shouldReceive('getByIdOrFail') + ->once() + ->withArgs(fn (ShopperId $id): bool => $id->value->toString() === $shopperId->value->toString()) + ->andReturn($shopper); $orderTunnelService = \Mockery::mock(OrderTunnelService::class); $orderTunnelService->shouldReceive('getBuilderFromBasketOrFail')->once()->andReturn($builder); $orderTunnelService->shouldReceive('assertBasketWeeklyAmountWithinLimitFor') ->once() - ->withArgs(function ($receivedShopper, $receivedBasket, $receivedDate) use ($shopper, $basket) { - return $receivedShopper === $shopper - && $receivedBasket === $basket - && $receivedDate instanceof CarbonInterface + ->withArgs(function ( + Shopper $receivedShopper, + Basket $receivedBasket, + CarbonInterface $receivedDate, + ) use ( + $shopper, + $basket, + ): bool { + return $receivedShopper === $shopper + && $receivedBasket === $basket && $receivedDate->format('Y-m-d') === VALID_TIMESLOT_DATE; }) ->andThrow(new WeeklyLimitExceededException()); @@ -176,29 +141,28 @@ describe('PickTimeSlotRequest', function () { $shopperRepository, $orderTunnelService, ); - $request->initialize(); - $request->merge(['timeslot' => VALID_TIMESLOT_DATE]); - - $rules = $request->rules(); - $basketTotalFn = $rules['basketTotal'][0]; - $failMessages = []; + $request->initialize( + request: ['timeslot' => VALID_TIMESLOT_DATE], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN - $basketTotalFn('basketTotal', 1000, function (string $message) use (&$failMessages): void { - $failMessages[] = $message; - }); + $validator = Validator::make( + ['timeslot' => VALID_TIMESLOT_DATE, 'basketTotal' => 1000], + $request->rules(), + ); // THEN - expect($failMessages)->toHaveCount(1) - ->and($failMessages[0]) + expect($validator->fails())->toBeTrue() + ->and($validator->errors()->first('basketTotal')) ->toBe(trans('You will reach the maximum weekly order limit with this basket.')); }); - it('maps to ApplyPickTimeSlotInput', function () { + it('maps to ApplyPickTimeSlotInput', function (): void { // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); - $customer = \Mockery::mock(Customer::class); - $customer->shouldReceive('getId')->once()->andReturn($shopperId); + $shopperId = new ShopperId(Uuid::uuid7()); + $customer = new Customer(); + $customer->id = $shopperId->value->toString(); $authService = \Mockery::mock(AppCustomerAuthService::class); $authService->shouldReceive('getCustomerAsMandatory')->once()->andReturn($customer); @@ -208,15 +172,16 @@ describe('PickTimeSlotRequest', function () { \Mockery::mock(ShopperRepository::class), \Mockery::mock(OrderTunnelService::class), ); - $request->initialize(); - $request->merge(['timeslot' => VALID_TIMESLOT_DATE]); + $request->initialize( + request: ['timeslot' => VALID_TIMESLOT_DATE], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN $input = $request->toApplyPickTimeSlotInput(); // THEN - expect($input)->toBeInstanceOf(ApplyPickTimeSlotInput::class) - ->and($input->shopperId)->toBe($shopperId) + expect($input->shopperId->value->toString())->toBe($shopperId->value->toString()) ->and($input->timeslot->format('Y-m-d'))->toBe(VALID_TIMESLOT_DATE); }); }); diff --git a/tests/Feature/App/Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php index 341af914..621a00f5 100644 --- a/tests/Feature/App/Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Requests\Fo\Orders; -use App\Cqs\Actions\Orders\InitializeOrderTunnelInput; use App\Http\Requests\Fo\Orders\ValidateSummaryRequest; use App\Models\Customer; use Domain\Exceptions\OrderTunnel\OrderLimitExceededException; @@ -13,47 +12,33 @@ use Domain\Models\ValueObjects\Entities\BasketId; use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Services\BasketService; use Domain\Services\OrderTunnelService; +use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppCustomerAuthService; use Ramsey\Uuid\Uuid; -describe('ValidateSummaryRequest', function () { - it('authorizes when user is logged in', function () { +describe('ValidateSummaryRequest', function (): void { + it('authorizes only when customer auth service returns true', function (): void { // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(true); + $authService->shouldReceive('check')->twice()->andReturn(true, false); $request = new ValidateSummaryRequest( $authService, \Mockery::mock(BasketService::class), \Mockery::mock(OrderTunnelService::class), ); - - // WHEN $request->initialize(); - // THEN - expect($request->authorize())->toBeTrue(); - }); - - it('does not authorize when user is not logged in', function () { - // GIVEN - $authService = \Mockery::mock(AppCustomerAuthService::class); - $authService->shouldReceive('check')->once()->andReturn(false); - - $request = new ValidateSummaryRequest( - $authService, - \Mockery::mock(BasketService::class), - \Mockery::mock(OrderTunnelService::class), - ); - // WHEN - $request->initialize(); + $authorized = $request->authorize(); + $denied = $request->authorize(); // THEN - expect($request->authorize())->toBeFalse(); + expect($authorized)->toBeTrue() + ->and($denied)->toBeFalse(); }); - it('fails basketTotal rule when order limit is exceeded', function () { + it('fails basketTotal validation when order limit is exceeded', function (): void { // GIVEN $basket = new Basket(new BasketId(Uuid::uuid7()), []); @@ -74,28 +59,23 @@ describe('ValidateSummaryRequest', function () { ); $request->initialize(); - $rules = $request->rules(); - $basketTotalFn = $rules['basketTotal'][0]; - $failMessages = []; - // WHEN - $basketTotalFn('basketTotal', 1000, function (string $message) use (&$failMessages): void { - $failMessages[] = $message; - }); + $validator = Validator::make(['basketTotal' => 1000], $request->rules()); // THEN - expect($failMessages)->toHaveCount(1) - ->and($failMessages[0])->toBe(trans('You have reached the maximum order limit for this basket.')); + expect($validator->fails())->toBeTrue() + ->and($validator->errors()->first('basketTotal')) + ->toBe(trans('You have reached the maximum order limit for this basket.')); }); - it('maps to InitializeOrderTunnelInput', function () { + it('maps to InitializeOrderTunnelInput', function (): void { // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); - $customer = \Mockery::mock(Customer::class); - $customer->shouldReceive('getId')->once()->andReturn($shopperId); + $shopperId = new ShopperId(Uuid::uuid7()); + $customer = new Customer(); + $customer->id = $shopperId->value->toString(); - $basket = new Basket(new BasketId(Uuid::uuid7()), []); - $authService = \Mockery::mock(AppCustomerAuthService::class); + $basket = new Basket(new BasketId(Uuid::uuid7()), []); + $authService = \Mockery::mock(AppCustomerAuthService::class); $authService->shouldReceive('getCustomerAsMandatory')->once()->andReturn($customer); $basketService = \Mockery::mock(BasketService::class); @@ -112,8 +92,7 @@ describe('ValidateSummaryRequest', function () { $input = $request->toInitializeOrderTunnelInput(); // THEN - expect($input)->toBeInstanceOf(InitializeOrderTunnelInput::class) - ->and($input->basket)->toBe($basket) - ->and($input->shopperId)->toBe($shopperId); + expect($input->basket)->toBe($basket) + ->and($input->shopperId->value->toString())->toBe($shopperId->value->toString()); }); }); diff --git a/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php b/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php index 468f5dcf..8749c31d 100644 --- a/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php @@ -7,7 +7,6 @@ namespace Tests\Feature\App\Http\Requests\Fo; use App\Http\Requests\Fo\UnsubscribeNewsletterRequest; use Illuminate\Support\Facades\Validator; use Ramsey\Uuid\Uuid; -use Shared\ValueObjects\CrmHashcode; describe('UnsubscribeNewsletterRequest', function () { it('validates correct rules', function () { @@ -68,7 +67,6 @@ describe('UnsubscribeNewsletterRequest', function () { $result = $request->getHashcode(); // THEN - expect($result)->toBeInstanceOf(CrmHashcode::class) - ->and($result->value)->toBe($uuid->toString()); + expect($result?->value)->toBe($uuid->toString()); }); }); diff --git a/tests/Unit/App/Policies/Frontend/OrderTunnelStepPolicyTest.php b/tests/Integration/WithApp/App/Policies/Frontend/OrderTunnelStepPolicyTest.php similarity index 99% rename from tests/Unit/App/Policies/Frontend/OrderTunnelStepPolicyTest.php rename to tests/Integration/WithApp/App/Policies/Frontend/OrderTunnelStepPolicyTest.php index 4d51cafa..cac204da 100644 --- a/tests/Unit/App/Policies/Frontend/OrderTunnelStepPolicyTest.php +++ b/tests/Integration/WithApp/App/Policies/Frontend/OrderTunnelStepPolicyTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Tests\Unit\App\Policies\Frontend; +namespace Tests\Integration\WithApp\App\Policies\Frontend; use App\Models\Customer; use App\Models\User; From c083d7403216d3767939c344acfc5cac5fe4d7db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 15:43:10 +0100 Subject: [PATCH 142/183] test(phpstan): remove all 145 redundant Pest expectations --- .../App/Services/ImageOptimizerServiceTest.php | 6 ++---- tests/Integration/WithApp/App/Casts/CodeCastTest.php | 3 +-- .../WithApp/App/Casts/DeliveryAddressCastTest.php | 6 ++---- .../WithApp/App/Casts/DiscountValueCastTest.php | 9 +++------ .../Integration/WithApp/App/Casts/EmailCastTest.php | 3 +-- .../WithApp/App/Casts/MatriculeCastTest.php | 3 +-- .../Integration/WithApp/App/Casts/MoneyCastTest.php | 6 ++---- .../WithApp/App/Casts/NutritionalValuesCastTest.php | 9 +++------ .../WithApp/App/Casts/OrderEmployeeCastTest.php | 4 ---- .../WithApp/App/Casts/OrderLineProductCastTest.php | 6 ++---- .../WithApp/App/Casts/OrderReferenceCastTest.php | 6 ++---- .../App/Casts/ShopperEstablishmentCodeCastTest.php | 3 +-- .../WithApp/App/Casts/ShopperServiceCodeCastTest.php | 3 +-- .../WithApp/App/Casts/ShopperSiteCodeCastTest.php | 3 +-- .../Cqs/Actions/Auth/ResetCustomerPasswordTest.php | 4 +--- .../Cqs/Actions/Contact/SubmitContactFormTest.php | 7 ++----- .../Cqs/Actions/Crm/UpdateCustomerPasswordTest.php | 4 +--- .../App/Cqs/Actions/Crm/UpdateCustomerTest.php | 4 +--- .../Cqs/Actions/Customers/RegisterCustomerTest.php | 7 ++----- .../App/Cqs/Actions/Discounts/CreateDiscountTest.php | 6 ++---- .../WithApp/App/Cqs/Actions/Faqs/CreateFaqTest.php | 4 +--- .../App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php | 4 +--- .../PickupExceptions/CreatePickupExceptionTest.php | 3 +-- .../ProductIncos/AssociateProductIncoTest.php | 4 +--- .../Cqs/Actions/ProductIncos/SyncProductIncoTest.php | 4 +--- .../App/Cqs/Actions/Products/CreateProductTest.php | 3 +-- .../App/Cqs/Actions/Ranges/CreateRangeTest.php | 3 +-- .../App/Cqs/Actions/Settings/UpdateSettingsTest.php | 3 +-- .../WithApp/App/Cqs/Actions/Shops/CreateShopTest.php | 4 +--- .../App/Cqs/Actions/Slides/CreateSlideTest.php | 3 +-- .../WithApp/App/Cqs/Actions/Tags/CreateTagTest.php | 4 +--- .../WithApp/App/Cqs/Actions/Users/CreateUserTest.php | 3 +-- .../Discounts/GetPaginatedDiscountsQueryTest.php | 5 +---- .../App/Cqs/Queries/Faqs/GetFaqsQueryTest.php | 4 +--- .../Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php | 3 --- .../Orders/GetTunnelOrderConfirmedQueryTest.php | 11 ++--------- .../App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php | 7 ++----- .../GetPaginatedPickupExceptionsQueryTest.php | 8 ++------ .../ProductIncos/GetProductIncoForEditQueryTest.php | 10 ++-------- .../Queries/Products/GetProductFormDataQueryTest.php | 7 ++----- .../Queries/Ranges/GetPaginatedRangesQueryTest.php | 5 +---- .../Cqs/Queries/Settings/GetSettingsQueryTest.php | 4 +--- .../Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php | 6 +----- .../Shops/GetShopPickupExceptionsQueryTest.php | 7 +------ .../App/Cqs/Queries/Shops/GetShopQueryTest.php | 4 +--- .../Queries/Slides/GetPaginatedSlidesQueryTest.php | 4 +--- .../WithApp/App/Models/ProductIncoTest.php | 4 +--- .../App/Services/EmployeeUpsertServiceTest.php | 4 ++-- .../App/Services/PublicHolidaysApiServiceTest.php | 4 ---- .../Directories/EloquentShopDirectoryTest.php | 3 +-- .../EloquentPickupExceptionRepositoryTest.php | 5 ----- .../Repositories/EloquentProductRepositoryTest.php | 4 +--- .../Repositories/EloquentShopperRepositoryTest.php | 3 ++- .../Repositories/SessionBasketRepositoryTest.php | 3 +-- .../Adapters/Services/AppAdminAuthServiceTest.php | 4 ++-- .../Adapters/Services/AppCustomerAuthServiceTest.php | 3 ++- .../App/Cqs/Actions/Employee/ImportEmployeesTest.php | 4 +--- .../App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php | 7 ++----- .../App/Cqs/Actions/Orders/PlacePendingOrderTest.php | 6 ++---- .../Cqs/Queries/Orders/GetBasketSummaryQueryTest.php | 4 +--- .../Queries/Orders/GetOrderConfirmationQueryTest.php | 6 +----- .../Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php | 5 +---- .../ProductIncos/GetArcadiaIncoPreviewQueryTest.php | 10 +++------- tests/Unit/App/Dto/SettingDtoTest.php | 2 -- .../Unit/App/Services/CodeGenerationServiceTest.php | 3 +-- .../Unit/App/Services/EmployeeCsvImportLineTest.php | 3 +-- .../App/Services/EmployeeCsvReaderServiceTest.php | 1 - tests/Unit/App/Services/IcsGeneratorServiceTest.php | 10 +++------- tests/Unit/Domain/Enums/CountryTest.php | 2 +- .../Unit/Domain/Events/BasketHasBeenModifiedTest.php | 4 +--- tests/Unit/Domain/Events/BasketRemovedTest.php | 4 +--- tests/Unit/Domain/Models/Entities/OrderTest.php | 9 +++------ tests/Unit/Domain/Models/Entities/ProductTest.php | 4 +--- .../Domain/Models/ValueObjects/AttachedFileTest.php | 4 +++- .../Domain/Models/ValueObjects/BasketProductTest.php | 4 +++- tests/Unit/Domain/Models/ValueObjects/CodeTest.php | 3 +-- .../Models/ValueObjects/ContactFormDataTest.php | 5 ++++- tests/Unit/Domain/Models/ValueObjects/EmailTest.php | 2 +- tests/Unit/Domain/Models/ValueObjects/IncoIdTest.php | 2 +- .../Domain/Models/ValueObjects/MatriculeTest.php | 3 +-- .../Models/ValueObjects/NutritionalValuesTest.php | 4 ++-- .../Models/ValueObjects/OrderReferenceTest.php | 12 ++++-------- .../Models/ValueObjects/PickupTimeSlotTest.php | 7 ++++--- .../Models/ValueObjects/ProductPricingTest.php | 3 ++- .../Domain/Models/ValueObjects/ProductWeightTest.php | 4 +--- tests/Unit/Domain/Services/BasketServiceTest.php | 3 +-- tests/Unit/Domain/Services/OrderServiceTest.php | 1 - .../Unit/Domain/Services/OrderTunnelServiceTest.php | 8 +++----- .../Domain/Services/PickupSchedulingServiceTest.php | 7 ++----- 89 files changed, 129 insertions(+), 293 deletions(-) diff --git a/tests/Integration/Standalones/App/Services/ImageOptimizerServiceTest.php b/tests/Integration/Standalones/App/Services/ImageOptimizerServiceTest.php index 8f089dec..876aaeec 100644 --- a/tests/Integration/Standalones/App/Services/ImageOptimizerServiceTest.php +++ b/tests/Integration/Standalones/App/Services/ImageOptimizerServiceTest.php @@ -29,8 +29,7 @@ describe('ImageOptimizerService', function (): void { $content = $optimized->fread(16); // THEN - expect($optimized)->toBeInstanceOf(\SplFileObject::class) - ->and($path)->not->toBeFalse() + expect($path)->not->toBeFalse() ->and(file_exists($path))->toBeTrue() ->and(pathinfo($path, PATHINFO_EXTENSION))->toBe('jpg') ->and($content)->toBeString(); @@ -48,8 +47,7 @@ describe('ImageOptimizerService', function (): void { $content = $result->fread(16); // THEN - expect($result)->toBeInstanceOf(\SplFileObject::class) - ->and($path)->not->toBeFalse() + expect($path)->not->toBeFalse() ->and(file_exists($path))->toBeTrue() ->and(pathinfo($path, PATHINFO_EXTENSION))->toBe('pdf') ->and($content)->toBeString(); diff --git a/tests/Integration/WithApp/App/Casts/CodeCastTest.php b/tests/Integration/WithApp/App/Casts/CodeCastTest.php index 56d26ce1..d81d6fb1 100644 --- a/tests/Integration/WithApp/App/Casts/CodeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/CodeCastTest.php @@ -17,8 +17,7 @@ it('gets a code', function () { $code = $cast->get($model, 'code', 'ABCDEFGH', []); // THEN - expect($code)->toBeInstanceOf(Code::class) - ->and($code->value)->toBe('ABCDEFGH'); + expect($code->value)->toBe('ABCDEFGH'); }); it('throws exception when getting null code', function () { diff --git a/tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php b/tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php index 64177cf1..9f2c35b3 100644 --- a/tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php +++ b/tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php @@ -17,8 +17,7 @@ it('gets a default delivery address when value is null', function () { $address = $cast->get($model, 'address', null, []); // THEN - expect($address)->toBeInstanceOf(DeliveryAddress::class) - ->and($address->name)->toBe('Non renseigné') + expect($address->name)->toBe('Non renseigné') ->and($address->address)->toBe('Non renseigné') ->and($address->postcode)->toBe('00000') ->and($address->city)->toBe('Non renseigné'); @@ -54,8 +53,7 @@ it('gets a delivery address from json string', function () { $address = $cast->get($model, 'address', $json, []); // THEN - expect($address)->toBeInstanceOf(DeliveryAddress::class) - ->and($address->name)->toBe('John') + expect($address->name)->toBe('John') ->and($address->address)->toBe('123 Street') ->and($address->postcode)->toBe('12345') ->and($address->city)->toBe('City') diff --git a/tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php b/tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php index 897cfef9..82e1be2a 100644 --- a/tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php +++ b/tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php @@ -25,8 +25,7 @@ it('gets a discount value from percentage', function () { ); // THEN - expect($value)->toBeInstanceOf(DiscountValue::class) - ->and($value->value())->toBe(10); + expect($value->value())->toBe(10); }); it('gets a discount value from amount', function () { @@ -43,8 +42,7 @@ it('gets a discount value from amount', function () { ); // THEN - expect($value)->toBeInstanceOf(DiscountValue::class) - ->and($value->value())->toBeInstanceOf(Money::class) + expect($value->value())->toBeInstanceOf(Money::class) ->and($value->value()->getAmount())->toBe('1000'); }); @@ -62,8 +60,7 @@ it('gets a discount value from amount string', function () { ); // THEN - expect($value)->toBeInstanceOf(DiscountValue::class) - ->and($value->value())->toBeInstanceOf(Money::class) + expect($value->value())->toBeInstanceOf(Money::class) ->and($value->value()->getAmount())->toBe('1000'); }); diff --git a/tests/Integration/WithApp/App/Casts/EmailCastTest.php b/tests/Integration/WithApp/App/Casts/EmailCastTest.php index 17bea089..36699d84 100644 --- a/tests/Integration/WithApp/App/Casts/EmailCastTest.php +++ b/tests/Integration/WithApp/App/Casts/EmailCastTest.php @@ -17,8 +17,7 @@ it('gets an email', function () { $email = $cast->get($model, 'email', 'test@example.com', []); // THEN - expect($email)->toBeInstanceOf(Email::class) - ->and($email->value)->toBe('test@example.com'); + expect($email->value)->toBe('test@example.com'); }); it('throws exception when getting invalid email', function () { diff --git a/tests/Integration/WithApp/App/Casts/MatriculeCastTest.php b/tests/Integration/WithApp/App/Casts/MatriculeCastTest.php index ee3d97e9..e2ef6690 100644 --- a/tests/Integration/WithApp/App/Casts/MatriculeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/MatriculeCastTest.php @@ -17,8 +17,7 @@ it('gets a matricule', function () { $matricule = $cast->get($model, 'matricule', '1234567', []); // THEN - expect($matricule)->toBeInstanceOf(Matricule::class) - ->and($matricule->value)->toBe('1234567'); + expect($matricule->value)->toBe('1234567'); }); it('throws exception when getting invalid matricule', function () { diff --git a/tests/Integration/WithApp/App/Casts/MoneyCastTest.php b/tests/Integration/WithApp/App/Casts/MoneyCastTest.php index 7d6fb15b..c5ebfa9f 100644 --- a/tests/Integration/WithApp/App/Casts/MoneyCastTest.php +++ b/tests/Integration/WithApp/App/Casts/MoneyCastTest.php @@ -18,8 +18,7 @@ it('gets a money from string', function () { $money = $cast->get($model, 'price', '1000', []); // THEN - expect($money)->toBeInstanceOf(Money::class) - ->and($money->getAmount())->toBe('1000') + expect($money->getAmount())->toBe('1000') ->and($money->getCurrency()->getCode())->toBe('EUR'); }); @@ -32,8 +31,7 @@ it('gets a money from int', function () { $money = $cast->get($model, 'price', 1000, []); // THEN - expect($money)->toBeInstanceOf(Money::class) - ->and($money->getAmount())->toBe('1000'); + expect($money->getAmount())->toBe('1000'); }); it('throws exception when getting invalid money type', function () { diff --git a/tests/Integration/WithApp/App/Casts/NutritionalValuesCastTest.php b/tests/Integration/WithApp/App/Casts/NutritionalValuesCastTest.php index fe24b79f..b543af29 100644 --- a/tests/Integration/WithApp/App/Casts/NutritionalValuesCastTest.php +++ b/tests/Integration/WithApp/App/Casts/NutritionalValuesCastTest.php @@ -21,8 +21,7 @@ it('gets nutritional values', function () { ]); // THEN - expect($values)->toBeInstanceOf(NutritionalValues::class) - ->and($values->refWeightG)->toBe(100.5) + expect($values->refWeightG)->toBe(100.5) ->and($values->kj)->toBe(200.0) ->and($values->kcal)->toBeNull(); }); @@ -53,8 +52,7 @@ it('sets nutritional values', function () { $array = $cast->set($model, 'nutritional', $values, []); // THEN - expect($array)->toBeArray() - ->and($array['nv_ref_weight_g'])->toBe(100.5) + expect($array['nv_ref_weight_g'])->toBe(100.5) ->and($array['nv_kj'])->toBe(200.0); }); @@ -67,8 +65,7 @@ it('sets default when null', function () { $array = $cast->set($model, 'nutritional', null, []); // THEN - expect($array)->toBeArray() - ->and($array['nv_ref_weight_g'])->toBeNull(); + expect($array['nv_ref_weight_g'])->toBeNull(); }); it('throws exception when setting invalid type', function () { diff --git a/tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php b/tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php index cc391254..a68e7cc8 100644 --- a/tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php @@ -58,15 +58,11 @@ it('gets an order employee from json string', function () { // THEN expect($employee)->toBeInstanceOf(OrderEmployee::class) - ->and($employee->matricule)->toBeInstanceOf(Matricule::class) ->and($employee->matricule->value)->toBe('1234567') ->and($employee->firstname)->toBe('John') ->and($employee->lastname)->toBe('Doe') - ->and($employee->facility)->toBeInstanceOf(ShopperEstablishmentCode::class) ->and($employee->facility->value)->toBe('FAC01') - ->and($employee->site)->toBeInstanceOf(ShopperSiteCode::class) ->and($employee->site->value)->toBe('SITE') - ->and($employee->service)->toBeInstanceOf(ShopperServiceCode::class) ->and($employee->service->value)->toBe('101'); }); diff --git a/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php b/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php index c0c88ead..1c0264cc 100644 --- a/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php +++ b/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php @@ -70,8 +70,7 @@ describe('OrderLineProductCast', function () { $product = $cast->get($model, 'product', $json, []); // THEN - expect($product)->toBeInstanceOf(OrderLineProduct::class) - ->and($product->incoId->value)->toBe(123) + expect($product->incoId->value)->toBe(123) ->and($product->originalId->value->toString())->toBe($uuid) ->and($product->name)->toBe('Product Name') ->and($product->weight->value)->toBe(1000) @@ -106,8 +105,7 @@ describe('OrderLineProductCast', function () { $product = $cast->get($model, 'product', $json, []); // THEN - expect($product)->toBeInstanceOf(OrderLineProduct::class) - ->and($product->taxRate)->toBe(TaxRate::TVA_20) + expect($product->taxRate)->toBe(TaxRate::TVA_20) ->and($product->picture)->toBeNull(); }); diff --git a/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php b/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php index 894407db..9b43bd18 100644 --- a/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php +++ b/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php @@ -21,8 +21,7 @@ it('gets a reference', function () { $reference = $cast->get($model, 'reference', $value, []); // THEN - expect($reference)->toBeInstanceOf(OrderReference::class) - ->and((string) $reference)->toBe($value) + expect((string) $reference)->toBe($value) ->and($reference->value->equals($uuid))->toBeTrue(); }); @@ -37,8 +36,7 @@ it('gets a reference from raw uuid string', function () { $reference = $cast->get($model, 'reference', $value, []); // THEN - expect($reference)->toBeInstanceOf(OrderReference::class) - ->and((string) $reference)->toBe(UuidHelper::toBase58($uuid)) + expect((string) $reference)->toBe(UuidHelper::toBase58($uuid)) ->and($reference->value->equals($uuid))->toBeTrue(); }); diff --git a/tests/Integration/WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php b/tests/Integration/WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php index 3a4b5704..d3db47dd 100644 --- a/tests/Integration/WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php @@ -17,8 +17,7 @@ it('gets a ShopperEstablishmentCode', function () { $code = $cast->get($model, 'etablissement', 'ETAB01', []); // THEN - expect($code)->toBeInstanceOf(ShopperEstablishmentCode::class) - ->and($code->value)->toBe('ETAB01'); + expect($code->value)->toBe('ETAB01'); }); it('throws exception when getting invalid ShopperEstablishmentCode type', function () { diff --git a/tests/Integration/WithApp/App/Casts/ShopperServiceCodeCastTest.php b/tests/Integration/WithApp/App/Casts/ShopperServiceCodeCastTest.php index d9a94f52..b2553984 100644 --- a/tests/Integration/WithApp/App/Casts/ShopperServiceCodeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/ShopperServiceCodeCastTest.php @@ -17,8 +17,7 @@ it('gets a ShopperServiceCode', function () { $code = $cast->get($model, 'service', '101', []); // THEN - expect($code)->toBeInstanceOf(ShopperServiceCode::class) - ->and($code->value)->toBe('101'); + expect($code->value)->toBe('101'); }); it('throws exception when getting invalid ShopperServiceCode type', function () { diff --git a/tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php b/tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php index e40523a3..4f3155fb 100644 --- a/tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php @@ -17,8 +17,7 @@ it('gets a ShopperSiteCode', function () { $code = $cast->get($model, 'site', 'PA', []); // THEN - expect($code)->toBeInstanceOf(ShopperSiteCode::class) - ->and($code->value)->toBe('PA'); + expect($code->value)->toBe('PA'); }); it('throws exception when getting invalid ShopperSiteCode type', function () { diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php index 0f000e4e..c5816b62 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php @@ -6,7 +6,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Actions\Auth; use App\Cqs\Actions\Auth\ResetCustomerPassword; use App\Cqs\Actions\Auth\ResetCustomerPasswordInput; -use App\Cqs\Actions\Auth\ResetCustomerPasswordOutput; use App\Enums\ResetCustomerPasswordStatus; use App\Models\Customer; use Carbon\CarbonImmutable; @@ -67,8 +66,7 @@ describe('ResetCustomerPassword action', function (): void { $output = $action($input); // THEN - expect($output)->toBeInstanceOf(ResetCustomerPasswordOutput::class) - ->and($output->status)->toBe(ResetCustomerPasswordStatus::SUCCESS) + expect($output->status)->toBe(ResetCustomerPasswordStatus::SUCCESS) ->and($output->emailVerified)->toBeTrue() ->and($customer->fresh()?->getRememberToken())->not->toBeNull(); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php index f53acd16..4e3a860f 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php @@ -9,7 +9,6 @@ use App\Cqs\Actions\Contact\SubmitContactForm; use App\Cqs\Actions\Contact\SubmitContactFormInput; use App\Lib\PrivateS3Disk; use Domain\Models\ValueObjects\AttachedFile; -use Domain\Models\ValueObjects\ContactFormData; use Domain\Models\ValueObjects\OrderReference; use Illuminate\Http\UploadedFile; use Ramsey\Uuid\Uuid; @@ -37,8 +36,7 @@ describe('SubmitContactForm action', function (): void { $result = $action($input); // THEN - expect($result)->toBeInstanceOf(ContactFormData::class) - ->and($result->lastName)->toBe('Doe') + expect($result->lastName)->toBe('Doe') ->and($result->firstName)->toBe('John') ->and($result->email)->toBe('john.doe@example.com') ->and($result->subject)->toBe('Question') @@ -72,8 +70,7 @@ describe('SubmitContactForm action', function (): void { $result = $action($input); // THEN - expect($result)->toBeInstanceOf(ContactFormData::class) - ->and($result->file)->toBeInstanceOf(AttachedFile::class) + expect($result->file)->toBeInstanceOf(AttachedFile::class) ->and($result->file?->path)->toBe('contact-attachments/document.pdf') ->and($result->file?->originalName)->toBe('document.pdf') ->and($result->file?->mimeType)->toBe('application/pdf'); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php index 54fd18d6..f9c30262 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php @@ -6,7 +6,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Actions\Crm; use App\Cqs\Actions\Crm\UpdateCustomerPassword; use App\Cqs\Actions\Crm\UpdateCustomerPasswordInput; -use App\Cqs\Actions\Crm\UpdateCustomerPasswordOutput; use App\Models\Customer; use App\Services\CrmService; use Domain\Enums\Country; @@ -75,8 +74,7 @@ describe('UpdateCustomerPassword action', function (): void { $output = $action(new UpdateCustomerPasswordInput('OldPass123!', 'NewPass456!')); // THEN - expect($output)->toBeInstanceOf(UpdateCustomerPasswordOutput::class) - ->and($output->result)->toBe($crmCustomer); + expect($output->result)->toBe($crmCustomer); }); it('returns false output when customer cannot be resolved in CRM', function (): void { diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php index 83a4153e..5d6e7bb8 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php @@ -6,7 +6,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Actions\Crm; use App\Cqs\Actions\Crm\UpdateCustomer; use App\Cqs\Actions\Crm\UpdateCustomerInput; -use App\Cqs\Actions\Crm\UpdateCustomerOutput; use App\Models\Customer; use App\Services\CrmService; use Domain\Enums\Country; @@ -95,8 +94,7 @@ describe('UpdateCustomer action', function (): void { $output = $action($input); // THEN - expect($output)->toBeInstanceOf(UpdateCustomerOutput::class) - ->and($output->result)->toBe($expectedCrmCustomer); + expect($output->result)->toBe($expectedCrmCustomer); }); it('omits nullable phone and address when null and propagates validation exceptions', function (): void { diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php index 4a133b7b..d8e4b0fd 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php @@ -8,7 +8,6 @@ use App\Contracts\ActionInput; use App\Contracts\Executor; use App\Cqs\Actions\Customers\RegisterCustomer; use App\Cqs\Actions\Customers\RegisterCustomerInput; -use App\Cqs\Actions\Customers\RegisterCustomerOutput; use App\Enums\RegisterCustomerStatus; use App\Exceptions\Crm\CrmCustomerExistsException; use App\Exceptions\CrmServiceException; @@ -120,8 +119,7 @@ describe('RegisterCustomer action', function (): void { $result = $action($input); // THEN: __invoke defers email verification and login to onSuccess() - expect($result)->toBeInstanceOf(RegisterCustomerOutput::class) - ->and($result->status)->toBe(RegisterCustomerStatus::SUCCESS) + expect($result->status)->toBe(RegisterCustomerStatus::SUCCESS) ->and($result->customer)->toBeInstanceOf(Customer::class) ->and($result->customer?->email->value)->toBe('john.doe@example.com') ->and($result->customer?->hashcode->value)->toBe($crmReturnedHashcode); @@ -185,8 +183,7 @@ describe('RegisterCustomer action', function (): void { $result = $action($input); // THEN - expect($result)->toBeInstanceOf(RegisterCustomerOutput::class) - ->and($result->status)->toBe(RegisterCustomerStatus::EMPLOYEE_ALREADY_REGISTERED) + expect($result->status)->toBe(RegisterCustomerStatus::EMPLOYEE_ALREADY_REGISTERED) ->and($result->customer)->toBeNull() ->and(Customer::query()->count())->toBe(1); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Discounts/CreateDiscountTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Discounts/CreateDiscountTest.php index 737057fd..c176d33f 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Discounts/CreateDiscountTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Discounts/CreateDiscountTest.php @@ -81,8 +81,7 @@ describe('CreateDiscount action', function (): void { $discount = $action($input); // THEN - expect($discount)->toBeInstanceOf(Discount::class) - ->and($discount->id)->toBeGreaterThan(0) + expect($discount->id)->toBeGreaterThan(0) ->and($discount->type)->toBe(DiscountType::PERCENT) ->and($discount->is_old_price_displayed)->toBeTrue() ->and($discount->value->getPercentage())->toBe(20); @@ -112,8 +111,7 @@ describe('CreateDiscount action', function (): void { $discount = $action($input); // THEN - expect($discount)->toBeInstanceOf(Discount::class) - ->and($discount->id)->toBeGreaterThan(0) + expect($discount->id)->toBeGreaterThan(0) ->and($discount->type)->toBe(DiscountType::AMOUNT) ->and($discount->is_old_price_displayed)->toBeFalse(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Faqs/CreateFaqTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Faqs/CreateFaqTest.php index 0c42dc20..9b585feb 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Faqs/CreateFaqTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Faqs/CreateFaqTest.php @@ -22,9 +22,7 @@ describe('CreateFaq action', function (): void { $faq = $action($input); // THEN - expect($faq)->toBeInstanceOf(Faq::class) - ->and($faq->id)->toBeInt() - ->and($faq->question)->toBe('Comment contacter le support ?') + expect($faq->question)->toBe('Comment contacter le support ?') ->and($faq->answer)->toBe('Via notre formulaire de contact en ligne.'); $fresh = Faq::query()->find($faq->id); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php index 5b486cd1..b0c79da8 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php @@ -6,7 +6,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Actions\Orders; use App\Cqs\Actions\Orders\ApplyPickTimeSlot; use App\Cqs\Actions\Orders\ApplyPickTimeSlotInput; -use App\Cqs\Actions\Orders\ApplyPickTimeSlotOutput; use App\Enums\ApplyPickTimeSlotStatus; use App\Models\Customer; use App\Models\Employee; @@ -151,8 +150,7 @@ describe('ApplyPickTimeSlot action', function (): void { $output = $action(new ApplyPickTimeSlotInput($customer->getId(), $targetFriday)); // THEN - expect($output)->toBeInstanceOf(ApplyPickTimeSlotOutput::class) - ->and($output->status)->toBe(ApplyPickTimeSlotStatus::MATCHED) + expect($output->status)->toBe(ApplyPickTimeSlotStatus::MATCHED) ->and($output->timeSlot)->not->toBeNull() ->and($output->timeSlot?->getAt()->format('Y-m-d'))->toBe('2026-11-20'); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php index 96789a70..a608d727 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php @@ -28,8 +28,7 @@ describe('CreatePickupException action', function () { $pickupException = $action($input); // THEN - expect($pickupException)->toBeInstanceOf(PickupException::class) - ->and($pickupException->date->format('Y-m-d'))->toBe('2026-05-01') + expect($pickupException->date->format('Y-m-d'))->toBe('2026-05-01') ->and($pickupException->label)->toBe('1er Mai') ->and($pickupException->repeatable)->toBeTrue() ->and($pickupException->repeat_frequency)->toBe(RepeatFrequency::YEARLY) diff --git a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php index 375748c6..dc21993c 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php @@ -7,7 +7,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Actions\ProductIncos; use App\Contracts\ActionInput; use App\Cqs\Actions\ProductIncos\AssociateProductInco; use App\Cqs\Actions\ProductIncos\AssociateProductIncoInput; -use App\Cqs\Actions\ProductIncos\AssociateProductIncoOutput; use App\Dto\ArcadiaIncoDataDto; use App\Enums\ProductIncoSyncStatus; use App\Models\Product; @@ -91,8 +90,7 @@ describe('AssociateProductInco action', function (): void { $output = $action($input); // THEN - expect($output)->toBeInstanceOf(AssociateProductIncoOutput::class) - ->and($output->status)->toBe(ProductIncoSyncStatus::SUCCESS) + expect($output->status)->toBe(ProductIncoSyncStatus::SUCCESS) ->and($output->inco)->toBeInstanceOf(ProductInco::class) ->and($output->inco?->product_id)->toBe($product->id) ->and($output->inco?->no_art)->toBe(27996) diff --git a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php index 21e9b7ec..be4bcb85 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php @@ -6,7 +6,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Actions\ProductIncos; use App\Cqs\Actions\ProductIncos\SyncProductInco; use App\Cqs\Actions\ProductIncos\SyncProductIncoInput; -use App\Cqs\Actions\ProductIncos\SyncProductIncoOutput; use App\Dto\ArcadiaIncoDataDto; use App\Enums\ProductIncoSyncStatus; use App\Models\Product; @@ -93,8 +92,7 @@ describe('SyncProductInco action', function (): void { $output = $action($input); // THEN - expect($output)->toBeInstanceOf(SyncProductIncoOutput::class) - ->and($output->status)->toBe(ProductIncoSyncStatus::SUCCESS) + expect($output->status)->toBe(ProductIncoSyncStatus::SUCCESS) ->and($output->inco?->ingredients)->toBe('

MAJ

'); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php index e3bf8a93..d97e3da7 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php @@ -154,8 +154,7 @@ describe('CreateProduct action', function (): void { $product = $executor->execute($action, $input); // THEN - expect($product)->toBeInstanceOf(Product::class) - ->and($product->name)->toBe('Poulet Fermier Bio') + expect($product->name)->toBe('Poulet Fermier Bio') ->and($product->price->getAmount())->toBe('1990') ->and($product->stock)->toBe(15) ->and($product->weight)->toBe(1400) diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php index 1324051b..6ce58774 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php @@ -49,8 +49,7 @@ describe('CreateRange action', function () { $range = $action($input); // THEN - expect($range)->toBeInstanceOf(Range::class) - ->and($range->name)->toBe('Gamme Décoration') + expect($range->name)->toBe('Gamme Décoration') ->and($range->slug)->toBe('gamme-decoration') ->and($range->description)->toBe('

Une superbe gamme

') ->and($range->picture_alt)->toBe('Image alt range') diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php index bb3bb536..f39c80c0 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php @@ -27,8 +27,7 @@ describe('UpdateSettings', function (): void { $setting = $action($input); // THEN - expect($setting)->toBeInstanceOf(Setting::class) - ->and($setting->employee_sites)->toBe(['PA', 'LY']); + expect($setting->employee_sites)->toBe(['PA', 'LY']); $this->assertDatabaseHas('settings', [ 'id' => Setting::SINGLETON_ID, diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php index eb8b9b04..79915c6f 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php @@ -8,7 +8,6 @@ use App\Contracts\ActionInput; use App\Cqs\Actions\Shops\CreateShop; use App\Cqs\Actions\Shops\CreateShopInput; use App\Models\PickupException; -use App\Models\Shop; use Domain\Enums\RepeatFrequency; use Domain\Models\ValueObjects\Coordinates; use Domain\Models\ValueObjects\PhoneNumber; @@ -36,8 +35,7 @@ describe('CreateShop action', function () { $shop = $action($input); // THEN - expect($shop)->toBeInstanceOf(Shop::class) - ->and($shop->name)->toBe('Boutique Bastille') + expect($shop->name)->toBe('Boutique Bastille') ->and($shop->address)->toBe('5 Place de la Bastille') ->and($shop->postcode)->toBe('75011') ->and($shop->city)->toBe('Paris') diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Slides/CreateSlideTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Slides/CreateSlideTest.php index 55aedd1f..0d5f8f41 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Slides/CreateSlideTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Slides/CreateSlideTest.php @@ -44,8 +44,7 @@ describe('CreateSlide action', function (): void { $slide = $action($input); // THEN - expect($slide)->toBeInstanceOf(Slide::class) - ->and($slide->id)->toBeGreaterThan(0) + expect($slide->id)->toBeGreaterThan(0) ->and($slide->title)->toBe('Nouvelle Bannière') ->and($slide->text)->toBe('

Contenu promo

') ->and($slide->link)->toBe('https://example.com/promo') diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Tags/CreateTagTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Tags/CreateTagTest.php index dc8be7cd..570f5efb 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Tags/CreateTagTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Tags/CreateTagTest.php @@ -19,9 +19,7 @@ describe('CreateTag action', function (): void { $tag = $action($input); // THEN - expect($tag)->toBeInstanceOf(Tag::class) - ->and($tag->id)->toBeInt() - ->and($tag->label)->toBe('Offre Spéciale') + expect($tag->label)->toBe('Offre Spéciale') ->and($tag->status)->toBeTrue(); $fresh = Tag::query()->find($tag->id); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Users/CreateUserTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Users/CreateUserTest.php index aee214b2..da186dbc 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Users/CreateUserTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Users/CreateUserTest.php @@ -27,8 +27,7 @@ describe('CreateUser action', function (): void { $user = $action($input); // THEN - expect($user)->toBeInstanceOf(User::class) - ->and($user->firstname)->toBe('Jean') + expect($user->firstname)->toBe('Jean') ->and($user->lastname)->toBe('Dupont') ->and($user->email)->toBe('jean.dupont@ldc.fr') ->and($user->role)->toBe(UserRole::Admin) diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Discounts/GetPaginatedDiscountsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Discounts/GetPaginatedDiscountsQueryTest.php index 9c3e00a8..2eab9eea 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Discounts/GetPaginatedDiscountsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Discounts/GetPaginatedDiscountsQueryTest.php @@ -7,7 +7,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Queries\Discounts; use App\Contracts\QueryInput; use App\Cqs\Queries\Discounts\GetPaginatedDiscountsQuery; use App\Cqs\Queries\Discounts\GetPaginatedDiscountsQueryInput; -use App\Dto\DiscountDto; use App\Models\Discount; use App\Services\DataTableService; use Domain\Enums\DiscountType; @@ -55,9 +54,7 @@ describe('GetPaginatedDiscountsQuery', function (): void { // THEN expect($paginator->total())->toBe(2) - ->and($paginator->items())->toHaveCount(2) - ->and($paginator->items()[0])->toBeInstanceOf(DiscountDto::class) - ->and($paginator->items()[1])->toBeInstanceOf(DiscountDto::class); + ->and($paginator->items())->toHaveCount(2); }); it('throws when an invalid input is passed', function (): void { diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php index ff3dca27..83f145ca 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php @@ -9,7 +9,6 @@ use App\Cqs\Queries\Faqs\GetFaqsQuery; use App\Dto\FaqDto; use App\Models\Faq; use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Support\Collection; uses(RefreshDatabase::class); @@ -34,8 +33,7 @@ describe('GetFaqsQuery', function (): void { $faqs = $query(new QueryInputEmpty()); // THEN - expect($faqs)->toBeInstanceOf(Collection::class) - ->and($faqs)->toHaveCount(2) + expect($faqs)->toHaveCount(2) ->and($faqs->first())->toBeInstanceOf(FaqDto::class) ->and($faqs->first()->question)->toBe('First question?') ->and($faqs->last()->question)->toBe('Second question?'); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php index 77df42e0..c340593b 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php @@ -6,7 +6,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Queries\Faqs; use App\Cqs\Queries\Faqs\GetPaginatedFaqsQuery; use App\Cqs\Queries\Faqs\GetPaginatedFaqsQueryInput; -use App\Dto\FaqDto; use App\Models\Faq; use App\Services\DataTableService; use Illuminate\Http\Request; @@ -51,7 +50,5 @@ describe('GetPaginatedFaqsQuery', function (): void { // THEN expect($paginator->total())->toBe(2); expect($paginator->items())->toHaveCount(2); - expect($paginator->items()[0])->toBeInstanceOf(FaqDto::class) - ->and($paginator->items()[1])->toBeInstanceOf(FaqDto::class); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php index 60aa2804..1ecba95f 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php @@ -6,9 +6,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Queries\Orders; use App\Cqs\Queries\Orders\GetTunnelOrderConfirmedQuery; use App\Cqs\Queries\Orders\GetTunnelOrderConfirmedQueryInput; -use App\Cqs\Queries\Orders\GetTunnelOrderConfirmedQueryOutput; -use App\Dto\OrderDto; -use App\Dto\ShopDto; use App\Models\Order; use App\Models\Shop; use App\Services\MapUrlService; @@ -66,13 +63,9 @@ describe('GetTunnelOrderConfirmedQuery', function (): void { $output = $query($input); // THEN - expect($output)->toBeInstanceOf(GetTunnelOrderConfirmedQueryOutput::class) - ->and($output->step)->toBe(OrderTunnelStep::CONFIRMATION) - ->and($output->order)->toBeInstanceOf(OrderDto::class) + expect($output->step)->toBe(OrderTunnelStep::CONFIRMATION) ->and((string) $output->order->reference)->toBe((string) $reference) - ->and($output->shop)->toBeInstanceOf(ShopDto::class) - ->and($output->shop->name)->toBe('Boutique Retrait') - ->and($output->mapUrl)->toBeString(); + ->and($output->shop->name)->toBe('Boutique Retrait'); }); it('throws UnexpectedValueException when order has no shop', function (): void { diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php index 68f792b7..ccbfe937 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php @@ -6,7 +6,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Queries\Pages; use App\Cqs\Queries\Pages\GetPageQuery; use App\Cqs\Queries\Pages\GetPageQueryInput; -use App\Dto\PageDto; use App\Models\Page; use Domain\Enums\StaticPageSlug; use Domain\Models\ValueObjects\Slug; @@ -29,8 +28,7 @@ describe('GetPageBySlugQuery', function (): void { $dto = $query(new GetPageQueryInput(new Slug(StaticPageSlug::LEGALS->value))); // THEN - expect($dto)->toBeInstanceOf(PageDto::class) - ->and($dto->id)->toBe($page->id) + expect($dto->id)->toBe($page->id) ->and($dto->slug)->toBe(StaticPageSlug::LEGALS) ->and($dto->seo_title)->toBe('Mentions légales SEO') ->and($dto->title)->toBe('Mentions légales'); @@ -52,8 +50,7 @@ describe('GetPageBySlugQuery', function (): void { $dto = $query(new GetPageQueryInput(new Slug('cgv'))); // THEN - expect($dto)->toBeInstanceOf(PageDto::class) - ->and($dto->id)->toBe($page->id) + expect($dto->id)->toBe($page->id) ->and($dto->slug)->toBe(StaticPageSlug::TERMS); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php index c2365bb9..7ecc3264 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php @@ -6,10 +6,8 @@ namespace Tests\Integration\WithApp\App\Cqs\Queries\PickupExceptions; use App\Cqs\Queries\PickupExceptions\GetPaginatedPickupExceptionsQuery; use App\Cqs\Queries\PickupExceptions\GetPaginatedPickupExceptionsQueryInput; -use App\Dto\PickupExceptionDto; use App\Models\PickupException; use App\Services\DataTableService; -use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\Request; use Illuminate\Session\NullSessionHandler; @@ -44,9 +42,7 @@ describe('GetPaginatedPickupExceptionsQuery', function () { $paginator = $query($input); // THEN - expect($paginator)->toBeInstanceOf(LengthAwarePaginator::class) - ->and($paginator->total())->toBe(3) - ->and($paginator->items())->toHaveCount(3) - ->and($paginator->items()[0])->toBeInstanceOf(PickupExceptionDto::class); + expect($paginator->total())->toBe(3) + ->and($paginator->items())->toHaveCount(3); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php index 4ee9d821..06cb6ecc 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php @@ -6,8 +6,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Queries\ProductIncos; use App\Cqs\Queries\ProductIncos\GetProductIncoForEditQuery; use App\Cqs\Queries\ProductIncos\GetProductIncoForEditQueryInput; -use App\Cqs\Queries\ProductIncos\GetProductIncoForEditQueryOutput; -use App\Dto\ProductDto; use App\Dto\ProductIncoDto; use App\Models\Product; use App\Models\ProductInco; @@ -68,9 +66,7 @@ describe('GetProductIncoForEditQuery', function (): void { $output = $query(new GetProductIncoForEditQueryInput($product->getId())); // THEN - expect($output)->toBeInstanceOf(GetProductIncoForEditQueryOutput::class) - ->and($output->product)->toBeInstanceOf(ProductDto::class) - ->and($output->product->id)->toBe($product->id) + expect($output->product->id)->toBe($product->id) ->and($output->inco)->toBeNull(); }); @@ -90,9 +86,7 @@ describe('GetProductIncoForEditQuery', function (): void { $output = $query(new GetProductIncoForEditQueryInput($product->getId())); // THEN - expect($output)->toBeInstanceOf(GetProductIncoForEditQueryOutput::class) - ->and($output->product)->toBeInstanceOf(ProductDto::class) - ->and($output->inco)->toBeInstanceOf(ProductIncoDto::class) + expect($output->inco)->toBeInstanceOf(ProductIncoDto::class) ->and($output->inco?->id)->toBe($inco->id) ->and($output->inco?->no_art)->toBe(12345); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductFormDataQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductFormDataQueryTest.php index e486c644..88a294db 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductFormDataQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductFormDataQueryTest.php @@ -8,7 +8,6 @@ use App\Contracts\QueryInput; use App\Cqs\Queries\Products\GetProductFormDataQuery; use App\Cqs\Queries\Products\GetProductFormDataQueryInput; use App\Dto\ProductDto; -use App\Dto\ProductFormDataDto; use App\Models\Product; use App\Models\Range; use App\Models\Tag; @@ -74,8 +73,7 @@ describe('GetProductFormDataQuery', function (): void { $output = $query($input); // THEN - expect($output)->toBeInstanceOf(ProductFormDataDto::class) - ->and($output->product)->toBeNull() + expect($output->product)->toBeNull() ->and($output->selectedProds)->toBeEmpty() ->and($output->existingProds->pluck('id')->all())->toContain((string) $product1->id, (string) $product2->id) ->and($output->existingProds->first())->toBeInstanceOf(ProductDto::class) @@ -102,8 +100,7 @@ describe('GetProductFormDataQuery', function (): void { $output = $query($input); // THEN - expect($output)->toBeInstanceOf(ProductFormDataDto::class) - ->and($output->product)->toBeInstanceOf(ProductDto::class) + expect($output->product)->toBeInstanceOf(ProductDto::class) ->and($output->product?->id)->toBe((string) $mainProduct->id) ->and($output->product?->range?->id)->toBe($range->id) ->and($output->product?->tax_rate)->toBe(TaxRate::TVA_20) diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php index 4061798c..545346d3 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php @@ -6,7 +6,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Queries\Ranges; use App\Cqs\Queries\Ranges\GetPaginatedRangesQuery; use App\Cqs\Queries\Ranges\GetPaginatedRangesQueryInput; -use App\Dto\RangeDto; use App\Models\Range; use App\Services\DataTableService; use Illuminate\Foundation\Testing\RefreshDatabase; @@ -56,8 +55,6 @@ describe('GetPaginatedRangesQuery', function () { // THEN expect($result->total())->toBe(2) - ->and($result->items())->toHaveCount(2) - ->and($result->items()[0])->toBeInstanceOf(RangeDto::class) - ->and($result->items()[1])->toBeInstanceOf(RangeDto::class); + ->and($result->items())->toHaveCount(2); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php index de622d53..05bc7308 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php @@ -6,7 +6,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Queries\Settings; use App\Contracts\QueryInputEmpty; use App\Cqs\Queries\Settings\GetSettingsQuery; -use App\Dto\SettingDto; use App\Models\Setting; use Illuminate\Foundation\Testing\RefreshDatabase; @@ -25,8 +24,7 @@ describe('GetSettingsQuery', function (): void { $dto = $query(new QueryInputEmpty()); // THEN - expect($dto)->toBeInstanceOf(SettingDto::class) - ->and($dto->id)->toBe(Setting::SINGLETON_ID) + expect($dto->id)->toBe(Setting::SINGLETON_ID) ->and($dto->employeeSites)->toBe(['NA', 'BO']); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php index 0a52276a..2517f776 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php @@ -6,9 +6,7 @@ namespace Tests\Integration\WithApp\App\Cqs\Queries\Shops; use App\Cqs\Queries\Shops\GetPaginatedShopsQuery; use App\Cqs\Queries\Shops\GetPaginatedShopsQueryInput; -use App\Cqs\Queries\Shops\GetPaginatedShopsQueryOutput; use App\Dto\PickupExceptionDto; -use App\Dto\ShopDto; use App\Models\PickupException; use App\Models\Shop; use App\Services\DataTableService; @@ -48,10 +46,8 @@ describe('GetPaginatedShopsQuery', function () { $output = $query($input); // THEN - expect($output)->toBeInstanceOf(GetPaginatedShopsQueryOutput::class) - ->and($output->shops->total())->toBe(2) + expect($output->shops->total())->toBe(2) ->and($output->shops->items())->toHaveCount(2) - ->and($output->shops->items()[0])->toBeInstanceOf(ShopDto::class) ->and($output->pickupExceptions)->toHaveCount(1) ->and($output->pickupExceptions->first())->toBeInstanceOf(PickupExceptionDto::class); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php index 05e89606..504bb341 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php @@ -6,8 +6,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Queries\Shops; use App\Cqs\Queries\Shops\GetShopPickupExceptionsQuery; use App\Cqs\Queries\Shops\GetShopPickupExceptionsQueryInput; -use App\Cqs\Queries\Shops\GetShopPickupExceptionsQueryOutput; -use App\Dto\ShopDto; use App\Models\Shop; use Domain\Services\PickupSchedulingService; use Illuminate\Foundation\Testing\RefreshDatabase; @@ -31,10 +29,7 @@ describe('GetShopPickupExceptionsQuery', function () { $output = $query($input); // THEN - expect($output)->toBeInstanceOf(GetShopPickupExceptionsQueryOutput::class) - ->and($output->shop)->toBeInstanceOf(ShopDto::class) - ->and($output->shop->id)->toBe($shop->id) - ->and($output->pickupExceptions)->toBeArray() + expect($output->shop->id)->toBe($shop->id) ->and($output->pickupDay)->not->toBeNull() ->and($output->pickupPeriod)->not->toBeNull(); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopQueryTest.php index d892bf4f..137af7a1 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopQueryTest.php @@ -7,7 +7,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Queries\Shops; use App\Contracts\QueryInput; use App\Cqs\Queries\Shops\GetShopQuery; use App\Cqs\Queries\Shops\GetShopQueryInput; -use App\Dto\ShopDto; use App\Models\PickupException; use App\Models\Shop; use Carbon\Carbon; @@ -47,8 +46,7 @@ describe('GetShopQuery', function (): void { $result = $query($input); // THEN - expect($result)->toBeInstanceOf(ShopDto::class) - ->and($result->name)->toBe('Boutique Par Défaut') + expect($result->name)->toBe('Boutique Par Défaut') ->and($result->city)->toBe('Paris') ->and($result->default)->toBeTrue() ->and($result->pickupExceptions)->toHaveCount(1) diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php index d99558d1..4980139f 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php @@ -53,9 +53,7 @@ describe('GetPaginatedSlidesQuery', function (): void { // THEN expect($paginator->total())->toBe(2) - ->and($paginator->items())->toHaveCount(2) - ->and($paginator->items()[0])->toBeInstanceOf(SlideDto::class) - ->and($paginator->items()[1])->toBeInstanceOf(SlideDto::class); + ->and($paginator->items())->toHaveCount(2); }); it('filters slides by publication date when publishedOnly is true', function (): void { diff --git a/tests/Integration/WithApp/App/Models/ProductIncoTest.php b/tests/Integration/WithApp/App/Models/ProductIncoTest.php index 585c7457..6ffc7455 100644 --- a/tests/Integration/WithApp/App/Models/ProductIncoTest.php +++ b/tests/Integration/WithApp/App/Models/ProductIncoTest.php @@ -5,7 +5,6 @@ declare(strict_types=1); namespace Tests\Integration\WithApp\App\Models; use App\Models\ProductInco; -use Domain\Models\ValueObjects\IncoId; describe('ProductInco model', function (): void { it('returns IncoId value object using no_art instead of surrogate id', function (): void { @@ -18,8 +17,7 @@ describe('ProductInco model', function (): void { $incoId = $inco->getId(); // THEN - expect($incoId)->toBeInstanceOf(IncoId::class) - ->and($incoId->value)->toBe(140317) + expect($incoId->value)->toBe(140317) ->and($incoId->value)->not->toBe(258); }); }); diff --git a/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php b/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php index 70a24803..7c0108e8 100644 --- a/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php +++ b/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php @@ -8,7 +8,6 @@ use App\Models\Setting; use App\Services\ArcadiaEmployee; use App\Services\CodeGenerationService; use App\Services\EmployeeUpsertService; -use App\Services\EmployeeUpsertServiceResult; use Carbon\CarbonImmutable; use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\ShopperEstablishmentCode; @@ -72,6 +71,7 @@ describe('EmployeeUpsertService', function (): void { $result = $service->upsertEmployees([$employee]); // THEN - expect($result)->toBeInstanceOf(EmployeeUpsertServiceResult::class); + expect($result->insertedCount)->toBe(1) + ->and($result->updatedCount)->toBe(0); }); }); diff --git a/tests/Integration/WithApp/App/Services/PublicHolidaysApiServiceTest.php b/tests/Integration/WithApp/App/Services/PublicHolidaysApiServiceTest.php index 01df7924..7c2e4384 100644 --- a/tests/Integration/WithApp/App/Services/PublicHolidaysApiServiceTest.php +++ b/tests/Integration/WithApp/App/Services/PublicHolidaysApiServiceTest.php @@ -4,9 +4,7 @@ declare(strict_types=1); namespace Tests\Integration\WithApp\App\Services; -use App\Dto\PublicHolidayDto; use App\Services\PublicHolidaysApiService; -use Carbon\CarbonImmutable; use Illuminate\Http\Client\Request; use Illuminate\Support\Facades\Http; @@ -27,8 +25,6 @@ describe('PublicHolidaysApiService', function (): void { // THEN expect($holidays)->toHaveCount(2) - ->and($holidays[0])->toBeInstanceOf(PublicHolidayDto::class) - ->and($holidays[0]->date)->toBeInstanceOf(CarbonImmutable::class) ->and($holidays[0]->date->format('Y-m-d'))->toBe('2026-01-01') ->and($holidays[0]->label)->toBe('1er janvier') ->and($holidays[1]->date->format('Y-m-d'))->toBe('2026-12-25') diff --git a/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php index 7172db33..4fb2594d 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php @@ -31,8 +31,7 @@ it('retrieves all available shops', function () { $shops = $directory->getAll(); // THEN - expect($shops)->toHaveCount(2) - ->and($shops[0])->toBeInstanceOf(\Domain\Models\Entities\Shop::class); + expect($shops)->toHaveCount(2); }); it('finds a shop by its identifier', function () { diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php index b66fb08b..a2c0386a 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php @@ -8,9 +8,7 @@ use App\Models\PickupException; use App\Models\Shop; use Carbon\CarbonPeriod; use Domain\Enums\RepeatFrequency; -use Domain\Models\Entities\PickupExceptionOnDate; use Domain\Models\ValueObjects\Entities\ShopId; -use Domain\Models\ValueObjects\ShopPickupOverride; use Illuminate\Support\Facades\DB; use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; use Ramsey\Uuid\Uuid; @@ -47,7 +45,6 @@ it('retrieves exceptions within a period for a shop', function () { // THEN expect($result)->toHaveCount(1) - ->and($result[0])->toBeInstanceOf(ShopPickupOverride::class) ->and($result[0]->exception->id->value->toString())->toBe($exUuid->toString()) ->and($result[0]->replacementDate?->format('Y-m-d'))->toBe('2023-01-11') ->and($result[0]->orderDeadlineAt?->format('Y-m-d H:i:s'))->toBe('2023-01-09 10:00:00'); @@ -72,7 +69,6 @@ it('retrieves all exceptions', function () { // THEN expect($result)->toHaveCount(1) - ->and($result[0])->toBeInstanceOf(PickupExceptionOnDate::class) ->and($result[0]->id->value->toString())->toBe($exUuid->toString()); }); @@ -107,7 +103,6 @@ it('retrieves exceptions associated with a shop', function () { // THEN expect($result)->toHaveCount(1) - ->and($result[0])->toBeInstanceOf(ShopPickupOverride::class) ->and($result[0]->exception->id->value->toString())->toBe($exUuid->toString()) ->and($result[0]->replacementDate?->format('Y-m-d'))->toBe('2023-01-11'); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php index 161af47a..80836375 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php @@ -9,7 +9,6 @@ use App\Models\Range; use Domain\Enums\Units\OrderUnit; use Domain\Exceptions\OrderTunnel\UnorderableProductException; use Domain\Models\Entities\Product as DomainProduct; -use Domain\Models\ValueObjects\BasketProduct; use Domain\Models\ValueObjects\Entities\ProductId; use Illuminate\Support\Facades\DB; use Infrastructure\Adapters\Repositories\EloquentProductRepository; @@ -66,8 +65,7 @@ it('retrieves a basket product', function () { $result = $repo->getBasketProduct($id, 2); // THEN - expect($result)->toBeInstanceOf(BasketProduct::class) - ->and($result->name)->toBe('Product Name') + expect($result->name)->toBe('Product Name') ->and($result->qty)->toBe(2); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php index 80979bdc..782a66dd 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php @@ -106,7 +106,8 @@ it('retrieves shopper by id or fails', function () { $result = $repo->getByIdOrFail(new ShopperId(Uuid::fromString($uuid))); // THEN - expect($result)->toBeInstanceOf(Shopper::class); + expect($result->id()->value->toString())->toBe($uuid) + ->and($result->matricule->value)->toBe('1234569'); }); it('throws exception if shopper not found in getByIdOrFail', function () { diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php index dc0ffafd..5a96a8ba 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php @@ -54,8 +54,7 @@ describe('SessionBasketRepository', function () { $retrievedProduct = $retrievedBasket->items()[$product->id->value->toString()]; - expect($retrievedProduct)->toBeInstanceOf(BasketProduct::class) - ->and($retrievedProduct->name)->toBe($product->name) + expect($retrievedProduct->name)->toBe($product->name) ->and($retrievedProduct->qty)->toBe($product->qty) ->and($retrievedProduct->unitPriceHt->getAmount())->toBe($product->unitPriceHt->getAmount()) ->and($retrievedProduct->unitDiscount->getAmount())->toBe($product->unitDiscount->getAmount()) diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/AppAdminAuthServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/AppAdminAuthServiceTest.php index 9fbd43ee..4dcf0514 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/AppAdminAuthServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/AppAdminAuthServiceTest.php @@ -93,7 +93,7 @@ describe('AppAdminAuthService', function () { // GIVEN $guard = \Mockery::mock(StatefulGuard::class); $user = new User(); - $user->id = '123'; + $user->id = 123; $guard->shouldReceive('user')->andReturn($user); $service = new AppAdminAuthService($guard); @@ -103,7 +103,7 @@ describe('AppAdminAuthService', function () { $id = $service->getMandatoryUserId(); // THEN - expect($returned)->toBeInstanceOf(User::class) + expect($returned->id)->toBe(123) ->and($id)->toBe('123'); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php index 121778d0..3049ccdc 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php @@ -211,6 +211,7 @@ describe('AppCustomerAuthService', function (): void { $crmService = Mockery::mock(CrmService::class); $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); + $customer->id = 'cust-123'; $guard->shouldReceive('user')->andReturn($customer); $service = new AppCustomerAuthService($guard, $crmService, $shopperService); @@ -219,7 +220,7 @@ describe('AppCustomerAuthService', function (): void { $returned = $service->getCustomerAsMandatory(); // THEN - expect($returned)->toBeInstanceOf(Customer::class); + expect($returned->id)->toBe('cust-123'); }); it('throws exception when getting customer as mandatory but null', function (): void { diff --git a/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesTest.php b/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesTest.php index 5da46190..bafe42a4 100644 --- a/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesTest.php +++ b/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesTest.php @@ -7,7 +7,6 @@ namespace Tests\Unit\App\Cqs\Actions\Employee; use App\Contracts\ActionInput; use App\Cqs\Actions\Employee\ImportEmployees; use App\Cqs\Actions\Employee\ImportEmployeesInput; -use App\Cqs\Actions\Employee\ImportEmployeesOutput; use App\Services\ArcadiaEmployee; use App\Services\EmployeeCsvImportLineService; use App\Services\EmployeeCsvReaderService; @@ -72,8 +71,7 @@ describe('ImportEmployees action', function (): void { $result = $action(new ImportEmployeesInput($fileObject)); // THEN - expect($result)->toBeInstanceOf(ImportEmployeesOutput::class) - ->and($result->insertedCount)->toBe(1) + expect($result->insertedCount)->toBe(1) ->and($result->updatedCount)->toBe(2) ->and(array_values($result->errors))->toBe(['Invalid CSV line at row 3']); diff --git a/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php b/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php index 1941d543..ad9ab7d3 100644 --- a/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php +++ b/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php @@ -6,7 +6,6 @@ namespace Tests\Unit\App\Cqs\Actions\Orders; use App\Cqs\Actions\Orders\ApplyPickTimeSlot; use App\Cqs\Actions\Orders\ApplyPickTimeSlotInput; -use App\Cqs\Actions\Orders\ApplyPickTimeSlotOutput; use App\Enums\ApplyPickTimeSlotStatus; use Carbon\CarbonImmutable; use Domain\Builders\OrderBuilderWithBasket; @@ -61,8 +60,7 @@ describe('ApplyPickTimeSlot', function (): void { $result = $action($input); // THEN - expect($result)->toBeInstanceOf(ApplyPickTimeSlotOutput::class) - ->and($result->status)->toBe(ApplyPickTimeSlotStatus::MATCHED) + expect($result->status)->toBe(ApplyPickTimeSlotStatus::MATCHED) ->and($result->timeSlot)->toBe($slot); }); @@ -108,8 +106,7 @@ describe('ApplyPickTimeSlot', function (): void { $result = $action($input); // THEN - expect($result)->toBeInstanceOf(ApplyPickTimeSlotOutput::class) - ->and($result->status)->toBe(ApplyPickTimeSlotStatus::UNAVAILABLE) + expect($result->status)->toBe(ApplyPickTimeSlotStatus::UNAVAILABLE) ->and($result->timeSlot)->toBeNull(); }); }); diff --git a/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php index 1492ff5c..73d40df6 100644 --- a/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php +++ b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -95,8 +95,7 @@ describe('PlacePendingOrder', function (): void { $result = $action($input); // THEN - expect($result)->toBeInstanceOf(PlacePendingOrderOutput::class) - ->and($result->status)->toBe(PlacePendingOrderStatus::PENDING_CREATED) + expect($result->status)->toBe(PlacePendingOrderStatus::PENDING_CREATED) ->and($result->orderId)->toBe($orderId) ->and($result->orderReference?->value)->toBe($orderReference->value); }); @@ -185,8 +184,7 @@ describe('PlacePendingOrder', function (): void { $result = $action($input); // THEN - expect($result)->toBeInstanceOf(PlacePendingOrderOutput::class) - ->and($result->status)->toBe(PlacePendingOrderStatus::BASKET_PRICE_CHANGED) + expect($result->status)->toBe(PlacePendingOrderStatus::BASKET_PRICE_CHANGED) ->and($result->orderReference)->toBeNull() ->and($result->errorMessage)->toBe('The price of one or more products in your basket has changed.'); }); diff --git a/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php index 5252eab3..4acaf9d9 100644 --- a/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php +++ b/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php @@ -6,7 +6,6 @@ namespace Tests\Unit\App\Cqs\Queries\Orders; use App\Cqs\Queries\Orders\GetBasketSummaryQuery; use App\Cqs\Queries\Orders\GetBasketSummaryQueryInput; -use App\Cqs\Queries\Orders\GetBasketSummaryQueryOutput; use Domain\Enums\OrderTunnelStep; use Domain\Models\Entities\Basket; use Domain\Models\ValueObjects\Entities\BasketId; @@ -29,8 +28,7 @@ describe('GetBasketSummaryQuery', function (): void { $output = $query($input); // THEN - expect($output)->toBeInstanceOf(GetBasketSummaryQueryOutput::class) - ->and($output->step)->toBe(OrderTunnelStep::REVIEW) + expect($output->step)->toBe(OrderTunnelStep::REVIEW) ->and($output->basket)->toBe($basket); }); }); diff --git a/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php index 2c78f3a4..49302843 100644 --- a/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php +++ b/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php @@ -6,8 +6,6 @@ namespace Tests\Unit\App\Cqs\Queries\Orders; use App\Cqs\Queries\Orders\GetOrderConfirmationQuery; use App\Cqs\Queries\Orders\GetOrderConfirmationQueryInput; -use App\Cqs\Queries\Orders\GetOrderConfirmationQueryOutput; -use App\Dto\ShopDto; use Domain\Builders\OrderBuilderCompleted; use Domain\Enums\OrderTunnelStep; use Domain\Models\Entities\Basket; @@ -54,11 +52,9 @@ describe('GetOrderConfirmationQuery', function (): void { $output = $query($input); // THEN - expect($output)->toBeInstanceOf(GetOrderConfirmationQueryOutput::class) - ->and($output->step)->toBe(OrderTunnelStep::CONFIRMATION) + expect($output->step)->toBe(OrderTunnelStep::CONFIRMATION) ->and($output->basket)->toBe($basket) ->and($output->builder)->toBe($builder) - ->and($output->shop)->toBeInstanceOf(ShopDto::class) ->and($output->shop->name)->toBe('Shop 1'); }); diff --git a/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php index b23aebaa..87493ad7 100644 --- a/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php +++ b/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php @@ -6,7 +6,6 @@ namespace Tests\Unit\App\Cqs\Queries\Orders; use App\Cqs\Queries\Orders\GetPickTimeSlotQuery; use App\Cqs\Queries\Orders\GetPickTimeSlotQueryInput; -use App\Cqs\Queries\Orders\GetPickTimeSlotQueryOutput; use App\Dto\ShopDto; use App\Services\MapUrlService; use Carbon\CarbonImmutable; @@ -56,9 +55,7 @@ describe('GetPickTimeSlotQuery', function (): void { $output = $query($input); // THEN - expect($output)->toBeInstanceOf(GetPickTimeSlotQueryOutput::class) - ->and($output->step)->toBe(OrderTunnelStep::BOOKING) - ->and($output->shop)->toBeInstanceOf(ShopDto::class) + expect($output->step)->toBe(OrderTunnelStep::BOOKING) ->and($output->shop->name)->toBe('Shop 1') ->and($output->mapUrl)->toBe('https://maps.example.com') ->and($output->timeSlots)->toBe($timeSlots); diff --git a/tests/Unit/App/Cqs/Queries/ProductIncos/GetArcadiaIncoPreviewQueryTest.php b/tests/Unit/App/Cqs/Queries/ProductIncos/GetArcadiaIncoPreviewQueryTest.php index 1aed9120..6bd85dd1 100644 --- a/tests/Unit/App/Cqs/Queries/ProductIncos/GetArcadiaIncoPreviewQueryTest.php +++ b/tests/Unit/App/Cqs/Queries/ProductIncos/GetArcadiaIncoPreviewQueryTest.php @@ -6,7 +6,6 @@ namespace Tests\Unit\App\Cqs\Queries\ProductIncos; use App\Cqs\Queries\ProductIncos\GetArcadiaIncoPreviewQuery; use App\Cqs\Queries\ProductIncos\GetArcadiaIncoPreviewQueryInput; -use App\Cqs\Queries\ProductIncos\GetArcadiaIncoPreviewQueryOutput; use App\Dto\ArcadiaIncoPreviewDto; use App\Enums\ArcadiaIncoPreviewStatus; use App\Services\ArcadiaIncoService; @@ -40,8 +39,7 @@ describe('GetArcadiaIncoPreviewQuery', function (): void { $result = $query($input); // THEN - expect($result)->toBeInstanceOf(GetArcadiaIncoPreviewQueryOutput::class) - ->and($result->status)->toBe(ArcadiaIncoPreviewStatus::FOUND) + expect($result->status)->toBe(ArcadiaIncoPreviewStatus::FOUND) ->and($result->preview)->toBe($previewDto) ->and($result->errorMessage)->toBeNull(); }); @@ -61,8 +59,7 @@ describe('GetArcadiaIncoPreviewQuery', function (): void { $result = $query($input); // THEN - expect($result)->toBeInstanceOf(GetArcadiaIncoPreviewQueryOutput::class) - ->and($result->status)->toBe(ArcadiaIncoPreviewStatus::NOT_FOUND) + expect($result->status)->toBe(ArcadiaIncoPreviewStatus::NOT_FOUND) ->and($result->preview)->toBeNull(); }); @@ -81,8 +78,7 @@ describe('GetArcadiaIncoPreviewQuery', function (): void { $result = $query($input); // THEN - expect($result)->toBeInstanceOf(GetArcadiaIncoPreviewQueryOutput::class) - ->and($result->status)->toBe(ArcadiaIncoPreviewStatus::API_ERROR) + expect($result->status)->toBe(ArcadiaIncoPreviewStatus::API_ERROR) ->and($result->errorMessage)->toBe('Connection timeout') ->and($result->preview)->toBeNull(); }); diff --git a/tests/Unit/App/Dto/SettingDtoTest.php b/tests/Unit/App/Dto/SettingDtoTest.php index 779f81a6..6121d494 100644 --- a/tests/Unit/App/Dto/SettingDtoTest.php +++ b/tests/Unit/App/Dto/SettingDtoTest.php @@ -5,7 +5,6 @@ declare(strict_types=1); namespace Tests\Unit\App\Dto; use App\Dto\SettingDto; -use Domain\Models\ValueObjects\ShopperSiteCode; describe('SettingDto', function (): void { it('creates a DTO and provides helper methods', function (): void { @@ -19,7 +18,6 @@ describe('SettingDto', function (): void { // THEN expect($dto->employeeSitesAsString())->toBe('PA, LY') ->and($dto->getShopperSiteCodes())->toHaveCount(2) - ->and($dto->getShopperSiteCodes()[0])->toBeInstanceOf(ShopperSiteCode::class) ->and($dto->getShopperSiteCodes()[0]->value)->toBe('PA') ->and($dto->getShopperSiteCodes()[1]->value)->toBe('LY') ->and($dto->getRouteKey())->toBe(1) diff --git a/tests/Unit/App/Services/CodeGenerationServiceTest.php b/tests/Unit/App/Services/CodeGenerationServiceTest.php index d48aac40..2856a9bc 100644 --- a/tests/Unit/App/Services/CodeGenerationServiceTest.php +++ b/tests/Unit/App/Services/CodeGenerationServiceTest.php @@ -27,8 +27,7 @@ describe('CodeGenerationService', function (): void { $code = $service->generateFrom($matricule); // THEN - expect($code)->toBeInstanceOf(Code::class) - ->and(strlen($code->value))->toBe(Code::LENGTH) + expect(strlen($code->value))->toBe(Code::LENGTH) ->and(preg_match('/^[' . Code::ALLOWED_CHARACTERS . ']+$/', $code->value))->toBe(1); }); diff --git a/tests/Unit/App/Services/EmployeeCsvImportLineTest.php b/tests/Unit/App/Services/EmployeeCsvImportLineTest.php index c2f7945c..a1948e5b 100644 --- a/tests/Unit/App/Services/EmployeeCsvImportLineTest.php +++ b/tests/Unit/App/Services/EmployeeCsvImportLineTest.php @@ -18,8 +18,7 @@ describe('EmployeeCsvImportLineService', function (): void { $line->setService('LDCCAV030'); // THEN - expect($line->startDate)->toBeInstanceOf(\DateTimeImmutable::class) - ->and($line->startDate->format('Y-m-d'))->toBe('2026-10-01') + expect($line->startDate->format('Y-m-d'))->toBe('2026-10-01') ->and($line->endDate)->toBeNull() ->and($line->expectedEndDate)->toBeInstanceOf(\DateTimeImmutable::class) ->and($line->expectedEndDate?->format('Y-m-d'))->toBe('2026-10-15') diff --git a/tests/Unit/App/Services/EmployeeCsvReaderServiceTest.php b/tests/Unit/App/Services/EmployeeCsvReaderServiceTest.php index 8dd11894..288a81c0 100644 --- a/tests/Unit/App/Services/EmployeeCsvReaderServiceTest.php +++ b/tests/Unit/App/Services/EmployeeCsvReaderServiceTest.php @@ -42,7 +42,6 @@ describe('EmployeeCsvReaderService', function (): void { assert($firstItem instanceof EmployeeCsvImportLineService); expect($items)->toHaveCount(1) - ->and($firstItem)->toBeInstanceOf(EmployeeCsvImportLineService::class) ->and($firstItem->matricule)->toBe('1234567') ->and($firstItem->service)->toBe('030'); diff --git a/tests/Unit/App/Services/IcsGeneratorServiceTest.php b/tests/Unit/App/Services/IcsGeneratorServiceTest.php index 9127f116..c738df67 100644 --- a/tests/Unit/App/Services/IcsGeneratorServiceTest.php +++ b/tests/Unit/App/Services/IcsGeneratorServiceTest.php @@ -8,7 +8,6 @@ use App\Dto\IcsContentDto; use App\Services\IcsGeneratorService; use Carbon\Carbon; use Carbon\CarbonImmutable; -use Domain\Models\ValueObjects\IcsContent; covers(IcsGeneratorService::class); @@ -47,8 +46,7 @@ describe('IcsGeneratorService', function (): void { $ics = $service->generate($dto); // THEN - expect($ics)->toBeInstanceOf(IcsContent::class) - ->and($ics->value) + expect($ics->value) ->toContain('BEGIN:VCALENDAR') ->toContain('PRODID:-//MyApp//NONSGML v1.0//EN') ->toContain('UID:uid-123') @@ -76,8 +74,7 @@ describe('IcsGeneratorService', function (): void { $ics = $service->generate($dto); // THEN - expect($ics)->toBeInstanceOf(IcsContent::class) - ->and($ics->value)->toContain('URL:http://example.com'); + expect($ics->value)->toContain('URL:http://example.com'); }); it('converts Europe/Paris winter timestamps to UTC correctly', function (): void { @@ -99,8 +96,7 @@ describe('IcsGeneratorService', function (): void { // THEN // 12:00 Europe/Paris in winter (UTC+1) is 11:00 UTC - expect($ics)->toBeInstanceOf(IcsContent::class) - ->and($ics->value)->toContain('VERSION:2.0') + expect($ics->value)->toContain('VERSION:2.0') ->toContain('BEGIN:VEVENT') ->toContain('DTSTAMP:20240101T100000Z') ->toContain('DTSTART:20240101T110000Z') diff --git a/tests/Unit/Domain/Enums/CountryTest.php b/tests/Unit/Domain/Enums/CountryTest.php index ea25089e..c9c867ac 100644 --- a/tests/Unit/Domain/Enums/CountryTest.php +++ b/tests/Unit/Domain/Enums/CountryTest.php @@ -93,6 +93,6 @@ describe('CountryEnum', function () { $isoCodes = Country::toIsoCodes(); // THEN - expect($isoCodes)->toBeArray()->toHaveKey('france', 'FR'); + expect($isoCodes)->toHaveKey('france', 'FR'); }); }); diff --git a/tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php b/tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php index 3017f81d..e0f0be0e 100644 --- a/tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php +++ b/tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php @@ -7,7 +7,6 @@ namespace Tests\Unit\Domain\Events; use Domain\Events\BasketHasBeenModified; use Domain\Models\ValueObjects\Entities\BasketId; use Ramsey\Uuid\Uuid; -use Shared\DDD\Event; describe('BasketHasBeenModified', function (): void { it('stores the basket id and implements Event', function (): void { @@ -18,7 +17,6 @@ describe('BasketHasBeenModified', function (): void { $event = new BasketHasBeenModified($basketId); // THEN - expect($event)->toBeInstanceOf(Event::class) - ->and($event->basketId)->toBe($basketId); + expect($event->basketId)->toBe($basketId); }); }); diff --git a/tests/Unit/Domain/Events/BasketRemovedTest.php b/tests/Unit/Domain/Events/BasketRemovedTest.php index bfcd4e00..6fbdde8c 100644 --- a/tests/Unit/Domain/Events/BasketRemovedTest.php +++ b/tests/Unit/Domain/Events/BasketRemovedTest.php @@ -7,7 +7,6 @@ namespace Tests\Unit\Domain\Events; use Domain\Events\BasketRemoved; use Domain\Models\ValueObjects\Entities\BasketId; use Ramsey\Uuid\Uuid; -use Shared\DDD\Event; describe('BasketRemoved', function (): void { it('stores the basket id and implements Event', function (): void { @@ -18,7 +17,6 @@ describe('BasketRemoved', function (): void { $event = new BasketRemoved($basketId); // THEN - expect($event)->toBeInstanceOf(Event::class) - ->and($event->basketId)->toBe($basketId); + expect($event->basketId)->toBe($basketId); }); }); diff --git a/tests/Unit/Domain/Models/Entities/OrderTest.php b/tests/Unit/Domain/Models/Entities/OrderTest.php index 4b642001..6024e0b7 100644 --- a/tests/Unit/Domain/Models/Entities/OrderTest.php +++ b/tests/Unit/Domain/Models/Entities/OrderTest.php @@ -9,7 +9,6 @@ use Domain\Enums\OrderStatus; use Domain\Enums\ProductBrand; use Domain\Enums\TaxRate; use Domain\Enums\Units\OrderUnit; -use Domain\Events\AnOrderHasBeenPlaced; use Domain\Models\Entities\Basket; use Domain\Models\Entities\Order; use Domain\Models\Entities\Shop; @@ -108,8 +107,7 @@ describe('Order - Instantiation', function (): void { $order = makeOrder(['lines' => [$line]]); // THEN - expect($order)->toBeInstanceOf(Order::class) - ->and($order->status)->toBe(OrderStatus::VALIDATED) + expect($order->status)->toBe(OrderStatus::VALIDATED) ->and($order->getTotal()->getAmount())->toBe('3798') ->and($order->getLines())->toHaveCount(1); }); @@ -207,7 +205,7 @@ describe('Order - id', function (): void { // WHEN $id = $order->id(); // THEN - expect($id)->toBeInstanceOf(OrderId::class); + expect(strlen($id->value->toString()))->toBe(36); }); }); @@ -355,8 +353,7 @@ describe('Order - Domain Events', function (): void { $event = $order->toPlacedEvent(); // THEN - expect($event)->toBeInstanceOf(AnOrderHasBeenPlaced::class) - ->and($event->orderId)->toBe($order->id()) + expect($event->orderId)->toBe($order->id()) ->and($event->reference)->toBe($order->reference) ->and($event->totalTtc->getAmount())->toBe($order->getTotal()->getAmount()) ->and($event->byMatricule)->toBe($order->employee->matricule) diff --git a/tests/Unit/Domain/Models/Entities/ProductTest.php b/tests/Unit/Domain/Models/Entities/ProductTest.php index 48170128..8dea4710 100644 --- a/tests/Unit/Domain/Models/Entities/ProductTest.php +++ b/tests/Unit/Domain/Models/Entities/ProductTest.php @@ -11,7 +11,6 @@ use Domain\Enums\Units\InvoicingUnit; use Domain\Models\Entities\Product; use Domain\Models\ValueObjects\DiscountValue; use Domain\Models\ValueObjects\Entities\ProductId; -use Domain\Models\ValueObjects\ProductPricing; use Domain\Models\ValueObjects\ProductWeight; use Money\Money; use Ramsey\Uuid\Uuid; @@ -330,8 +329,7 @@ describe('Product', function (): void { $pricing = $product->pricing(); // THEN - expect($pricing)->toBeInstanceOf(ProductPricing::class) - ->and($pricing->basePriceHt())->toEqual(Money::EUR(1000)) + expect($pricing->basePriceHt())->toEqual(Money::EUR(1000)) ->and($pricing->basePriceTtc())->toEqual(Money::EUR(1200)) ->and($pricing->discountAmountHt())->toEqual(Money::EUR(0)) ->and($pricing->discountedPriceHt())->toEqual(Money::EUR(1000)) diff --git a/tests/Unit/Domain/Models/ValueObjects/AttachedFileTest.php b/tests/Unit/Domain/Models/ValueObjects/AttachedFileTest.php index f9864afc..c16ee833 100644 --- a/tests/Unit/Domain/Models/ValueObjects/AttachedFileTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/AttachedFileTest.php @@ -33,7 +33,9 @@ describe('AttachedFile', function () { ); // THEN - expect($vo)->toBeInstanceOf(AttachedFile::class); + expect($vo->path)->toBe($path) + ->and($vo->originalName)->toBe($originalName) + ->and($vo->mimeType)->toBe($mimeType); }); it('throws exception if path is empty', function () { diff --git a/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php b/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php index f4769633..66960ff4 100644 --- a/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php @@ -87,7 +87,9 @@ describe('BasketProduct', function () { ); // THEN - expect($vo)->toBeInstanceOf(BasketProduct::class); + expect($vo->id)->toBe($id) + ->and($vo->name)->toBe($name) + ->and($vo->qty)->toBe($qty); }); it('throws exception if name is empty', function () { diff --git a/tests/Unit/Domain/Models/ValueObjects/CodeTest.php b/tests/Unit/Domain/Models/ValueObjects/CodeTest.php index 7ee20aab..23af9482 100644 --- a/tests/Unit/Domain/Models/ValueObjects/CodeTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/CodeTest.php @@ -13,8 +13,7 @@ describe('Code Value Object', function () { $vo = new Code($value); // THEN - expect($vo)->toBeInstanceOf(Code::class) - ->and($vo->value)->toBe($value); + expect($vo->value)->toBe($value); })->with([ 'standard length 6' => 'ABCDEF', 'legacy code length 8' => 'ABCDEFGH', diff --git a/tests/Unit/Domain/Models/ValueObjects/ContactFormDataTest.php b/tests/Unit/Domain/Models/ValueObjects/ContactFormDataTest.php index 714f9668..981fbd6d 100644 --- a/tests/Unit/Domain/Models/ValueObjects/ContactFormDataTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/ContactFormDataTest.php @@ -47,7 +47,10 @@ describe('ContactFormData', function () { ); // THEN - expect($vo)->toBeInstanceOf(ContactFormData::class); + expect($vo->lastName)->toBe($lastName) + ->and($vo->firstName)->toBe($firstName) + ->and($vo->email)->toBe($email) + ->and($vo->orderRef)->toBe($orderRef); }); it('throws exception if lastName is empty', function () { diff --git a/tests/Unit/Domain/Models/ValueObjects/EmailTest.php b/tests/Unit/Domain/Models/ValueObjects/EmailTest.php index 5da14970..d914b247 100644 --- a/tests/Unit/Domain/Models/ValueObjects/EmailTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/EmailTest.php @@ -15,7 +15,7 @@ describe('Email', function () { $vo = new Email($email); // THEN - expect($vo)->toBeInstanceOf(Email::class); + expect($vo->value)->toBe($email); }); it('throws exception if email format is invalid', function () { diff --git a/tests/Unit/Domain/Models/ValueObjects/IncoIdTest.php b/tests/Unit/Domain/Models/ValueObjects/IncoIdTest.php index dff358a0..e0f613e9 100644 --- a/tests/Unit/Domain/Models/ValueObjects/IncoIdTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/IncoIdTest.php @@ -16,7 +16,7 @@ describe('IncoId', function () { $vo = new IncoId($value); // THEN - expect($vo)->toBeInstanceOf(IncoId::class); + expect($vo->value)->toBe($value); }); it('throws exception if value is zero or negative', function () { diff --git a/tests/Unit/Domain/Models/ValueObjects/MatriculeTest.php b/tests/Unit/Domain/Models/ValueObjects/MatriculeTest.php index dc085663..d640517c 100644 --- a/tests/Unit/Domain/Models/ValueObjects/MatriculeTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/MatriculeTest.php @@ -13,8 +13,7 @@ describe('Matricule', function () { $vo = new Matricule($value); // THEN - expect($vo)->toBeInstanceOf(Matricule::class) - ->and($vo->value)->toBe($value); + expect($vo->value)->toBe($value); })->with([ '7 digits with leading zero' => '0111123', '8 digits with leading zero' => '01111234', diff --git a/tests/Unit/Domain/Models/ValueObjects/NutritionalValuesTest.php b/tests/Unit/Domain/Models/ValueObjects/NutritionalValuesTest.php index 08c49f28..02d7fc9b 100644 --- a/tests/Unit/Domain/Models/ValueObjects/NutritionalValuesTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/NutritionalValuesTest.php @@ -22,7 +22,8 @@ describe('NutritionalValues', function () { $vo = new NutritionalValues(refWeightG: $refWeightG, kj: $kj); // THEN - expect($vo)->toBeInstanceOf(NutritionalValues::class); + expect($vo->refWeightG)->toBe(100.0) + ->and($vo->kj)->toBe(500.0); }); it('throws exception if reference weight is negative', function () { @@ -77,7 +78,6 @@ describe('NutritionalValues', function () { $array = $vo->toArray(); // THEN - expect($array)->toBeArray(); expect($array['nv_ref_weight_g'])->toBe(100.0); expect($array['nv_kj'])->toBe(500.0); expect($array['nv_protein_g'])->toBe(10.5); diff --git a/tests/Unit/Domain/Models/ValueObjects/OrderReferenceTest.php b/tests/Unit/Domain/Models/ValueObjects/OrderReferenceTest.php index 9f98ac5f..bfb0eb79 100644 --- a/tests/Unit/Domain/Models/ValueObjects/OrderReferenceTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/OrderReferenceTest.php @@ -23,8 +23,7 @@ describe('OrderReference', function () { $vo = getNewOrderReference($uuidV7); // THEN - expect($vo)->toBeInstanceOf(OrderReference::class) - ->and((string) $vo)->toBe(UuidHelper::toBase58($uuidV7)) + expect((string) $vo)->toBe(UuidHelper::toBase58($uuidV7)) ->and($vo->value)->toBe($uuidV7); }); @@ -37,8 +36,7 @@ describe('OrderReference', function () { $vo = OrderReference::fromBase58($base58); // THEN - expect($vo)->toBeInstanceOf(OrderReference::class) - ->and((string) $vo)->toBe($base58) + expect((string) $vo)->toBe($base58) ->and($vo->value->equals($uuidV7))->toBeTrue(); }); @@ -51,8 +49,7 @@ describe('OrderReference', function () { $vo = OrderReference::fromString($uuidString); // THEN - expect($vo)->toBeInstanceOf(OrderReference::class) - ->and((string) $vo)->toBe(UuidHelper::toBase58($uuidV7)) + expect((string) $vo)->toBe(UuidHelper::toBase58($uuidV7)) ->and($vo->value->equals($uuidV7))->toBeTrue(); }); @@ -65,8 +62,7 @@ describe('OrderReference', function () { $vo = OrderReference::fromString($base58); // THEN - expect($vo)->toBeInstanceOf(OrderReference::class) - ->and((string) $vo)->toBe($base58) + expect((string) $vo)->toBe($base58) ->and($vo->value->equals($uuidV7))->toBeTrue(); }); diff --git a/tests/Unit/Domain/Models/ValueObjects/PickupTimeSlotTest.php b/tests/Unit/Domain/Models/ValueObjects/PickupTimeSlotTest.php index 74384fde..bfd50a17 100644 --- a/tests/Unit/Domain/Models/ValueObjects/PickupTimeSlotTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/PickupTimeSlotTest.php @@ -16,7 +16,8 @@ describe('PickupTimeSlot', function () { $vo = new PickupTimeSlot($startAt, $duration); // THEN - expect($vo)->toBeInstanceOf(PickupTimeSlot::class); + expect($vo->getAt()->format('Y-m-d H:i:s'))->toBe($startAt->format('Y-m-d H:i:s')) + ->and($vo->getFor()->d)->toBe(1); }); }); @@ -29,7 +30,7 @@ describe('PickupTimeSlot methods', function (): void { // WHEN $res = $vo->getAt(); // THEN - expect($res)->toBeInstanceOf(\DateTimeImmutable::class); + expect($res->format('Y-m-d H:i:s'))->toBe($at->format('Y-m-d H:i:s')); }); it('returns getAt as immutable when passed immutable', function (): void { @@ -40,7 +41,7 @@ describe('PickupTimeSlot methods', function (): void { // WHEN $res = $vo->getAt(); // THEN - expect($res)->toBeInstanceOf(\DateTimeImmutable::class); + expect($res->format('Y-m-d H:i:s'))->toBe($at->format('Y-m-d H:i:s')); }); it('returns getFor', function (): void { diff --git a/tests/Unit/Domain/Models/ValueObjects/ProductPricingTest.php b/tests/Unit/Domain/Models/ValueObjects/ProductPricingTest.php index 1b593abe..35a91189 100644 --- a/tests/Unit/Domain/Models/ValueObjects/ProductPricingTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/ProductPricingTest.php @@ -40,7 +40,8 @@ describe('ProductPricing', function () { $vo = getNewProductPricing($data); // THEN - expect($vo)->toBeInstanceOf(ProductPricing::class); + expect($vo->basePriceHt()->getAmount())->toBe('1000') + ->and($vo->hasDiscount)->toBeFalse(); }); it('throws exception if basePriceHt is negative', function () { diff --git a/tests/Unit/Domain/Models/ValueObjects/ProductWeightTest.php b/tests/Unit/Domain/Models/ValueObjects/ProductWeightTest.php index 594ede82..77ba0cdb 100644 --- a/tests/Unit/Domain/Models/ValueObjects/ProductWeightTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/ProductWeightTest.php @@ -17,9 +17,7 @@ describe('ProductWeight', function () { $vo = new ProductWeight($value, $isVariable); // THEN - expect($vo) - ->toBeInstanceOf(ProductWeight::class) - ->and($vo->value)->toBe(1600) + expect($vo->value)->toBe(1600) ->and($vo->toGrams())->toBe(1600); }); diff --git a/tests/Unit/Domain/Services/BasketServiceTest.php b/tests/Unit/Domain/Services/BasketServiceTest.php index 7ab56682..7389fd74 100644 --- a/tests/Unit/Domain/Services/BasketServiceTest.php +++ b/tests/Unit/Domain/Services/BasketServiceTest.php @@ -245,8 +245,7 @@ describe('BasketService', function (): void { $returnedBasket = $service->getBasket(); // THEN - expect($returnedBasket)->toBeInstanceOf(Basket::class) - ->and($returnedBasket->id->value)->toBe($sessionId->value) + expect($returnedBasket->id->value)->toBe($sessionId->value) ->and($returnedBasket->countItems())->toBe(0); }); diff --git a/tests/Unit/Domain/Services/OrderServiceTest.php b/tests/Unit/Domain/Services/OrderServiceTest.php index 6d211e60..fb4c48a8 100644 --- a/tests/Unit/Domain/Services/OrderServiceTest.php +++ b/tests/Unit/Domain/Services/OrderServiceTest.php @@ -191,7 +191,6 @@ describe('Order Creation', function () { $order = $service->createOrderFromBasket($basket, $pickupTimeSlot, $shopper, $shop); // THEN - expect($order)->toBeInstanceOf(Order::class); expect($order->status)->toBe(OrderStatus::VALIDATED); expect(UuidHelper::isV7($order->reference->value))->toBeTrue(); diff --git a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php index d12eec6a..915079e2 100644 --- a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php +++ b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php @@ -377,7 +377,7 @@ describe('OrderTunnelService', function (): void { $slots = $service->getAvailableTimeSlots($shop); // THEN - expect($slots)->toBeArray(); + expect($slots)->not->toBeEmpty(); }); it('initializes order from basket', function (): void { @@ -572,7 +572,6 @@ describe('OrderTunnelService', function (): void { $order = $service->finalizeOrder($builder); // THEN - expect($order)->toBeInstanceOf(Order::class); expect($order->employee->matricule->value)->toBe('1234567'); expect($order->deliveryAddress->name)->toBe('Shop'); }); @@ -683,7 +682,7 @@ describe('OrderTunnelService', function (): void { $order = $service->finalizeOrder($builder); // THEN - expect($order)->toBeInstanceOf(Order::class); + expect($order->status)->toBe(OrderStatus::VALIDATED); }); it('throws BasketPriceChangedException with refreshed basket when product price changes before finalization', function (): void { @@ -958,8 +957,7 @@ describe('OrderTunnelService', function (): void { $order = $service->placePendingOrder($builder); // THEN - expect($order)->toBeInstanceOf(Order::class) - ->and($order->status)->toBe(OrderStatus::WAITING); + expect($order->status)->toBe(OrderStatus::WAITING); }); it('exports, confirms and cancels a pending order across split steps', function (): void { diff --git a/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php b/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php index b060c278..9996f64e 100644 --- a/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php +++ b/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php @@ -17,7 +17,6 @@ use Domain\Models\ValueObjects\ShopPickupOverride; use Domain\Ports\Repositories\PickupExceptionRepository; use Domain\Services\PickupSchedulingService; use Ramsey\Uuid\Uuid; -use Ramsey\Uuid\UuidInterface; function createTestShop(int $id = 1): Shop { @@ -368,15 +367,13 @@ describe('Pickup Scheduling Service', function (): void { // Test 1: is Friday, associated -> checked, replacement null // THEN - expect($editable[0]->pickupException->id->value)->toBeInstanceOf(UuidInterface::class) - ->and($editable[0]->isPickupDay)->toBeTrue() + expect($editable[0]->isPickupDay)->toBeTrue() ->and($editable[0]->missingSubsitute)->toBeTrue() ->and($editable[0]->passedDeadline)->toBeFalse(); // Test 2: not Friday, not associated // THEN - expect($editable[1]->pickupException->id->value)->toBeInstanceOf(UuidInterface::class) - ->and($editable[1]->isPickupDay)->toBeFalse() + expect($editable[1]->isPickupDay)->toBeFalse() ->and($editable[1]->missingSubsitute)->toBeFalse() ->and($editable[1]->passedDeadline)->toBeFalse(); }); From c2490e03393225772164f646830906fc30f6fecc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 15:45:21 +0100 Subject: [PATCH 143/183] test(phpstan): remove all 55 redundant RefreshDatabase uses() --- tests/Feature/App/Console/Commands/UserCreateTest.php | 3 --- .../App/Http/Controllers/Bo/ProductIncosControllerTest.php | 3 --- tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php | 3 --- tests/Feature/App/Jobs/DeleteOldResetTokensTest.php | 3 --- tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php | 3 --- tests/Feature/App/Jobs/UpdateSlidesStatusTest.php | 3 --- .../Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php | 3 --- tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php | 3 --- tests/Integration/WithApp/App/Casts/CalendarDateCastTest.php | 3 --- tests/Integration/WithApp/App/Casts/UtcDatetimeCastTest.php | 3 --- .../WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php | 3 --- .../WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php | 3 --- .../WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php | 3 --- .../WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php | 3 --- .../WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php | 3 --- .../Employee/SynchronizeEmployeesWithArcadiaApiTest.php | 3 --- .../WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php | 3 --- .../WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php | 3 --- .../App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php | 3 --- .../App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php | 3 --- .../WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php | 3 --- .../App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php | 3 --- .../Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php | 3 --- .../Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php | 3 --- .../Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php | 3 --- .../App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php | 3 --- .../App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php | 3 --- .../ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php | 3 --- .../WithApp/App/Cqs/Actions/Products/CreateProductTest.php | 3 --- .../WithApp/App/Cqs/Actions/Products/DeleteProductTest.php | 3 --- .../WithApp/App/Cqs/Actions/Products/UpdateProductTest.php | 3 --- .../WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php | 3 --- .../WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php | 3 --- .../WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php | 3 --- .../WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php | 3 --- .../WithApp/App/Cqs/Actions/Shops/CreateShopTest.php | 3 --- .../WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php | 3 --- .../App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php | 3 --- .../WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php | 3 --- .../App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php | 3 --- .../WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php | 3 --- .../PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php | 3 --- .../Cqs/Queries/Products/GetFoProductIndexPageQueryTest.php | 3 --- .../App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php | 3 --- .../WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php | 3 --- .../App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php | 3 --- .../App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php | 3 --- tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php | 3 --- tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php | 3 --- tests/Integration/WithApp/App/Dto/RangeDtoTest.php | 3 --- tests/Integration/WithApp/App/Dto/ShopDtoTest.php | 3 --- .../WithApp/App/Services/EmployeeSyncServiceTest.php | 3 --- .../WithApp/App/Services/EmployeeUpsertServiceTest.php | 3 --- .../WithApp/App/Services/OrderOwnershipServiceTest.php | 3 --- tests/Integration/WithApp/App/Services/StatsServiceTest.php | 3 --- 55 files changed, 165 deletions(-) diff --git a/tests/Feature/App/Console/Commands/UserCreateTest.php b/tests/Feature/App/Console/Commands/UserCreateTest.php index 222df908..415ba285 100644 --- a/tests/Feature/App/Console/Commands/UserCreateTest.php +++ b/tests/Feature/App/Console/Commands/UserCreateTest.php @@ -6,11 +6,8 @@ namespace Tests\Feature\App\Console\Commands; use App\Models\User; use Domain\Enums\UserRole; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Hash; -uses(RefreshDatabase::class); - it('creates an admin user via uwil:user:create command using Executor', function (): void { /** @var \Tests\TestCase $this */ // GIVEN diff --git a/tests/Feature/App/Http/Controllers/Bo/ProductIncosControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/ProductIncosControllerTest.php index 4eaebf42..ae06fdb9 100644 --- a/tests/Feature/App/Http/Controllers/Bo/ProductIncosControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/ProductIncosControllerTest.php @@ -21,11 +21,8 @@ use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; use Domain\Enums\UserRole; use Domain\Models\ValueObjects\NutritionalValues; -use Illuminate\Foundation\Testing\RefreshDatabase; use Money\Money; -uses(RefreshDatabase::class); - describe('ProductIncosController', function () { beforeEach(function () { /** @var \Tests\TestCase $this */ diff --git a/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php index a3f6ed50..12f62b3c 100644 --- a/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php @@ -9,7 +9,6 @@ use App\Models\Range; use App\Models\Tag; use App\Models\User; use Domain\Enums\UserRole; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Gate; use Uwil\Storage\Contracts\StorageService; @@ -20,8 +19,6 @@ use function Pest\Laravel\get; use function Pest\Laravel\patch; use function Pest\Laravel\postJson; -uses(RefreshDatabase::class); - describe('RangesController', function () { beforeEach(function () { /** @var \Tests\TestCase $this */ diff --git a/tests/Feature/App/Jobs/DeleteOldResetTokensTest.php b/tests/Feature/App/Jobs/DeleteOldResetTokensTest.php index cac020ab..aaffb1d3 100644 --- a/tests/Feature/App/Jobs/DeleteOldResetTokensTest.php +++ b/tests/Feature/App/Jobs/DeleteOldResetTokensTest.php @@ -6,11 +6,8 @@ namespace Tests\Feature\App\Jobs; use App\Jobs\DeleteOldResetTokens; use App\Models\PasswordReset; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Date; -uses(RefreshDatabase::class); - it('deletes old password reset tokens via Executor when dispatched', function (): void { // GIVEN Date::setTestNow('2026-11-14 12:00:00'); diff --git a/tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php b/tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php index 333e95e8..22ed28d3 100644 --- a/tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php +++ b/tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php @@ -7,12 +7,9 @@ namespace Tests\Feature\App\Jobs; use App\Jobs\EnsurePublicHolidaysSyncedJob; use App\Models\PickupException; use App\Models\Shop; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Http; -uses(RefreshDatabase::class); - afterEach(function (): void { Date::setTestNow(); }); diff --git a/tests/Feature/App/Jobs/UpdateSlidesStatusTest.php b/tests/Feature/App/Jobs/UpdateSlidesStatusTest.php index a5a9933f..88e6fad3 100644 --- a/tests/Feature/App/Jobs/UpdateSlidesStatusTest.php +++ b/tests/Feature/App/Jobs/UpdateSlidesStatusTest.php @@ -6,11 +6,8 @@ namespace Tests\Feature\App\Jobs; use App\Jobs\UpdateSlidesStatus; use App\Models\Slide; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Date; -uses(RefreshDatabase::class); - it('updates scheduled slides status via Executor when dispatched', function (): void { // GIVEN Date::setTestNow('2026-11-14 10:00:00'); diff --git a/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php b/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php index 8e4deb47..4610c005 100644 --- a/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php +++ b/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php @@ -8,11 +8,8 @@ use App\Jobs\UpsertShopsPickupExceptionsUsingApiForYear; use App\Models\PickupException; use App\Models\Shop; use Domain\Enums\RepeatFrequency; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Http; -uses(RefreshDatabase::class); - it('throws an exception if the year is before 2026', function (): void { // GIVEN $invalidYear = 2025; diff --git a/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php b/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php index df486d24..1ab783d6 100644 --- a/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php +++ b/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php @@ -8,13 +8,10 @@ use App\Listeners\UpdateCustomerLastLogin; use App\Models\Customer; use Domain\Models\ValueObjects\Email; use Illuminate\Auth\Events\Login; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Date; use Ramsey\Uuid\Uuid; use Shared\ValueObjects\CrmHashcode; -uses(RefreshDatabase::class); - it('updates customer last_login_at via Executor when Login event is handled', function (): void { // GIVEN Date::setTestNow('2026-11-14 14:00:00'); diff --git a/tests/Integration/WithApp/App/Casts/CalendarDateCastTest.php b/tests/Integration/WithApp/App/Casts/CalendarDateCastTest.php index de39d0cf..a7a8e2ff 100644 --- a/tests/Integration/WithApp/App/Casts/CalendarDateCastTest.php +++ b/tests/Integration/WithApp/App/Casts/CalendarDateCastTest.php @@ -8,12 +8,9 @@ use App\Casts\CalendarDateCast; use App\Models\PickupException; use Carbon\CarbonImmutable; use Domain\Enums\RepeatFrequency; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\DB; -uses(RefreshDatabase::class); - describe('CalendarDateCast', function (): void { it('stores a calendar date without shifting Paris midnight back to the previous UTC day', function (): void { // GIVEN diff --git a/tests/Integration/WithApp/App/Casts/UtcDatetimeCastTest.php b/tests/Integration/WithApp/App/Casts/UtcDatetimeCastTest.php index 33c40945..fc644848 100644 --- a/tests/Integration/WithApp/App/Casts/UtcDatetimeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/UtcDatetimeCastTest.php @@ -9,13 +9,10 @@ use App\Models\Discount; use Carbon\CarbonImmutable; use Domain\Enums\DiscountType; use Domain\Models\ValueObjects\DiscountValue; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\DB; use Money\Money; -uses(RefreshDatabase::class); - describe('UtcDatetimeCast', function (): void { it('converts a non-UTC DateTimeInterface to UTC when persisted and reads it back in UTC', function (): void { // GIVEN diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php index 4fb64524..caf5c79f 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php @@ -23,7 +23,6 @@ use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Services\BasketService; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Session; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Infrastructure\Adapters\Locks\LaravelCacheLock; @@ -36,8 +35,6 @@ use Money\Money; use Psr\Log\NullLogger; use Ramsey\Uuid\Uuid; -uses(RefreshDatabase::class); - function makeBasketProductFixture(bool $status = true, bool $withInco = true): Product { $range = new Range(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php index d7ac48d7..eff12633 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php @@ -22,7 +22,6 @@ use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Services\BasketService; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Session; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Infrastructure\Adapters\Locks\LaravelCacheLock; @@ -35,8 +34,6 @@ use Money\Money; use Psr\Log\NullLogger; use Ramsey\Uuid\Uuid; -uses(RefreshDatabase::class); - describe('EmptyBasket action', function (): void { it('removes all items from session basket and clears order builder', function (): void { // GIVEN diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php index 70c49a01..5fbb9cc9 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php @@ -23,7 +23,6 @@ use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Services\BasketService; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Session; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Infrastructure\Adapters\Locks\LaravelCacheLock; @@ -36,8 +35,6 @@ use Money\Money; use Psr\Log\NullLogger; use Ramsey\Uuid\Uuid; -uses(RefreshDatabase::class); - function makeRemovableProductFixture(): Product { $range = new Range(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php index f9c30262..40c12fc3 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php @@ -12,14 +12,11 @@ use Domain\Enums\Country; use Domain\Exceptions\AuthServiceException; use Domain\Models\ValueObjects\CrmCustomer; use Domain\Models\ValueObjects\Email; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Auth; use Infrastructure\Adapters\Services\AppCustomerAuthService; use Ramsey\Uuid\Uuid; use Shared\ValueObjects\CrmHashcode; -uses(RefreshDatabase::class); - function makePasswordTestCrmCustomer(string $hashcode, string $email): CrmCustomer { return new CrmCustomer( diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php index 5d6e7bb8..ffa16dbe 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php @@ -12,15 +12,12 @@ use Domain\Enums\Country; use Domain\Exceptions\AuthServiceException; use Domain\Models\ValueObjects\CrmCustomer; use Domain\Models\ValueObjects\Email; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\ValidationException; use Infrastructure\Adapters\Services\AppCustomerAuthService; use Ramsey\Uuid\Uuid; use Shared\ValueObjects\CrmHashcode; -uses(RefreshDatabase::class); - function makeCrmCustomerDto(string $hashcode, string $email): CrmCustomer { return new CrmCustomer( diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php index 36245e62..46731116 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php @@ -22,7 +22,6 @@ use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository as CacheRepository; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\DB; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Infrastructure\Adapters\Locks\LaravelCacheLock; @@ -31,8 +30,6 @@ use Kwaadpepper\Serial\Converters\NativeBaseConverter; use Kwaadpepper\Serial\SerialCasterBuilder; use Psr\Log\NullLogger; -uses(RefreshDatabase::class); - describe('SynchronizeEmployeesWithArcadiaApi action', function (): void { it('executes outside a SQL transaction and preserves failed site cursor independently of succeeded sites', function (): void { // GIVEN diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php index b0c79da8..027abcdd 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php @@ -35,7 +35,6 @@ use Domain\Services\OrderService; use Domain\Services\OrderTunnelService; use Domain\Services\PickupSchedulingService; use Domain\Services\ShopperService; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Session; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; @@ -51,8 +50,6 @@ use Money\Money; use Ramsey\Uuid\Uuid; use Shared\ValueObjects\CrmHashcode; -uses(RefreshDatabase::class); - describe('ApplyPickTimeSlot action', function (): void { beforeEach(function (): void { $now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris'); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php index 101af0b3..3e639b20 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php @@ -18,14 +18,11 @@ use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Services\OrderService; -use Illuminate\Foundation\Testing\RefreshDatabase; use Infrastructure\Adapters\Repositories\EloquentOrderRepository; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; -uses(RefreshDatabase::class); - function makeCancelOrderFixture(OrderStatus $status = OrderStatus::VALIDATED): Order { $shop = Shop::factory()->create(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php index 9525c9a6..fb40e1b0 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php @@ -17,13 +17,10 @@ use Domain\Models\ValueObjects\OrderReference; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; -use Illuminate\Foundation\Testing\RefreshDatabase; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; -uses(RefreshDatabase::class); - describe('ClaimTodayOrderReminder action', function (): void { it('claims an unreminded validated order atomically and rejects duplicate claims', function (): void { // GIVEN diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php index aaef4497..dccc41d3 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php @@ -23,7 +23,6 @@ use Domain\Services\OrderService; use Domain\Services\OrderTunnelService; use Domain\Services\PickupSchedulingService; use Domain\Services\ShopperService; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Session; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Infrastructure\Adapters\Repositories\EloquentOrderRepository; @@ -37,8 +36,6 @@ use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; -uses(RefreshDatabase::class); - describe('InitializeOrderTunnel action', function (): void { it('stores OrderBuilderWithBasket in session for the shopper and basket', function (): void { // GIVEN diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php index 8f208810..7ff12a50 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -59,7 +59,6 @@ use Domain\Services\PickupSchedulingService; use Domain\Services\ShopperService; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\DB; @@ -84,8 +83,6 @@ use Shared\Concurrency\Lock; use Shared\Concurrency\LockTimeoutException; use Shared\ValueObjects\CrmHashcode; -uses(RefreshDatabase::class); - describe('Order placement two-step CQS actions', function (): void { beforeEach(function (): void { $now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris'); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php index 9054e998..82297be7 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php @@ -17,13 +17,10 @@ use Domain\Models\ValueObjects\OrderReference; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; -use Illuminate\Foundation\Testing\RefreshDatabase; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; -uses(RefreshDatabase::class); - describe('ReleaseTodayOrderReminder action', function (): void { it('releases reminded_at only when timestamp matches the claim timestamp', function (): void { // GIVEN diff --git a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php index a608d727..52e472d9 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php @@ -9,9 +9,6 @@ use App\Cqs\Actions\PickupExceptions\CreatePickupException; use App\Cqs\Actions\PickupExceptions\CreatePickupExceptionInput; use App\Models\PickupException; use Domain\Enums\RepeatFrequency; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('CreatePickupException action', function () { test('it creates and persists a pickup exception in database', function () { diff --git a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php index 97a684d6..7a6fcb0e 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php @@ -8,9 +8,6 @@ use App\Contracts\ActionInput; use App\Cqs\Actions\PickupExceptions\DeletePickupException; use App\Cqs\Actions\PickupExceptions\DeletePickupExceptionInput; use App\Models\PickupException; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('DeletePickupException action', function () { test('it deletes a pickup exception from database', function () { diff --git a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php index 010f23d2..3af3227b 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php @@ -9,9 +9,6 @@ use App\Cqs\Actions\PickupExceptions\UpdatePickupException; use App\Cqs\Actions\PickupExceptions\UpdatePickupExceptionInput; use App\Models\PickupException; use Domain\Enums\RepeatFrequency; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('UpdatePickupException action', function () { test('it updates and persists a pickup exception in database', function () { diff --git a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php index dc21993c..210ee3bd 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php @@ -20,11 +20,8 @@ use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; use Domain\Models\ValueObjects\NutritionalValues; -use Illuminate\Foundation\Testing\RefreshDatabase; use Money\Money; -uses(RefreshDatabase::class); - describe('AssociateProductInco action', function (): void { $createProduct = function (): Product { $range = new Range(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php index be4bcb85..9ad307d7 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php @@ -19,11 +19,8 @@ use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; use Domain\Models\ValueObjects\NutritionalValues; -use Illuminate\Foundation\Testing\RefreshDatabase; use Money\Money; -uses(RefreshDatabase::class); - describe('SyncProductInco action', function (): void { $createProduct = function (): Product { $range = new Range(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php index 0c39db03..563cb707 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php @@ -21,7 +21,6 @@ use Domain\Enums\Units\OrderUnit; use Domain\Models\ValueObjects\NutritionalValues; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository as CacheRepository; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\DB; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Infrastructure\Adapters\Locks\LaravelCacheLock; @@ -29,8 +28,6 @@ use Money\Money; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; -uses(RefreshDatabase::class); - describe('SynchronizeProductIncosWithArcadiaApi action', function (): void { $createProductWithInco = function (int $noArt): ProductInco { $range = new Range(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php index d97e3da7..1f406510 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php @@ -21,7 +21,6 @@ use Domain\Enums\Units\OrderUnit; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository; use Illuminate\Database\QueryException; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\UploadedFile; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Infrastructure\Adapters\Locks\LaravelCacheLock; @@ -31,8 +30,6 @@ use Shared\Filesystem\TemporaryFileFactory; use Uwil\Storage\Contracts\StorageService; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; -uses(RefreshDatabase::class); - function makeCreateProductRange(): Range { $range = new Range(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Products/DeleteProductTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Products/DeleteProductTest.php index 3e016a10..49fd2462 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Products/DeleteProductTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Products/DeleteProductTest.php @@ -13,13 +13,10 @@ use Domain\Enums\SellUnit; use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; -use Illuminate\Foundation\Testing\RefreshDatabase; use Money\Money; use Uwil\Storage\Contracts\StorageService; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; -uses(RefreshDatabase::class); - describe('DeleteProduct action', function (): void { it('soft-deletes a product while preserving S3 assets for order history and restoration', function (): void { // GIVEN diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Products/UpdateProductTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Products/UpdateProductTest.php index 689ee901..a2affc95 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Products/UpdateProductTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Products/UpdateProductTest.php @@ -19,7 +19,6 @@ use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\UploadedFile; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Infrastructure\Adapters\Locks\LaravelCacheLock; @@ -29,8 +28,6 @@ use Shared\Filesystem\TemporaryFileFactory; use Uwil\Storage\Contracts\StorageService; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; -uses(RefreshDatabase::class); - function makeUpdateProductFixture( ?StorageFilePath $picture = null, ?StorageFilePath $pictureLarge = null, diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php index 6ce58774..654085b2 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php @@ -14,7 +14,6 @@ use App\Services\ImageOptimizerService; use Domain\Models\ValueObjects\PictureMetadata; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\UploadedFile; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Infrastructure\Adapters\Locks\LaravelCacheLock; @@ -23,8 +22,6 @@ use Shared\Filesystem\TemporaryFileFactory; use Uwil\Storage\Contracts\StorageService; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; -uses(RefreshDatabase::class); - describe('CreateRange action', function () { test('it creates and persists a range in database', function () { /** @var \Tests\TestCase $this */ diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php index e7628efa..41339510 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php @@ -12,15 +12,12 @@ use App\Models\Range; use App\Services\ActionExecutorService; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository; -use Illuminate\Foundation\Testing\RefreshDatabase; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Infrastructure\Adapters\Locks\LaravelCacheLock; use Psr\Log\NullLogger; use Uwil\Storage\Contracts\StorageService; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; -uses(RefreshDatabase::class); - describe('DeleteRange action', function () { test('it deletes an existing range from database', function () { /** @var \Tests\TestCase $this */ diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php index 9e7547e3..cce8983d 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php @@ -15,7 +15,6 @@ use App\Services\PublicImageStorageService; use Domain\Models\ValueObjects\PictureMetadata; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\UploadedFile; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Infrastructure\Adapters\Locks\LaravelCacheLock; @@ -24,8 +23,6 @@ use Shared\Filesystem\TemporaryFileFactory; use Uwil\Storage\Contracts\StorageService; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; -uses(RefreshDatabase::class); - describe('UpdateRange action', function () { test('it updates an existing range in database', function () { /** @var \Tests\TestCase $this */ diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php index f39c80c0..73c84e4e 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php @@ -8,9 +8,6 @@ use App\Cqs\Actions\Settings\UpdateSettings; use App\Cqs\Actions\Settings\UpdateSettingsInput; use App\Models\Setting; use Domain\Models\ValueObjects\ShopperSiteCode; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('UpdateSettings', function (): void { it('updates employee sites configuration', function (): void { diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php index 79915c6f..5e1c9a40 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php @@ -11,11 +11,8 @@ use App\Models\PickupException; use Domain\Enums\RepeatFrequency; use Domain\Models\ValueObjects\Coordinates; use Domain\Models\ValueObjects\PhoneNumber; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Date; -uses(RefreshDatabase::class); - describe('CreateShop action', function () { test('it creates and persists a shop in database', function () { /** @var \Tests\TestCase $this */ diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php index a5fa0e69..9ed27f84 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php @@ -8,9 +8,6 @@ use App\Contracts\ActionInput; use App\Cqs\Actions\Shops\DeleteShop; use App\Cqs\Actions\Shops\DeleteShopInput; use App\Models\Shop; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('DeleteShop action', function () { test('it deletes a shop from database', function () { diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php index 45afee6f..467b8238 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php @@ -9,9 +9,6 @@ use App\Cqs\Actions\Shops\UpdateShopPickupExceptions; use App\Cqs\Actions\Shops\UpdateShopPickupExceptionsInput; use App\Models\PickupException; use App\Models\Shop; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('UpdateShopPickupExceptions action', function () { test('it syncs pickup exceptions for a shop', function () { diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php index 10809ad2..4e4154e5 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php @@ -10,9 +10,6 @@ use App\Cqs\Actions\Shops\UpdateShopInput; use App\Models\Shop; use Domain\Models\ValueObjects\Coordinates; use Domain\Models\ValueObjects\PhoneNumber; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('UpdateShop action', function () { test('it updates and persists a shop in database', function () { diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php index 3f08f406..7698b0fa 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php @@ -9,12 +9,9 @@ use App\Cqs\Queries\Customers\GetCustomerByEmailQueryInput; use App\Models\Customer; use Domain\Models\ValueObjects\Email; use Domain\Models\ValueObjects\Entities\ShopperId; -use Illuminate\Foundation\Testing\RefreshDatabase; use Ramsey\Uuid\Uuid; use Shared\ValueObjects\CrmHashcode; -uses(RefreshDatabase::class); - describe('GetCustomerByEmailQuery', function (): void { it('returns ShopperId when customer with email exists', function (): void { // GIVEN diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php index 83f145ca..179a739e 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php @@ -8,9 +8,6 @@ use App\Contracts\QueryInputEmpty; use App\Cqs\Queries\Faqs\GetFaqsQuery; use App\Dto\FaqDto; use App\Models\Faq; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('GetFaqsQuery', function (): void { it('returns a collection of FaqDto instances ordered by order', function (): void { diff --git a/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php index 7ecc3264..2c61bede 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php @@ -8,7 +8,6 @@ use App\Cqs\Queries\PickupExceptions\GetPaginatedPickupExceptionsQuery; use App\Cqs\Queries\PickupExceptions\GetPaginatedPickupExceptionsQueryInput; use App\Models\PickupException; use App\Services\DataTableService; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\Request; use Illuminate\Session\NullSessionHandler; use Illuminate\Session\Store; @@ -17,8 +16,6 @@ use Shared\Pagination\PageNumber; use Shared\Pagination\PageSize; use Shared\Pagination\Pagination; -uses(RefreshDatabase::class); - afterEach(function (): void { DataTableService::clearColumnsCache(); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoProductIndexPageQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoProductIndexPageQueryTest.php index e7ab32f1..01f43b0c 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoProductIndexPageQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoProductIndexPageQueryTest.php @@ -9,14 +9,11 @@ use App\Cqs\Queries\Products\GetFoProductIndexPageQueryInput; use App\Dto\RangeDto; use App\Models\Range; use App\Services\ProductDtoAssemblerService; -use Illuminate\Foundation\Testing\RefreshDatabase; use Infrastructure\Adapters\Repositories\EloquentProductRepository; use Shared\Pagination\PageNumber; use Shared\Pagination\PageSize; use Shared\Pagination\Pagination; -uses(RefreshDatabase::class); - describe('GetFoProductIndexPageQuery', function (): void { it('returns only published ranges and excludes disabled ranges', function (): void { // GIVEN diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php index 545346d3..371520e8 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php @@ -8,7 +8,6 @@ use App\Cqs\Queries\Ranges\GetPaginatedRangesQuery; use App\Cqs\Queries\Ranges\GetPaginatedRangesQueryInput; use App\Models\Range; use App\Services\DataTableService; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\Request; use Illuminate\Session\NullSessionHandler; use Illuminate\Session\Store; @@ -17,8 +16,6 @@ use Shared\Pagination\PageNumber; use Shared\Pagination\PageSize; use Shared\Pagination\Pagination; -uses(RefreshDatabase::class); - afterEach(function (): void { DataTableService::clearColumnsCache(); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php index 05bc7308..96923965 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php @@ -7,9 +7,6 @@ namespace Tests\Integration\WithApp\App\Cqs\Queries\Settings; use App\Contracts\QueryInputEmpty; use App\Cqs\Queries\Settings\GetSettingsQuery; use App\Models\Setting; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('GetSettingsQuery', function (): void { it('returns settings as SettingDto', function (): void { diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php index 2517f776..496782e7 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php @@ -10,7 +10,6 @@ use App\Dto\PickupExceptionDto; use App\Models\PickupException; use App\Models\Shop; use App\Services\DataTableService; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Http\Request; use Illuminate\Session\NullSessionHandler; use Illuminate\Session\Store; @@ -19,8 +18,6 @@ use Shared\Pagination\PageNumber; use Shared\Pagination\PageSize; use Shared\Pagination\Pagination; -uses(RefreshDatabase::class); - afterEach(function (): void { DataTableService::clearColumnsCache(); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php index 504bb341..3bac85c0 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php @@ -8,12 +8,9 @@ use App\Cqs\Queries\Shops\GetShopPickupExceptionsQuery; use App\Cqs\Queries\Shops\GetShopPickupExceptionsQueryInput; use App\Models\Shop; use Domain\Services\PickupSchedulingService; -use Illuminate\Foundation\Testing\RefreshDatabase; use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; use Infrastructure\Adapters\Repositories\EloquentShopRepository; -uses(RefreshDatabase::class); - describe('GetShopPickupExceptionsQuery', function () { test('it executes and returns pickup exceptions output for a shop', function () { // GIVEN diff --git a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php index d96b4167..eb3eaaf8 100644 --- a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php @@ -23,13 +23,10 @@ use Domain\Models\ValueObjects\ProductWeight; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Date; use Money\Money; use Ramsey\Uuid\Uuid; -uses(RefreshDatabase::class); - describe('OrderLineDto Integration', function (): void { test('it maps from OrderLine Eloquent model with correct unit price TTC and flattened product properties', function (): void { // GIVEN diff --git a/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php b/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php index 4f718747..8ce8b20e 100644 --- a/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php @@ -7,9 +7,6 @@ namespace Tests\Integration\WithApp\App\Dto; use App\Dto\PickupExceptionDto; use App\Models\PickupException; use App\Models\Shop; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('PickupExceptionDto Integration', function () { test('fromModel works without pivot loaded', function () { diff --git a/tests/Integration/WithApp/App/Dto/RangeDtoTest.php b/tests/Integration/WithApp/App/Dto/RangeDtoTest.php index 9c6747b5..f3bc055c 100644 --- a/tests/Integration/WithApp/App/Dto/RangeDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/RangeDtoTest.php @@ -6,9 +6,6 @@ namespace Tests\Integration\WithApp\App\Dto; use App\Dto\RangeDto; use App\Models\Range; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('RangeDto Integration', function () { test('it maps from Range Eloquent model correctly', function () { diff --git a/tests/Integration/WithApp/App/Dto/ShopDtoTest.php b/tests/Integration/WithApp/App/Dto/ShopDtoTest.php index 9e2cc1da..c9bdccca 100644 --- a/tests/Integration/WithApp/App/Dto/ShopDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/ShopDtoTest.php @@ -7,9 +7,6 @@ namespace Tests\Integration\WithApp\App\Dto; use App\Dto\ShopDto; use App\Models\PickupException; use App\Models\Shop; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('ShopDto Integration', function () { test('it maps from Shop Eloquent model correctly', function () { diff --git a/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php b/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php index 2eaba579..ac42c1a7 100644 --- a/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php +++ b/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php @@ -19,12 +19,9 @@ use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository as CacheRepository; -use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Carbon; use Psr\Log\NullLogger; -uses(RefreshDatabase::class); - afterEach(function (): void { \Mockery::close(); }); diff --git a/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php b/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php index 7c0108e8..e88ef850 100644 --- a/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php +++ b/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php @@ -14,13 +14,10 @@ use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Ports\Services\EmployeeImportStorageService; -use Illuminate\Foundation\Testing\RefreshDatabase; use Kwaadpepper\Serial\Converters\NativeBaseConverter; use Kwaadpepper\Serial\SerialCasterBuilder; use Psr\Log\NullLogger; -uses(RefreshDatabase::class); - afterEach(function (): void { \Mockery::close(); }); diff --git a/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php b/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php index e7e0a3a6..20beb25c 100644 --- a/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php +++ b/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php @@ -19,13 +19,10 @@ use Domain\Models\ValueObjects\OrderReference; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; -use Illuminate\Foundation\Testing\RefreshDatabase; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; -uses(RefreshDatabase::class); - covers(OrderOwnershipService::class); describe('OrderOwnershipService', function () { diff --git a/tests/Integration/WithApp/App/Services/StatsServiceTest.php b/tests/Integration/WithApp/App/Services/StatsServiceTest.php index c5582fad..06c904b1 100644 --- a/tests/Integration/WithApp/App/Services/StatsServiceTest.php +++ b/tests/Integration/WithApp/App/Services/StatsServiceTest.php @@ -29,13 +29,10 @@ use Domain\Models\ValueObjects\ProductWeight; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; -use Illuminate\Foundation\Testing\RefreshDatabase; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; -uses(RefreshDatabase::class); - covers(StatsService::class); describe('StatsService', function (): void { From c9d53f43c0e4869c9f30c3fe4333eb9d780e8d19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 15:49:48 +0100 Subject: [PATCH 144/183] test(clock): add global clock reset and freeze time across 22 test files --- .../Controllers/Bo/OrdersControllerTest.php | 12 +++++++++++ .../Controllers/Bo/ProductsControllerTest.php | 13 ++++++++++++ .../Fo/Auth/ForgotPasswordControllerTest.php | 15 +++++++++++++ .../Fo/Auth/LoginControllerTest.php | 15 +++++++++++++ .../Fo/Auth/ResetPasswordControllerTest.php | 15 +++++++++++++ .../Fo/Customers/CustomerControllerTest.php | 15 +++++++++++++ .../Fo/Customers/OrderControllerTest.php | 14 +++++++++++++ .../Fo/Pages/HomeControllerTest.php | 15 +++++++++++++ .../Auth/ResetCustomerPasswordTest.php | 15 +++++++++++++ .../Slides/GetPaginatedSlidesQueryTest.php | 12 +++++++++++ .../WithApp/App/Dto/OrderLineDtoTest.php | 15 +++++++++++++ .../Services/OrderOwnershipServiceTest.php | 15 +++++++++++++ .../WithApp/App/Services/StatsServiceTest.php | 15 +++++++++++++ tests/Pest.php | 21 +++++++++++++++++++ .../Unit/Domain/Models/Entities/OrderTest.php | 12 +++++++++++ .../Entities/PickupExceptionOnDateTest.php | 12 +++++++++++ .../Domain/Models/Entities/ProductTest.php | 12 +++++++++++ .../EditablePickupExceptionForShopTest.php | 12 +++++++++++ .../ValueObjects/EmployeeUpsertDataTest.php | 12 +++++++++++ .../ValueObjects/ShopPickupOverrideTest.php | 12 +++++++++++ .../Unit/Domain/Services/OrderServiceTest.php | 12 +++++++++++ .../Services/OrderTunnelServiceTest.php | 12 +++++++++++ .../Domain/Services/ShopperServiceTest.php | 12 +++++++++++ 23 files changed, 315 insertions(+) diff --git a/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php index 36cfc46d..f899a475 100644 --- a/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php @@ -11,6 +11,7 @@ use App\Models\Order; use App\Models\Shop; use App\Models\User; use App\Services\CrmService; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Domain\Enums\OrderStatus; use Domain\Enums\UserRole; @@ -34,10 +35,21 @@ describe('Bo\OrdersController', function (): void { beforeEach(function (): void { /** @var \Tests\TestCase $this */ // GIVEN + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); + $user = User::factory()->create(['role' => UserRole::SuperAdmin]); $this->actingAs($user, 'backend'); }); + afterEach(function (): void { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); + }); + it('can access index with paginated orders and filters', function (): void { /** @var \Tests\TestCase $this */ // GIVEN diff --git a/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php index 4d4db005..b34e12ef 100644 --- a/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php @@ -11,6 +11,8 @@ use App\Models\Product; use App\Models\Range; use App\Models\Tag; use App\Models\User; +use Carbon\Carbon; +use Carbon\CarbonImmutable; use Domain\Enums\DiscountType; use Domain\Enums\ProductBrand; use Domain\Enums\SellUnit; @@ -32,10 +34,21 @@ describe('ProductsController', function () { beforeEach(function () { // GIVEN /** @var \Tests\TestCase $this */ + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); + $this->user = User::factory()->create(['role' => UserRole::SuperAdmin]); $this->actingAs($this->user, 'backend'); }); + afterEach(function (): void { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); + }); + it('can access index', function () { // WHEN $this->withoutExceptionHandling(); diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php index 08ee2956..e8910776 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php @@ -7,6 +7,7 @@ namespace Tests\Feature\App\Http\Controllers\Fo\Auth; use App\Models\Customer; use App\Models\Page; use App\Services\CrmService; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Database\Seeders\ContentSeeder; use Domain\Enums\Country; @@ -21,6 +22,7 @@ use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Services\ShopperService; use Illuminate\Auth\Notifications\ResetPassword; use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\View; use Illuminate\Support\Str; @@ -35,6 +37,19 @@ function sharePagesForForgotPasswordTest(): void } describe('ForgotPasswordController', function () { + beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); + }); + + afterEach(function (): void { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); + }); + it('can access get /auth/mot-de-passe-oublie', function () { /** @var \Tests\TestCase $this */ // GIVEN diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php index a2578756..b916b3db 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php @@ -9,6 +9,7 @@ use App\Exceptions\CustomerNotEmployedException; use App\Models\Customer; use App\Models\Page; use App\Services\CrmService; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Database\Seeders\ContentSeeder; use Domain\Enums\Country; @@ -23,12 +24,26 @@ use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Services\ShopperService; use Illuminate\Auth\Notifications\VerifyEmail; use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\View; use Illuminate\Support\Str; use Shared\ValueObjects\CrmHashcode; describe('LoginController', function () { + beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); + }); + + afterEach(function (): void { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); + }); + it('can access get /auth/connexion', function () { /** @var \Tests\TestCase $this */ // GIVEN diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php index fa9e4714..7e667f55 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php @@ -8,6 +8,7 @@ use App\Exceptions\CustomerNotEmployedException; use App\Models\Customer; use App\Models\Page; use App\Services\CrmService; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Database\Seeders\ContentSeeder; use Domain\Enums\Country; @@ -22,11 +23,25 @@ use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Services\ShopperService; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Password; use Illuminate\Support\Facades\View; use Illuminate\Support\Str; describe('ResetPasswordController', function () { + beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); + }); + + afterEach(function (): void { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); + }); + it('can access get /auth/reinitialiser-mdp/1', function () { /** @var \Tests\TestCase $this */ // GIVEN diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php index f4e794e4..d9968874 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php @@ -8,6 +8,7 @@ use App\Models\Customer; use App\Models\Employee; use App\Models\Page; use App\Services\CrmService; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Database\Seeders\ContentSeeder; use Domain\Enums\Country; @@ -17,11 +18,25 @@ use Domain\Models\ValueObjects\Email; use Domain\Models\ValueObjects\Matricule; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\View; use Ramsey\Uuid\Uuid; use Shared\ValueObjects\CrmHashcode; describe('CustomerController', function () { + beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); + }); + + afterEach(function (): void { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); + }); + it('can access get /compte', function () { // GIVEN /** @var \Tests\TestCase $this */ diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php index 16b8dba1..7485c54c 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php @@ -11,6 +11,7 @@ use App\Models\Order; use App\Models\Page; use App\Models\Shop; use App\Services\CrmService; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Database\Seeders\ContentSeeder; use Domain\Enums\Country; @@ -36,6 +37,19 @@ use Ramsey\Uuid\Uuid; use Shared\ValueObjects\CrmHashcode; describe('OrderController', function () { + beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); + }); + + afterEach(function (): void { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); + }); + it('can access get /compte/commandes', function () { /** @var \Tests\TestCase $this */ // GIVEN diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php index 85288f82..4bc4f93e 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php @@ -9,6 +9,7 @@ use App\Models\Page; use App\Models\Product; use App\Models\Range; use App\Models\Slide; +use Carbon\CarbonImmutable; use Database\Seeders\ContentSeeder; use Domain\Enums\DiscountType; use Domain\Enums\ProductBrand; @@ -17,11 +18,25 @@ use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; use Domain\Models\ValueObjects\DiscountValue; use Illuminate\Support\Carbon; +use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\View; use Money\Money; use Ramsey\Uuid\Uuid; describe('HomeController', function () { + beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); + }); + + afterEach(function (): void { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); + }); + it('can access home page', function () { /** @var \Tests\TestCase $this */ // GIVEN diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php index c5816b62..c0cb1a00 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php @@ -8,6 +8,7 @@ use App\Cqs\Actions\Auth\ResetCustomerPassword; use App\Cqs\Actions\Auth\ResetCustomerPasswordInput; use App\Enums\ResetCustomerPasswordStatus; use App\Models\Customer; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Domain\Models\Entities\Shopper; use Domain\Models\ValueObjects\Email; @@ -17,10 +18,24 @@ use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Services\ShopperService; +use Illuminate\Support\Facades\Date; use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; use Infrastructure\Adapters\Services\AppCustomerAuthService; +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); + describe('ResetCustomerPassword action', function (): void { it('resets password, rotates remember_token and returns success output for active employee', function (): void { // GIVEN diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php index 4980139f..3bad50bb 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php @@ -9,6 +9,8 @@ use App\Cqs\Queries\Slides\GetPaginatedSlidesQueryInput; use App\Dto\SlideDto; use App\Models\Slide; use App\Services\DataTableService; +use Carbon\Carbon; +use Carbon\CarbonImmutable; use Illuminate\Http\Request; use Illuminate\Session\NullSessionHandler; use Illuminate\Session\Store; @@ -18,8 +20,18 @@ use Shared\Pagination\PageNumber; use Shared\Pagination\PageSize; use Shared\Pagination\Pagination; +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + afterEach(function (): void { DataTableService::clearColumnsCache(); + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); }); describe('GetPaginatedSlidesQuery', function (): void { diff --git a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php index eb3eaaf8..a7c33fda 100644 --- a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php @@ -8,6 +8,8 @@ use App\Dto\OrderLineDto; use App\Models\Order; use App\Models\OrderLine; use App\Models\Shop; +use Carbon\Carbon; +use Carbon\CarbonImmutable; use Domain\Enums\OrderStatus; use Domain\Enums\ProductBrand; use Domain\Enums\TaxRate; @@ -27,6 +29,19 @@ use Illuminate\Support\Facades\Date; use Money\Money; use Ramsey\Uuid\Uuid; +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); + describe('OrderLineDto Integration', function (): void { test('it maps from OrderLine Eloquent model with correct unit price TTC and flattened product properties', function (): void { // GIVEN diff --git a/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php b/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php index 20beb25c..52795a6e 100644 --- a/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php +++ b/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php @@ -8,6 +8,7 @@ use App\Models\Customer; use App\Models\Employee; use App\Models\Order; use App\Services\OrderOwnershipService; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Domain\Enums\OrderStatus; use Domain\Models\ValueObjects\Code; @@ -19,12 +20,26 @@ use Domain\Models\ValueObjects\OrderReference; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; +use Illuminate\Support\Facades\Date; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; covers(OrderOwnershipService::class); +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); + describe('OrderOwnershipService', function () { it('returns true if order is owned by customer', function () { // GIVEN diff --git a/tests/Integration/WithApp/App/Services/StatsServiceTest.php b/tests/Integration/WithApp/App/Services/StatsServiceTest.php index 06c904b1..7ed25a9c 100644 --- a/tests/Integration/WithApp/App/Services/StatsServiceTest.php +++ b/tests/Integration/WithApp/App/Services/StatsServiceTest.php @@ -9,6 +9,7 @@ use App\Models\Employee; use App\Models\Order; use App\Models\OrderLine; use App\Services\StatsService; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Domain\Enums\OrderStatus; use Domain\Enums\ProductBrand; @@ -29,12 +30,26 @@ use Domain\Models\ValueObjects\ProductWeight; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; +use Illuminate\Support\Facades\Date; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; covers(StatsService::class); +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); + describe('StatsService', function (): void { $createEmployee = function (int $id, string $matricule, ?Customer $customer = null, ?CarbonImmutable $createdAt = null): Employee { $timestamp = $createdAt ?? CarbonImmutable::now(); diff --git a/tests/Pest.php b/tests/Pest.php index 171cecd8..42a0452a 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -2,8 +2,11 @@ declare(strict_types=1); +use Carbon\Carbon; +use Carbon\CarbonImmutable; use DG\BypassFinals; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Http; use PHPUnit\Framework\TestCase as BasePHPUnitTestCase; use Tests\TestCase as LaravelTestCase; @@ -23,17 +26,35 @@ pest() ->beforeEach(function (): void { Http::preventStrayRequests(); }) + ->afterEach(function (): void { + Carbon::setTestNow(); + CarbonImmutable::setTestNow(); + Date::setTestNow(); + }) ->in('Feature'); pest() ->extend(LaravelTestCase::class) ->use(RefreshDatabase::class) + ->afterEach(function (): void { + Carbon::setTestNow(); + CarbonImmutable::setTestNow(); + Date::setTestNow(); + }) ->in('Integration/WithApp'); pest() ->extend(BasePHPUnitTestCase::class) + ->afterEach(function (): void { + Carbon::setTestNow(); + CarbonImmutable::setTestNow(); + }) ->in('Integration/Standalones'); pest() ->extend(BasePHPUnitTestCase::class) + ->afterEach(function (): void { + Carbon::setTestNow(); + CarbonImmutable::setTestNow(); + }) ->in('Unit'); diff --git a/tests/Unit/Domain/Models/Entities/OrderTest.php b/tests/Unit/Domain/Models/Entities/OrderTest.php index 6024e0b7..ac2572c3 100644 --- a/tests/Unit/Domain/Models/Entities/OrderTest.php +++ b/tests/Unit/Domain/Models/Entities/OrderTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\Entities; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Domain\Enums\OrderStatus; use Domain\Enums\ProductBrand; @@ -97,6 +98,17 @@ function makeOrder(array $overrides = []): Order ); } +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); + describe('Order - Instantiation', function (): void { it('can instantiate a valid order', function (): void { diff --git a/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php b/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php index 24331f24..33aaebec 100644 --- a/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php +++ b/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php @@ -4,12 +4,24 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\Entities; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Domain\Enums\RepeatFrequency; use Domain\Models\Entities\PickupExceptionOnDate; use Domain\Models\ValueObjects\Entities\PickupExceptionId; use Ramsey\Uuid\Uuid; +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); + describe('PickupExceptionOnDate', function (): void { it('can instantiate correctly', function (): void { // GIVEN diff --git a/tests/Unit/Domain/Models/Entities/ProductTest.php b/tests/Unit/Domain/Models/Entities/ProductTest.php index 8dea4710..ce8d49de 100644 --- a/tests/Unit/Domain/Models/Entities/ProductTest.php +++ b/tests/Unit/Domain/Models/Entities/ProductTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\Entities; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Domain\Enums\SellUnit; use Domain\Enums\TaxRate; @@ -42,6 +43,17 @@ function makeProduct( ); } +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); + describe('Product', function (): void { it('can instantiate correctly', function (): void { // GIVEN diff --git a/tests/Unit/Domain/Models/ValueObjects/EditablePickupExceptionForShopTest.php b/tests/Unit/Domain/Models/ValueObjects/EditablePickupExceptionForShopTest.php index d0c649d9..aeecf155 100644 --- a/tests/Unit/Domain/Models/ValueObjects/EditablePickupExceptionForShopTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/EditablePickupExceptionForShopTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\ValueObjects; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Domain\Enums\RepeatFrequency; use Domain\Models\Entities\PickupExceptionOnDate; @@ -11,6 +12,17 @@ use Domain\Models\ValueObjects\EditablePickupExceptionForShop; use Domain\Models\ValueObjects\Entities\PickupExceptionId; use Ramsey\Uuid\Uuid; +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); + describe('EditablePickupExceptionForShop', function (): void { it('can instantiate and clones the exception', function (): void { // GIVEN diff --git a/tests/Unit/Domain/Models/ValueObjects/EmployeeUpsertDataTest.php b/tests/Unit/Domain/Models/ValueObjects/EmployeeUpsertDataTest.php index 89091dc6..37195c17 100644 --- a/tests/Unit/Domain/Models/ValueObjects/EmployeeUpsertDataTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/EmployeeUpsertDataTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\ValueObjects; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Domain\Models\ValueObjects\Code; use Domain\Models\ValueObjects\EmployeeUpsertData; @@ -12,6 +13,17 @@ use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); + describe('EmployeeUpsertData', function (): void { it('can be instantiated', function (): void { // GIVEN diff --git a/tests/Unit/Domain/Models/ValueObjects/ShopPickupOverrideTest.php b/tests/Unit/Domain/Models/ValueObjects/ShopPickupOverrideTest.php index 678f9a27..e821d0cb 100644 --- a/tests/Unit/Domain/Models/ValueObjects/ShopPickupOverrideTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/ShopPickupOverrideTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\ValueObjects; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Domain\Enums\RepeatFrequency; use Domain\Models\Entities\PickupExceptionOnDate; @@ -11,6 +12,17 @@ use Domain\Models\ValueObjects\Entities\PickupExceptionId; use Domain\Models\ValueObjects\ShopPickupOverride; use Ramsey\Uuid\Uuid; +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); + describe('ShopPickupOverride', function (): void { it('can instantiate correctly', function (): void { // GIVEN diff --git a/tests/Unit/Domain/Services/OrderServiceTest.php b/tests/Unit/Domain/Services/OrderServiceTest.php index fb4c48a8..e6a90b71 100644 --- a/tests/Unit/Domain/Services/OrderServiceTest.php +++ b/tests/Unit/Domain/Services/OrderServiceTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Services; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Domain\Enums\OrderStatus; use Domain\Enums\ProductBrand; @@ -41,6 +42,17 @@ use Ramsey\Uuid\Uuid; use Shared\Helpers\UuidHelper; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); + describe('Order Cancellation', function () { it('cancels a validated order successfully', function () { // GIVEN diff --git a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php index 915079e2..977609bf 100644 --- a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php +++ b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Services; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\WeekDay; use Domain\Builders\OrderBuilder; @@ -182,6 +183,17 @@ function createOrderTunnelService( ); } +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); + describe('OrderTunnelService', function (): void { it('allows access to BOOKING step when builder is from basket and has items', function (): void { // GIVEN diff --git a/tests/Unit/Domain/Services/ShopperServiceTest.php b/tests/Unit/Domain/Services/ShopperServiceTest.php index 6d1500e5..74955a85 100644 --- a/tests/Unit/Domain/Services/ShopperServiceTest.php +++ b/tests/Unit/Domain/Services/ShopperServiceTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Services; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Domain\Models\Entities\Shop; use Domain\Models\Entities\Shopper; @@ -20,6 +21,17 @@ use Domain\Services\ShopperService; use Mockery; use Ramsey\Uuid\Uuid; +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); + describe('ShopperService', function (): void { it('gets shopper for id', function (): void { From a4f2343eb27af3bedf3b35a18cb42af76a0844ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 15:54:41 +0100 Subject: [PATCH 145/183] test(eloquent,container): use Model::query() and direct dependency instantiation --- .../Controllers/Bo/OrdersControllerTest.php | 24 +++++++++---------- .../Fo/Ajax/BasketControllerTest.php | 20 ++++++++++++---- .../Fo/Auth/LoginControllerTest.php | 6 ++--- .../Fo/Customers/CustomerControllerTest.php | 8 +++---- .../Fo/Customers/OrderControllerTest.php | 12 +++++----- .../Jobs/SendMissingOrderReminderJobTest.php | 2 +- .../Feature/App/Jobs/SendReminderMailTest.php | 2 +- .../Listeners/UpdateCustomerLastLoginTest.php | 12 +++++++++- .../Orders/ClaimTodayOrderReminderTest.php | 2 +- .../Actions/Orders/PlacePendingOrderTest.php | 21 +++++++++------- .../WithApp/App/Dto/OrderLineDtoTest.php | 2 +- .../Services/OrderOwnershipServiceTest.php | 16 ++++++------- .../WithApp/App/Services/StatsServiceTest.php | 12 +++++----- .../Directories/EloquentShopDirectoryTest.php | 6 ++--- .../EloquentPickupExceptionRepositoryTest.php | 10 ++++---- .../EloquentShopRepositoryTest.php | 14 +++++------ .../EloquentShopperRepositoryTest.php | 14 +++++------ .../SessionBasketRepositoryTest.php | 8 ++++++- ...oquentEmployeeImportStorageServiceTest.php | 6 ++--- 19 files changed, 115 insertions(+), 82 deletions(-) diff --git a/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php index f899a475..8173a078 100644 --- a/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php @@ -54,7 +54,7 @@ describe('Bo\OrdersController', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $shop = Shop::factory()->create(['name' => 'Boutique Test']); - Order::forceCreate([ + Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'shop_id' => $shop->id, 'reference' => new OrderReference(Uuid::uuid7()), @@ -81,7 +81,7 @@ describe('Bo\OrdersController', function (): void { // GIVEN $shop = Shop::factory()->create(['name' => 'Boutique Pagination']); for ($i = 0; $i < 30; $i++) { - Order::forceCreate([ + Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'shop_id' => $shop->id, 'reference' => new OrderReference(Uuid::uuid7()), @@ -111,7 +111,7 @@ describe('Bo\OrdersController', function (): void { $reference = new OrderReference($refUuid); $ref = (string) $reference; $shop = Shop::factory()->create(['name' => 'UniqueShopSearch']); - Order::forceCreate([ + Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'shop_id' => $shop->id, 'reference' => $reference, @@ -139,7 +139,7 @@ describe('Bo\OrdersController', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $shop = Shop::factory()->create(); - $olderOrder = Order::forceCreate([ + $olderOrder = Order::query()->forceCreate([ 'id' => Uuid::uuid7(Date::now()->subHours(2))->toString(), 'shop_id' => $shop->id, 'reference' => new OrderReference(Uuid::uuid7()), @@ -149,7 +149,7 @@ describe('Bo\OrdersController', function (): void { 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->addDays(7)->toDateString(), ]); - $newerOrder = Order::forceCreate([ + $newerOrder = Order::query()->forceCreate([ 'id' => Uuid::uuid7(Date::now())->toString(), 'shop_id' => $shop->id, 'reference' => new OrderReference(Uuid::uuid7()), @@ -175,7 +175,7 @@ describe('Bo\OrdersController', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $shop = Shop::factory()->create(); - $todayOrder = Order::forceCreate([ + $todayOrder = Order::query()->forceCreate([ 'id' => Uuid::uuid7(Date::now())->toString(), 'shop_id' => $shop->id, 'reference' => new OrderReference(Uuid::uuid7()), @@ -185,7 +185,7 @@ describe('Bo\OrdersController', function (): void { 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->addDays(7)->toDateString(), ]); - $pastOrder = Order::forceCreate([ + $pastOrder = Order::query()->forceCreate([ 'id' => Uuid::uuid7(Date::now()->subDays(3))->toString(), 'shop_id' => $shop->id, 'reference' => new OrderReference(Uuid::uuid7()), @@ -212,12 +212,12 @@ describe('Bo\OrdersController', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $shop = Shop::factory()->create(); - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'hashcode' => Uuid::uuid4()->toString(), 'email' => new Email('customer@example.com'), ]); - Employee::forceCreate([ + Employee::query()->forceCreate([ 'id' => 9991, 'customer_id' => $customer->id, 'matricule' => new Matricule('1000999'), @@ -235,7 +235,7 @@ describe('Bo\OrdersController', function (): void { $crmMock->shouldReceive('getCustomerFromHashCode')->andReturn(null); App::instance(CrmService::class, $crmMock); - $order = Order::forceCreate([ + $order = Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'shop_id' => $shop->id, 'reference' => new OrderReference(Uuid::uuid7()), @@ -259,7 +259,7 @@ describe('Bo\OrdersController', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $shop = Shop::factory()->create(); - $order = Order::forceCreate([ + $order = Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'shop_id' => $shop->id, 'reference' => new OrderReference(Uuid::uuid7()), @@ -298,7 +298,7 @@ describe('Bo\OrdersController', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $shop = Shop::factory()->create(); - $order = Order::forceCreate([ + $order = Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'shop_id' => $shop->id, 'reference' => new OrderReference(Uuid::uuid7()), diff --git a/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php index 8bc7fc11..5f4034d0 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php @@ -18,11 +18,16 @@ use Domain\Models\ValueObjects\BasketProduct; use Domain\Models\ValueObjects\DiscountRate; use Domain\Models\ValueObjects\Email; use Domain\Models\ValueObjects\Entities\ProductId; -use Domain\Ports\Repositories\BasketRepository; use Domain\Services\BasketService; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\View; +use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; +use Infrastructure\Adapters\Repositories\EloquentProductRepository; +use Infrastructure\Adapters\Repositories\SessionBasketRepository; +use Infrastructure\Adapters\Serializers\BasketSerializer; +use Infrastructure\Adapters\Services\AppSessionService; use Money\Money; use Ramsey\Uuid\Uuid; @@ -119,9 +124,16 @@ describe('BasketController', function () { $range->picture_title = 'title'; $range->save(); - $basketService = resolve(BasketService::class); - $basketRepository = resolve(BasketRepository::class); - $basket = $basketService->getBasket(); + /** @var \Illuminate\Contracts\Session\Session $session */ + $session = Session::driver(); + $basketRepository = new SessionBasketRepository($session, 'basket_', new BasketSerializer()); + $basketService = new BasketService( + $basketRepository, + new EloquentProductRepository(), + new AppSessionService('domain_session_uuid'), + new LaravelDomainEventDispatcher(), + ); + $basket = $basketService->getBasket(); for ($i = 1; $i <= 5; $i++) { $product = new Product([ diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php index b916b3db..3ad1d4fb 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php @@ -139,7 +139,7 @@ describe('LoginController', function () { ])); Cache::flush(); - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'email' => new Email('test@example.com'), 'hashcode' => (string) Str::uuid(), ]); @@ -191,7 +191,7 @@ describe('LoginController', function () { ])); Cache::flush(); - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'email' => new Email('test2@example.com'), 'hashcode' => (string) Str::uuid(), ]); @@ -263,7 +263,7 @@ describe('LoginController', function () { ])); Cache::flush(); - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'email' => new Email('unverified@example.com'), 'hashcode' => (string) Str::uuid(), ]); diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php index d9968874..e34efc43 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php @@ -123,13 +123,13 @@ describe('CustomerController', function () { Cache::flush(); $hashcode = new CrmHashcode(Uuid::uuid4()); - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'hashcode' => $hashcode->value, 'email' => new Email('jean.dupont@example.com'), ]); - Employee::forceCreate([ + Employee::query()->forceCreate([ 'id' => 8882, 'customer_id' => $customer->id, 'matricule' => new Matricule('8888002'), @@ -189,13 +189,13 @@ describe('CustomerController', function () { Cache::flush(); $hashcode = new CrmHashcode(Uuid::uuid4()); - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'hashcode' => $hashcode->value, 'email' => new Email('jean.dupont@example.com'), ]); - Employee::forceCreate([ + Employee::query()->forceCreate([ 'id' => 8883, 'customer_id' => $customer->id, 'matricule' => new Matricule('8888003'), diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php index 7485c54c..ce6063f9 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php @@ -111,13 +111,13 @@ describe('OrderController', function () { Cache::flush(); $hashcode = new CrmHashcode(Uuid::uuid4()); - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'hashcode' => $hashcode->value, 'email' => new Email('verified@example.com'), ]); - Employee::forceCreate([ + Employee::query()->forceCreate([ 'id' => 8881, 'customer_id' => $customer->id, 'matricule' => new Matricule('8888001'), @@ -135,7 +135,7 @@ describe('OrderController', function () { $refUuid = Uuid::uuid7(); $reference = new OrderReference($refUuid); $ref = (string) $reference; - Order::forceCreate([ + Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'shop_id' => $shop->id, 'reference' => $reference, @@ -194,13 +194,13 @@ describe('OrderController', function () { Cache::flush(); $hashcode = new CrmHashcode(Uuid::uuid4()); - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'hashcode' => $hashcode->value, 'email' => new Email('verified_show@example.com'), ]); - Employee::forceCreate([ + Employee::query()->forceCreate([ 'id' => 8882, 'customer_id' => $customer->id, 'matricule' => new Matricule('8888002'), @@ -218,7 +218,7 @@ describe('OrderController', function () { $refUuid = Uuid::uuid7(); $reference = new OrderReference($refUuid); $ref = (string) $reference; - $order = Order::forceCreate([ + $order = Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'shop_id' => $shop->id, 'reference' => $reference, diff --git a/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php b/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php index 333c2b40..9628d687 100644 --- a/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php +++ b/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php @@ -193,7 +193,7 @@ describe('SendMissingOrderReminderJob', function (): void { 'end_date' => CarbonImmutable::now()->addMonth(), ]); - Order::forceCreate([ + Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'shop_id' => $shop->id, 'reference' => new OrderReference(Uuid::uuid7()), diff --git a/tests/Feature/App/Jobs/SendReminderMailTest.php b/tests/Feature/App/Jobs/SendReminderMailTest.php index 064f44f7..6a9992ca 100644 --- a/tests/Feature/App/Jobs/SendReminderMailTest.php +++ b/tests/Feature/App/Jobs/SendReminderMailTest.php @@ -59,7 +59,7 @@ describe('SendReminderMail job', function (): void { 'service' => new ShopperServiceCode('01'), ]); - $order = Order::forceCreate([ + $order = Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'shop_id' => $shop->id, 'reference' => new OrderReference(Uuid::uuid7()), diff --git a/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php b/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php index 1ab783d6..55afe162 100644 --- a/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php +++ b/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php @@ -4,12 +4,17 @@ declare(strict_types=1); namespace Tests\Feature\App\Listeners; +use App\Cqs\Actions\Customers\UpdateCustomerLastLogin as UpdateCustomerLastLoginAction; use App\Listeners\UpdateCustomerLastLogin; use App\Models\Customer; +use App\Services\ActionExecutorService; use Domain\Models\ValueObjects\Email; use Illuminate\Auth\Events\Login; use Illuminate\Support\Facades\Date; +use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; +use Psr\Log\NullLogger; use Ramsey\Uuid\Uuid; +use Shared\Concurrency\Lock; use Shared\ValueObjects\CrmHashcode; it('updates customer last_login_at via Executor when Login event is handled', function (): void { @@ -21,7 +26,12 @@ it('updates customer last_login_at via Executor when Login event is handled', fu $customer->last_login_at = null; $customer->saveOrFail(); - $listener = app(UpdateCustomerLastLogin::class); + $executor = new ActionExecutorService( + lock: \Mockery::mock(Lock::class), + logger: new NullLogger(), + eventDispatcher: new LaravelDomainEventDispatcher(), + ); + $listener = new UpdateCustomerLastLogin($executor, new UpdateCustomerLastLoginAction()); // WHEN $listener->handle(new Login('frontend', $customer, false)); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php index fb40e1b0..0f8c5c38 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php @@ -25,7 +25,7 @@ describe('ClaimTodayOrderReminder action', function (): void { it('claims an unreminded validated order atomically and rejects duplicate claims', function (): void { // GIVEN $shop = Shop::factory()->create(); - $order = Order::forceCreate([ + $order = Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'shop_id' => $shop->id, 'reference' => new OrderReference(Uuid::uuid7()), diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php index 7ff12a50..3ad7603b 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -72,6 +72,9 @@ use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; use Infrastructure\Adapters\Repositories\EloquentProductRepository; use Infrastructure\Adapters\Repositories\EloquentShopperRepository; use Infrastructure\Adapters\Repositories\EloquentShopRepository; +use Infrastructure\Adapters\Repositories\SessionBasketRepository; +use Infrastructure\Adapters\Serializers\BasketSerializer; +use Infrastructure\Adapters\Services\AppSessionService; use Infrastructure\Adapters\Services\CsvGeneratorImpl; use Infrastructure\Adapters\Services\EloquentEmployeeStatisticsService; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; @@ -189,15 +192,20 @@ describe('Order placement two-step CQS actions', function (): void { $inco->no_art = 778800 + $sequence; $inco->saveOrFail(); - /** @var BasketService $basketService */ - $basketService = resolve(BasketService::class); + /** @var \Illuminate\Contracts\Session\Session $session */ + $session = Session::driver(); + $basketRepo = new SessionBasketRepository($session, 'basket_', new BasketSerializer()); + $dispatcher = new LaravelDomainEventDispatcher(); + $basketService = new BasketService( + $basketRepo, + new EloquentProductRepository(), + new AppSessionService('domain_session_uuid'), + $dispatcher, + ); $basketService->empty(); $basketService->add($product->getId(), $qty); $basket = $basketService->getBasket(); - /** @var BasketRepository $basketRepo */ - $basketRepo = resolve(BasketRepository::class); - $slot = new PickupTimeSlot( $pickupAt ?? CarbonImmutable::parse('2026-11-20 14:00:00', 'Europe/Paris'), new \DateInterval('PT2H'), @@ -206,12 +214,9 @@ describe('Order placement two-step CQS actions', function (): void { $builder = OrderBuilder::fromBasket($basket, $customer->getId()) ->withPickupTimeSlot($shop->getId(), $slot); - /** @var \Illuminate\Contracts\Session\Session $session */ - $session = Session::driver(); $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); $builderManager->save($builder); - $dispatcher = new LaravelDomainEventDispatcher(); $shopRepo = new EloquentShopRepository(); $shopperRepo = new EloquentShopperRepository(); $orderRepo = new EloquentOrderRepository(); diff --git a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php index a7c33fda..e3743241 100644 --- a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php @@ -46,7 +46,7 @@ describe('OrderLineDto Integration', function (): void { test('it maps from OrderLine Eloquent model with correct unit price TTC and flattened product properties', function (): void { // GIVEN $shop = Shop::factory()->create(); - $order = Order::forceCreate([ + $order = Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'shop_id' => $shop->id, 'reference' => new OrderReference(Uuid::uuid7()), diff --git a/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php b/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php index 52795a6e..87981f17 100644 --- a/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php +++ b/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php @@ -43,13 +43,13 @@ afterEach(function (): void { describe('OrderOwnershipService', function () { it('returns true if order is owned by customer', function () { // GIVEN - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'hashcode' => Uuid::uuid4()->toString(), 'email' => new Email('owner@example.com'), ]); - Employee::forceCreate([ + Employee::query()->forceCreate([ 'id' => 301, 'customer_id' => $customer->id, 'matricule' => new Matricule('1000301'), @@ -63,7 +63,7 @@ describe('OrderOwnershipService', function () { 'updated_at' => CarbonImmutable::now(), ]); - $order = Order::forceCreate([ + $order = Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, @@ -83,13 +83,13 @@ describe('OrderOwnershipService', function () { it('returns false if order is not owned by customer', function () { // GIVEN - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'hashcode' => Uuid::uuid4()->toString(), 'email' => new Email('notowner@example.com'), ]); - Employee::forceCreate([ + Employee::query()->forceCreate([ 'id' => 302, 'customer_id' => $customer->id, 'matricule' => new Matricule('1000302'), @@ -103,7 +103,7 @@ describe('OrderOwnershipService', function () { 'updated_at' => CarbonImmutable::now(), ]); - $order = Order::forceCreate([ + $order = Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, @@ -123,13 +123,13 @@ describe('OrderOwnershipService', function () { it('returns false if customer has no employee', function () { // GIVEN - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'hashcode' => Uuid::uuid4()->toString(), 'email' => new Email('noemp@example.com'), ]); - $order = Order::forceCreate([ + $order = Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, diff --git a/tests/Integration/WithApp/App/Services/StatsServiceTest.php b/tests/Integration/WithApp/App/Services/StatsServiceTest.php index 7ed25a9c..d7b23aa7 100644 --- a/tests/Integration/WithApp/App/Services/StatsServiceTest.php +++ b/tests/Integration/WithApp/App/Services/StatsServiceTest.php @@ -56,7 +56,7 @@ describe('StatsService', function (): void { $codeSuffix = str_replace('0', '9', (string) $id); - return Employee::forceCreate([ + return Employee::query()->forceCreate([ 'id' => $id, 'customer_id' => $customer?->id, 'matricule' => new Matricule($matricule), @@ -78,7 +78,7 @@ describe('StatsService', function (): void { ?CarbonImmutable $pickupDay = null, int $totalCents = 1000, ): Order { - return Order::forceCreate([ + return Order::query()->forceCreate([ 'id' => Uuid::uuid7($createdAt)->toString(), 'reference' => new OrderReference(Uuid::uuid7()), 'status' => $status->value, @@ -101,7 +101,7 @@ describe('StatsService', function (): void { $service = new StatsService(new Currency('EUR')); expect($service->getMembershipPercentage())->toBe(0.0); - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'hashcode' => Uuid::uuid4()->toString(), 'email' => new Email('member@example.com'), @@ -124,7 +124,7 @@ describe('StatsService', function (): void { $now = CarbonImmutable::now(); $inRange = $now->subDays(3); $outRange = $now->subDays(20); - $customer1 = Customer::forceCreate([ + $customer1 = Customer::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'hashcode' => Uuid::uuid4()->toString(), 'email' => new Email('range1@example.com'), @@ -150,7 +150,7 @@ describe('StatsService', function (): void { // GIVEN $service = new StatsService(new Currency('EUR')); $now = CarbonImmutable::now(); - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'hashcode' => Uuid::uuid4()->toString(), 'email' => new Email('stats@example.com'), @@ -184,7 +184,7 @@ describe('StatsService', function (): void { priceKgTtc: new Money(1055, new Currency('EUR')), taxRate: TaxRate::TVA_5_5, ); - OrderLine::forceCreate([ + OrderLine::query()->forceCreate([ 'order_id' => $validatedOrder->id, 'product' => $productVo, 'quantity' => 2, diff --git a/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php index 4fb2594d..33899d21 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php @@ -11,14 +11,14 @@ use Ramsey\Uuid\Uuid; it('retrieves all available shops', function () { // GIVEN - Shop::forceCreate([ + Shop::query()->forceCreate([ 'name' => 'Shop 1', 'address' => 'Addr 1', 'postcode' => '75000', 'city' => 'Paris', 'default' => false, ]); - Shop::forceCreate([ + Shop::query()->forceCreate([ 'name' => 'Shop 2', 'address' => 'Addr 2', 'postcode' => '75001', @@ -36,7 +36,7 @@ it('retrieves all available shops', function () { it('finds a shop by its identifier', function () { // GIVEN - $model = Shop::forceCreate([ + $model = Shop::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'name' => 'Shop X', 'address' => 'Addr X', diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php index a2c0386a..4e316351 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php @@ -16,10 +16,10 @@ use Ramsey\Uuid\Uuid; it('retrieves exceptions within a period for a shop', function () { // GIVEN $shopUuid = Uuid::uuid7(); - $shop = Shop::forceCreate(['id' => $shopUuid->toString(), 'name' => 'Shop 1', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); + $shop = Shop::query()->forceCreate(['id' => $shopUuid->toString(), 'name' => 'Shop 1', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); $exUuid = Uuid::uuid7(); - $ex1 = PickupException::forceCreate([ + $ex1 = PickupException::query()->forceCreate([ 'id' => $exUuid->toString(), 'date' => '2023-01-10', 'label' => 'Fermé', @@ -53,7 +53,7 @@ it('retrieves exceptions within a period for a shop', function () { it('retrieves all exceptions', function () { // GIVEN $exUuid = Uuid::uuid7(); - PickupException::forceCreate([ + PickupException::query()->forceCreate([ 'id' => $exUuid->toString(), 'date' => '2023-01-10', 'label' => 'Fermé', @@ -75,10 +75,10 @@ it('retrieves all exceptions', function () { it('retrieves exceptions associated with a shop', function () { // GIVEN $shopUuid = Uuid::uuid7(); - $shop = Shop::forceCreate(['id' => $shopUuid->toString(), 'name' => 'Shop 1', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); + $shop = Shop::query()->forceCreate(['id' => $shopUuid->toString(), 'name' => 'Shop 1', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); $exUuid = Uuid::uuid7(); - $ex1 = PickupException::forceCreate([ + $ex1 = PickupException::query()->forceCreate([ 'id' => $exUuid->toString(), 'date' => '2023-01-10', 'label' => 'Fermé', diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php index 11cd22c6..d8c6c75a 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php @@ -18,7 +18,7 @@ use Ramsey\Uuid\Uuid; it('finds exception shop for a matricule', function () { // GIVEN - $shop = Shop::forceCreate([ + $shop = Shop::query()->forceCreate([ 'name' => 'Shop X', 'address' => 'Addr X', 'postcode' => '75000', @@ -26,7 +26,7 @@ it('finds exception shop for a matricule', function () { 'default' => false, ]); - Employee::forceCreate([ + Employee::query()->forceCreate([ 'matricule' => new Matricule('1234567'), 'nom' => 'Doe', 'prenom' => 'John', @@ -63,7 +63,7 @@ it('returns null if exception shop is not found', function () { it('finds shop for site and service', function () { // GIVEN - $shop = Shop::forceCreate([ + $shop = Shop::query()->forceCreate([ 'name' => 'Shop Y', 'address' => 'Addr Y', 'postcode' => '75000', @@ -89,7 +89,7 @@ it('finds shop for site and service', function () { it('finds shop for site and null service', function () { // GIVEN - $shop = Shop::forceCreate([ + $shop = Shop::query()->forceCreate([ 'name' => 'Shop Z', 'address' => 'Addr Z', 'postcode' => '75000', @@ -126,7 +126,7 @@ it('returns null if shop for site and service is not found', function () { it('finds shop by id', function () { // GIVEN - $shop = Shop::forceCreate([ + $shop = Shop::query()->forceCreate([ 'name' => 'Shop 1', 'address' => 'Addr 1', 'postcode' => '75000', @@ -157,7 +157,7 @@ it('returns null if shop by id is not found', function () { it('retrieves default shop', function () { // GIVEN - Shop::forceCreate([ + Shop::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'name' => 'Shop 1', 'address' => 'Addr 1', @@ -165,7 +165,7 @@ it('retrieves default shop', function () { 'city' => 'Paris', 'default' => false, ]); - $defaultShop = Shop::forceCreate([ + $defaultShop = Shop::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'name' => 'Shop Default', 'address' => 'Addr Default', diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php index 782a66dd..b4fa6011 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php @@ -22,13 +22,13 @@ it('retrieves shopper by id', function () { // GIVEN $uuid = Uuid::uuid7()->toString(); - Customer::forceCreate([ + Customer::query()->forceCreate([ 'id' => $uuid, 'email' => new Email('test@example.com'), 'hashcode' => Uuid::uuid4()->toString(), ]); - Employee::forceCreate([ + Employee::query()->forceCreate([ 'customer_id' => $uuid, 'matricule' => new Matricule('1234567'), 'nom' => 'Doe', @@ -64,7 +64,7 @@ it('returns null if customer exists but has no employee', function () { // GIVEN $uuid = Uuid::uuid7()->toString(); - Customer::forceCreate([ + Customer::query()->forceCreate([ 'id' => $uuid, 'email' => new Email('test@example.com'), 'hashcode' => Uuid::uuid4()->toString(), @@ -83,13 +83,13 @@ it('retrieves shopper by id or fails', function () { // GIVEN $uuid = Uuid::uuid7()->toString(); - Customer::forceCreate([ + Customer::query()->forceCreate([ 'id' => $uuid, 'email' => new Email('test@example.com'), 'hashcode' => Uuid::uuid4()->toString(), ]); - Employee::forceCreate([ + Employee::query()->forceCreate([ 'customer_id' => $uuid, 'matricule' => new Matricule('1234569'), 'nom' => 'Doe', @@ -127,13 +127,13 @@ it('persists updates to both customer and associated employee', function () { $uuid = Uuid::uuid7()->toString(); $shopperId = new ShopperId(Uuid::fromString($uuid)); - Customer::forceCreate([ + Customer::query()->forceCreate([ 'id' => $uuid, 'email' => new Email('before@example.com'), 'hashcode' => Uuid::uuid4()->toString(), ]); - Employee::forceCreate([ + Employee::query()->forceCreate([ 'customer_id' => $uuid, 'matricule' => new Matricule('1234567'), 'nom' => 'Doe', diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php index 5a96a8ba..e91d4e98 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php @@ -14,6 +14,9 @@ use Domain\Models\ValueObjects\Entities\BasketId; use Domain\Models\ValueObjects\Entities\ProductId; use Domain\Models\ValueObjects\IncoId; use Domain\Ports\Repositories\BasketRepository; +use Illuminate\Support\Facades\Session; +use Infrastructure\Adapters\Repositories\SessionBasketRepository; +use Infrastructure\Adapters\Serializers\BasketSerializer; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; @@ -23,7 +26,10 @@ describe('SessionBasketRepository', function () { function getRepository(): BasketRepository { - return app(BasketRepository::class); + /** @var \Illuminate\Contracts\Session\Session $session */ + $session = Session::driver(); + + return new SessionBasketRepository($session, 'basket_', new BasketSerializer()); } it('returns null when session is empty', function () { diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeImportStorageServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeImportStorageServiceTest.php index c419bbd3..f9699af1 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeImportStorageServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeImportStorageServiceTest.php @@ -45,7 +45,7 @@ it('retrieves correct import statistics based on a start time', function () { $importStartTime = CarbonImmutable::parse('2023-01-01 12:00:00'); // Inserted after - Employee::forceCreate([ + Employee::query()->forceCreate([ 'matricule' => new Matricule('1234567'), 'nom' => 'Nom', 'prenom' => 'Prenom', @@ -59,7 +59,7 @@ it('retrieves correct import statistics based on a start time', function () { ]); // Updated after - Employee::forceCreate([ + Employee::query()->forceCreate([ 'matricule' => new Matricule('1234568'), 'nom' => 'N', 'prenom' => 'P', @@ -73,7 +73,7 @@ it('retrieves correct import statistics based on a start time', function () { ]); // Not updated after - Employee::forceCreate([ + Employee::query()->forceCreate([ 'matricule' => new Matricule('1234569'), 'nom' => 'N', 'prenom' => 'P', From 2db00301f49652b748d1666bb21e5f7c4d068c43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 16:01:08 +0100 Subject: [PATCH 146/183] test(shared): add pure unit test suites across Helpers, Enums, Filesystem, Pagination, and ValueObjects --- tests/Unit/Shared/Enums/BaseEnumTest.php | 148 ++++++++++++++++++ .../Filesystem/TemporaryFileFactoryTest.php | 103 ++++++++++++ tests/Unit/Shared/Helpers/DatesHelperTest.php | 111 +++++++++++++ .../Unit/Shared/Helpers/StringEncoderTest.php | 82 ++++++++++ .../Unit/Shared/Helpers/StringHelperTest.php | 103 ++++++++++++ tests/Unit/Shared/Helpers/UuidHelperTest.php | 108 +++++++++++++ .../Unit/Shared/Pagination/PageNumberTest.php | 44 ++++++ tests/Unit/Shared/Pagination/PageOfTest.php | 46 ++++++ tests/Unit/Shared/Pagination/PageSizeTest.php | 47 ++++++ .../Shared/ValueObjects/CrmHashcodeTest.php | 45 ++++++ 10 files changed, 837 insertions(+) create mode 100644 tests/Unit/Shared/Enums/BaseEnumTest.php create mode 100644 tests/Unit/Shared/Filesystem/TemporaryFileFactoryTest.php create mode 100644 tests/Unit/Shared/Helpers/DatesHelperTest.php create mode 100644 tests/Unit/Shared/Helpers/StringEncoderTest.php create mode 100644 tests/Unit/Shared/Helpers/StringHelperTest.php create mode 100644 tests/Unit/Shared/Helpers/UuidHelperTest.php create mode 100644 tests/Unit/Shared/Pagination/PageNumberTest.php create mode 100644 tests/Unit/Shared/Pagination/PageOfTest.php create mode 100644 tests/Unit/Shared/Pagination/PageSizeTest.php create mode 100644 tests/Unit/Shared/ValueObjects/CrmHashcodeTest.php diff --git a/tests/Unit/Shared/Enums/BaseEnumTest.php b/tests/Unit/Shared/Enums/BaseEnumTest.php new file mode 100644 index 00000000..d05b638a --- /dev/null +++ b/tests/Unit/Shared/Enums/BaseEnumTest.php @@ -0,0 +1,148 @@ + */ + use BaseEnum; + + case PENDING = 1; + case IN_PROGRESS = 2; + case DONE = 3; + + public const array LABELS = [ + 'PENDING' => 'En attente', + 'IN_PROGRESS' => 'In Progress', + 'DONE' => 'Terminé', + ]; +} + +enum StringStatusFixture: string implements HasBaseEnum +{ + /** @use BaseEnum */ + use BaseEnum; + + case DRAFT = 'draft'; + case PUBLISHED = 'published'; +} + +enum MissingLabelFixture: string implements HasBaseEnum +{ + /** @use BaseEnum */ + use BaseEnum; + + case FIRST = 'first'; + case SECOND = 'second'; + + public const array LABELS = [ + 'FIRST' => 'First', + ]; +} + +it('exposes value, name, and configured label for int-backed enum', function (): void { + // GIVEN + $enum = IntStatusFixture::IN_PROGRESS; + + // WHEN + $value = $enum->value(); + $name = $enum->name(); + $label = $enum->label(); + + // THEN + expect($value)->toBe(2) + ->and($name)->toBe('IN_PROGRESS') + ->and($label)->toBe('In Progress'); +}); + +it('falls back to ucfirst lowercase name when LABELS is not defined', function (): void { + // GIVEN + $enum = StringStatusFixture::DRAFT; + + // WHEN + $label = $enum->label(); + $labels = StringStatusFixture::toLabels(); + + // THEN + expect($label)->toBe('Draft') + ->and($labels)->toBe([ + 'DRAFT' => 'Draft', + 'PUBLISHED' => 'Published', + ]); +}); + +it('returns all labels and values maps', function (): void { + // GIVEN / WHEN + $labels = IntStatusFixture::toLabels(); + $values = IntStatusFixture::toValues(); + + // THEN + expect($labels)->toBe([ + 'PENDING' => 'En attente', + 'IN_PROGRESS' => 'In Progress', + 'DONE' => 'Terminé', + ])->and($values)->toBe([ + 'PENDING' => 1, + 'IN_PROGRESS' => 2, + 'DONE' => 3, + ]); +}); + +it('throws Error when LABELS is missing a case key', function (): void { + // GIVEN / WHEN / THEN + expect(static fn (): array => MissingLabelFixture::toLabels()) + ->toThrow(\Error::class, "Missing definition label Tests\Unit\Shared\Enums\MissingLabelFixture for 'SECOND'"); +}); + +it('resolves enum via make from instance, value, normalized label, custom field, and returns null when unknown', function (): void { + // GIVEN / WHEN + $fromInstance = IntStatusFixture::make(IntStatusFixture::DONE); + $fromIntValue = IntStatusFixture::make(1); + $fromNormalizedLabel = IntStatusFixture::make('In-Progress!', 'label'); + $fromNameField = IntStatusFixture::make('PENDING', 'name'); + $fromUnknownValue = IntStatusFixture::make(999); + $fromUnknownLabel = IntStatusFixture::make('nonexistent', 'label'); + + // THEN + expect($fromInstance)->toBe(IntStatusFixture::DONE) + ->and($fromIntValue)->toBe(IntStatusFixture::PENDING) + ->and($fromNormalizedLabel)->toBe(IntStatusFixture::IN_PROGRESS) + ->and($fromNameField)->toBe(IntStatusFixture::PENDING) + ->and($fromUnknownValue)->toBeNull() + ->and($fromUnknownLabel)->toBeNull() + ->and(static fn (): ?StringStatusFixture => StringStatusFixture::make('draft'))->toThrow(\TypeError::class); +}); + +it('checks equality including variadic arguments', function (): void { + // GIVEN + $enum = IntStatusFixture::PENDING; + + // WHEN / THEN + expect($enum->equals(IntStatusFixture::PENDING))->toBeTrue() + ->and($enum->equals(IntStatusFixture::DONE))->toBeFalse() + ->and($enum->equals(IntStatusFixture::DONE, IntStatusFixture::PENDING))->toBeTrue() + ->and($enum->equals(IntStatusFixture::DONE, IntStatusFixture::IN_PROGRESS))->toBeFalse(); +}); + +it('serializes to json using its backing value', function (): void { + // GIVEN + $intEnum = IntStatusFixture::DONE; + $stringEnum = StringStatusFixture::PUBLISHED; + + // WHEN + $encodedInt = json_encode($intEnum); + $encodedString = json_encode($stringEnum); + + // THEN + expect($encodedInt)->toBe('3') + ->and($encodedString)->toBe('"published"'); +}); diff --git a/tests/Unit/Shared/Filesystem/TemporaryFileFactoryTest.php b/tests/Unit/Shared/Filesystem/TemporaryFileFactoryTest.php new file mode 100644 index 00000000..f486ccf9 --- /dev/null +++ b/tests/Unit/Shared/Filesystem/TemporaryFileFactoryTest.php @@ -0,0 +1,103 @@ +newWithBytes('hello world', 'report.csv!@#'); + $content = $file->fread(100); + + // THEN + expect($file->getFilename())->toEndWith('.csv') + ->and($content)->toBe('hello world'); +}); + +it('creates a temporary file with empty filename and empty content', function (): void { + // GIVEN + $factory = new TemporaryFileFactory(); + + // WHEN + $file = $factory->newWithBytes('', ''); + + // THEN + expect($file->getSize())->toBe(0) + ->and($file->fread(10))->toBe(''); +}); + +it('copies multi-chunk SplFileObject even when source cursor is not at offset 0', function (): void { + // GIVEN + $factory = new TemporaryFileFactory(); + $payload = str_repeat('A', 9500); + $source = $factory->newWithBytes($payload, 'large.txt'); + $source->fseek(5000); + + // WHEN + $copy = $factory->newWithContentOf($source); + $copiedBytes = ''; + while (! $copy->eof()) { + $chunk = $copy->fread(4096); + if ($chunk !== false) { + $copiedBytes .= $chunk; + } + } + + // THEN + expect($copiedBytes)->toBe($payload); +}); + +it('creates a temporary file from stream resource rewinding non-zero cursor', function (): void { + // GIVEN + $factory = new TemporaryFileFactory(); + $stream = tmpfile(); + expect($stream)->not->toBeFalse(); + assert(is_resource($stream)); + + fwrite($stream, 'stream-content'); + fseek($stream, 6); + + // WHEN + $file = $factory->newWithStream($stream, 'upload.txt'); + $content = $file->fread(100); + fclose($stream); + + // THEN + expect($file->getFilename())->toEndWith('.txt') + ->and($content)->toBe('stream-content'); +}); + +it('throws TemporaryFileException when newWithStream receives non-resource', function (): void { + // GIVEN + $factory = new TemporaryFileFactory(); + + // WHEN & THEN + expect(static fn (): \SplFileObject => $factory->newWithStream('not-a-stream')) // @phpstan-ignore argument.type + ->toThrow(TemporaryFileException::class); +}); + +it('deletes tracked temporary files on factory destruction', function (): void { + // GIVEN + $factory = new TemporaryFileFactory(); + $file = $factory->newWithBytes('temporary', 'cleanup.txt'); + $path = $file->getRealPath(); + expect($path)->not->toBeFalse(); + assert(is_string($path)); + expect(is_file($path))->toBeTrue(); + + // WHEN + $factory->__destruct(); + unset($file, $factory); + clearstatcache(true, $path); + + // THEN + expect(is_file($path))->toBeFalse(); +}); diff --git a/tests/Unit/Shared/Helpers/DatesHelperTest.php b/tests/Unit/Shared/Helpers/DatesHelperTest.php new file mode 100644 index 00000000..24a184e8 --- /dev/null +++ b/tests/Unit/Shared/Helpers/DatesHelperTest.php @@ -0,0 +1,111 @@ + new DatesHelper()) + ->toThrow(\LogicException::class, 'Static class'); +}); + +it('returns true for isIn when both bounds are null', function (): void { + // GIVEN + $from = null; + $to = null; + + // WHEN + $result = DatesHelper::isIn($from, $to); + + // THEN + expect($result)->toBeTrue(); +}); + +it('checks bounded isIn intervals at before, inside, and after edges', function (): void { + // GIVEN + $from = CarbonImmutable::parse('2026-06-15 09:00:00', 'UTC'); + $to = CarbonImmutable::parse('2026-06-15 11:00:00', 'UTC'); + + // WHEN / THEN (inside) + expect(DatesHelper::isIn($from, $to))->toBeTrue(); + + // WHEN / THEN (at exact lower bound) + expect(DatesHelper::isIn(CarbonImmutable::parse('2026-06-15 10:00:00', 'UTC'), $to))->toBeTrue(); + + // WHEN / THEN (at exact upper bound) + expect(DatesHelper::isIn($from, CarbonImmutable::parse('2026-06-15 10:00:00', 'UTC')))->toBeTrue(); + + // WHEN / THEN (before interval) + $futureFrom = CarbonImmutable::parse('2026-06-15 10:00:01', 'UTC'); + $futureTo = CarbonImmutable::parse('2026-06-15 12:00:00', 'UTC'); + expect(DatesHelper::isIn($futureFrom, $futureTo))->toBeFalse(); + + // WHEN / THEN (after interval) + $pastFrom = CarbonImmutable::parse('2026-06-15 08:00:00', 'UTC'); + $pastTo = CarbonImmutable::parse('2026-06-15 09:59:59', 'UTC'); + expect(DatesHelper::isIn($pastFrom, $pastTo))->toBeFalse(); +}); + +it('checks open-ended isIn intervals with only from or only to', function (): void { + // GIVEN + $past = CarbonImmutable::parse('2026-06-15 09:00:00', 'UTC'); + $future = CarbonImmutable::parse('2026-06-15 11:00:00', 'UTC'); + + // WHEN / THEN + expect(DatesHelper::isIn($past, null))->toBeTrue() + ->and(DatesHelper::isIn($future, null))->toBeFalse() + ->and(DatesHelper::isIn(null, $future))->toBeTrue() + ->and(DatesHelper::isIn(null, $past))->toBeFalse(); +}); + +it('parses trimmed Y-m-d, RFC3339, fractional RFC3339, ISO8601, and fallback strings', function (): void { + // GIVEN / WHEN + $ymd = DatesHelper::parseDateTime(' 2026-06-15 '); + $rfc3339 = DatesHelper::parseDateTime('2026-06-15T10:30:00+02:00'); + $fractional = DatesHelper::parseDateTime('2026-06-15T10:30:00.123456+02:00'); + $iso8601 = DatesHelper::parseDateTime('2026-06-15T10:30:00Z'); + $fallback = DatesHelper::parseDateTime('2026-06-15 14:00:00'); + + // THEN + expect($ymd->format('Y-m-d H:i:s'))->toBe('2026-06-15 00:00:00') + ->and($rfc3339->format(\DATE_RFC3339))->toBe('2026-06-15T10:30:00+02:00') + ->and($fractional->format('Y-m-d\TH:i:s.uP'))->toBe('2026-06-15T10:30:00.123456+02:00') + ->and($iso8601->format('Y-m-d\TH:i:s\Z'))->toBe('2026-06-15T10:30:00Z') + ->and($fallback->format('Y-m-d H:i:s'))->toBe('2026-06-15 14:00:00'); +}); + +it('throws InvalidArgumentException when parsing an invalid datetime string', function (): void { + // GIVEN + $invalid = 'not-a-valid-date'; + + // WHEN / THEN + expect(static fn (): \DateTimeInterface => DatesHelper::parseDateTime($invalid)) + ->toThrow(\InvalidArgumentException::class, 'Unrecognized date/time format: not-a-valid-date'); +}); + +it('formats both string and DateTimeImmutable to RFC3339', function (): void { + // GIVEN + $dateTime = new \DateTimeImmutable('2026-06-15T10:30:00+02:00'); + + // WHEN + $fromString = DatesHelper::toRfc3339('2026-06-15T10:30:00+02:00'); + $fromInstance = DatesHelper::toRfc3339($dateTime); + + // THEN + expect($fromString)->toBe('2026-06-15T10:30:00+02:00') + ->and($fromInstance)->toBe('2026-06-15T10:30:00+02:00'); +}); diff --git a/tests/Unit/Shared/Helpers/StringEncoderTest.php b/tests/Unit/Shared/Helpers/StringEncoderTest.php new file mode 100644 index 00000000..5f08b585 --- /dev/null +++ b/tests/Unit/Shared/Helpers/StringEncoderTest.php @@ -0,0 +1,82 @@ +toBe('') + ->and(StringEncoder::toUtf8($withBom, 'UTF-8'))->toBe('Bonjour') + ->and(StringEncoder::toUtf8($withBom, 'UTF-8', stripBom: false))->toBe($withBom); +}); + +it('throws ValueError for invalid UTF-8 or unknown encoding in toUtf8', function (): void { + // GIVEN + $invalidUtf8 = "\xFF\xFE"; + + // WHEN / THEN + expect(static fn (): string => StringEncoder::toUtf8($invalidUtf8, 'UTF-8')) + ->toThrow(\ValueError::class) + ->and(static fn (): string => StringEncoder::toUtf8('abc', 'UNKNOWN-ENC')) + ->toThrow(\ValueError::class); +}); + +it('converts Windows-1252 special bytes via aliases', function (): void { + // GIVEN + $bytes = "\x80\x92\x9C\xE9"; + + // WHEN / THEN + expect(StringEncoder::toUtf8($bytes, 'win1252'))->toBe("€\u{2019}œé") + ->and(StringEncoder::toUtf8($bytes, 'cp1252'))->toBe("€\u{2019}œé") + ->and(StringEncoder::toUtf8($bytes, 'latin-1'))->toBe("€\u{2019}œé") + ->and(StringEncoder::toUtf8($bytes, ' ISO-8859-1 '))->toBe("€\u{2019}œé"); +}); + +it('converts ISO-8859-15 override bytes to UTF-8', function (): void { + // GIVEN + $bytes = "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"; + + // WHEN + $result = StringEncoder::toUtf8($bytes, 'ISO-8859-15'); + + // THEN + expect($result)->toBe('€ŠšŽžŒœŸ'); +}); + +it('detects and converts to UTF-8 with fallback encoding and BOM handling', function (): void { + // GIVEN + $validUtf8WithBom = "\xEF\xBB\xBFCafé"; + $rawWin1252 = "\x80\xE9"; + $rawLatin9 = "\xA4\xBC"; + + // WHEN / THEN + expect(StringEncoder::detectAndConvertToUtf8(''))->toBe('') + ->and(StringEncoder::detectAndConvertToUtf8($validUtf8WithBom))->toBe('Café') + ->and(StringEncoder::detectAndConvertToUtf8($rawWin1252))->toBe('€é') + ->and(StringEncoder::detectAndConvertToUtf8($rawLatin9, 'ISO-8859-15'))->toBe('€Œ') + ->and(static fn (): string => StringEncoder::detectAndConvertToUtf8('abc', 'UTF-8')) + ->toThrow(\ValueError::class) + ->and(static fn (): string => StringEncoder::detectAndConvertToUtf8('abc', 'UNKNOWN')) + ->toThrow(\ValueError::class); +}); + +it('converts arrays of strings and lists supported encodings', function (): void { + // GIVEN + $items = ["\x80", "\xE9"]; + + // WHEN + $converted = StringEncoder::arrayToUtf8($items, 'Windows-1252'); + $supported = StringEncoder::supportedEncodings(); + + // THEN + expect($converted)->toBe(['€', 'é']) + ->and($supported)->toContain('UTF-8', 'Windows-1252', 'ISO-8859-15', 'win1252', 'latin-9'); +}); diff --git a/tests/Unit/Shared/Helpers/StringHelperTest.php b/tests/Unit/Shared/Helpers/StringHelperTest.php new file mode 100644 index 00000000..f3bc8d5b --- /dev/null +++ b/tests/Unit/Shared/Helpers/StringHelperTest.php @@ -0,0 +1,103 @@ +toBe('Ete creme brulee'); +}); + +it('slugifies strings with accents, punctuation, and custom separators', function (): void { + // GIVEN + $input = ' Été : crème brûlée & café! '; + + // WHEN + $default = StringHelper::slugify($input); + $custom = StringHelper::slugify($input, '_'); + + // THEN + expect($default)->toBe('ete-creme-brulee-cafe') + ->and($custom)->toBe('ete_creme_brulee_cafe'); +}); + +it('converts strings to snakeCase, kebabCase, pascalCase, and camelCase', function (): void { + // GIVEN + $cases = [ + 'helloWorld' => ['hello_world', 'hello-world', 'HelloWorld', 'helloWorld'], + 'HTTPResponseCode' => ['http_response_code', 'http-response-code', 'HttpResponseCode', 'httpResponseCode'], + 'hello-world foo' => ['hello_world_foo', 'hello-world-foo', 'HelloWorldFoo', 'helloWorldFoo'], + '' => ['', '', '', ''], + ]; + + // WHEN / THEN + foreach ($cases as $input => [$snake, $kebab, $pascal, $camel]) { + expect(StringHelper::snakeCase($input))->toBe($snake) + ->and(StringHelper::kebabCase($input))->toBe($kebab) + ->and(StringHelper::pascalCase($input))->toBe($pascal) + ->and(StringHelper::camelCase($input))->toBe($camel); + } +}); + +it('converts strings to titleCase', function (): void { + // GIVEN / WHEN / THEN + expect(StringHelper::titleCase(''))->toBe('') + ->and(StringHelper::titleCase(' '))->toBe('') + ->and(StringHelper::titleCase('jean-luc PICARD'))->toBe('Jean-Luc Picard'); +}); + +it('truncates words with default or custom suffix and handles multibyte accents', function (): void { + // GIVEN + $short = 'Un deux trois'; + $long = 'Été crème brûlée café théâtre'; + + // WHEN / THEN + expect(StringHelper::words($short, 5))->toBe('Un deux trois') + ->and(StringHelper::words($long, 3))->toBe('Été crème brûlée ...') + ->and(StringHelper::words($long, 3, '…'))->toBe('Été crème brûlée…'); +}); + +it('tokenizes strings with multibyte delimiters using mbStrtok', function (): void { + // GIVEN + $delimiters = 'é,; '; + $input = 'unédeux,trois; quatre'; + + // WHEN + $t1 = StringHelper::mbStrtok($delimiters, $input); + $t2 = StringHelper::mbStrtok($delimiters); + $t3 = StringHelper::mbStrtok($delimiters); + $t4 = StringHelper::mbStrtok($delimiters); + $t5 = StringHelper::mbStrtok($delimiters); + + // THEN + expect($t1)->toBe('un') + ->and($t2)->toBe('deux') + ->and($t3)->toBe('trois') + ->and($t4)->toBe('quatre') + ->and($t5)->toBeFalse(); +}); + +it('sanitizes null, empty, HTML, newlines, control bytes, 4-byte emoji, and Windows-1252 bytes', function (): void { + // GIVEN + $html = "

Bonjour & \t\r\nmonde\r!

"; + $withEmoji = "Test😀\x00\x7F\xC2\xA0\xC2\xADok"; + $win1252 = "\x80\xE9"; + + // WHEN / THEN + expect(StringHelper::sanitize(null))->toBeNull() + ->and(StringHelper::sanitize(''))->toBe('') + ->and(StringHelper::sanitize($html))->toBe("Bonjour & \t\nmonde\n!") + ->and(StringHelper::sanitize($withEmoji))->toBe('Testok') + ->and(StringHelper::sanitize($win1252))->toBe('€é'); +}); diff --git a/tests/Unit/Shared/Helpers/UuidHelperTest.php b/tests/Unit/Shared/Helpers/UuidHelperTest.php new file mode 100644 index 00000000..53a80543 --- /dev/null +++ b/tests/Unit/Shared/Helpers/UuidHelperTest.php @@ -0,0 +1,108 @@ +toString(); + $v7 = Uuid::uuid7()->toString(); + $invalid = 'not-a-uuid'; + + // WHEN & THEN + expect(UuidHelper::isValid($v4))->toBeTrue() + ->and(UuidHelper::isValid($v7))->toBeTrue() + ->and(UuidHelper::isValid($invalid))->toBeFalse(); +}); + +it('roundtrips v4 and v7 uuids through base58 including surrounding whitespace', function (): void { + // GIVEN + $v4 = Uuid::uuid4(); + $v7 = Uuid::uuid7(); + + // WHEN + $v4Base58 = UuidHelper::toBase58($v4); + $v7Base58 = UuidHelper::toBase58($v7); + + $decodedV4 = UuidHelper::fromBase58(" {$v4Base58} \n"); + $decodedV7 = UuidHelper::fromBase58("\t{$v7Base58} "); + + // THEN + expect($decodedV4->toString())->toBe($v4->toString()) + ->and($decodedV7->toString())->toBe($v7->toString()); +}); + +it('rejects invalid base58 inputs', function (string $input): void { + // GIVEN / WHEN / THEN + expect(static fn (): UuidInterface => UuidHelper::fromBase58($input)) + ->toThrow(InvalidUuidException::class); +})->with([ + 'empty string' => [''], + 'too short' => ['12345678901234567890'], + 'too long' => ['12345678901234567890123'], + 'ambiguous chars 0OIl' => ['0OIl123456789012345678'], + 'invalid payload' => ['zzzzzzzzzzzzzzzzzzzzzz'], +]); + +it('detects uuid versions for v4, v7, and v1', function (): void { + // GIVEN + $v4 = Uuid::uuid4(); + $v7 = Uuid::uuid7(); + $v1 = Uuid::uuid1(); + + // WHEN & THEN + expect(UuidHelper::version($v4))->toBe(4) + ->and(UuidHelper::isV4($v4))->toBeTrue() + ->and(UuidHelper::isV7($v4))->toBeFalse() + ->and(UuidHelper::version($v7))->toBe(7) + ->and(UuidHelper::isV4($v7))->toBeFalse() + ->and(UuidHelper::isV7($v7))->toBeTrue() + ->and(UuidHelper::version($v1))->toBe(1) + ->and(UuidHelper::isV4($v1))->toBeFalse() + ->and(UuidHelper::isV7($v1))->toBeFalse(); +}); + +it('passes validateUuid for valid uuid and throws for invalid UuidInterface', function (): void { + // GIVEN + $valid = Uuid::uuid4(); + $invalid = new LazyUuidFromString('invalid'); + + // WHEN + UuidHelper::validateUuid($valid); + + // THEN + expect(static function () use ($invalid): void { + UuidHelper::validateUuid($invalid); + })->toThrow(InvalidUuidException::class); +}); + +it('extracts exact utc datetime with millisecond precision from v7 uuid', function (): void { + // GIVEN + $expected = new \DateTimeImmutable('2025-06-15 12:34:56.789000', new \DateTimeZone('UTC')); + $v7 = Uuid::uuid7($expected); + + // WHEN + $actual = UuidHelper::toDateTime($v7); + + // THEN + expect($actual->getTimezone()->getName())->toBe('UTC') + ->and($actual->format('Y-m-d H:i:s.v'))->toBe($expected->format('Y-m-d H:i:s.v')); +}); + +it('throws InvalidUuidException when extracting datetime from non-v7 uuid', function (): void { + // GIVEN + $v4 = Uuid::uuid4(); + + // WHEN & THEN + expect(static fn (): \DateTimeImmutable => UuidHelper::toDateTime($v4)) + ->toThrow(InvalidUuidException::class); +}); diff --git a/tests/Unit/Shared/Pagination/PageNumberTest.php b/tests/Unit/Shared/Pagination/PageNumberTest.php new file mode 100644 index 00000000..0ca9ba26 --- /dev/null +++ b/tests/Unit/Shared/Pagination/PageNumberTest.php @@ -0,0 +1,44 @@ +value())->toBe(1) + ->and($ofFive->value())->toBe(5) + ->and($defaultFactory->value())->toBe(1) + ->and((string) $ofFive)->toBe('5') + ->and(json_encode($ofFive))->toBe('5'); +}); + +it('checks equality with same, different, and non-PageNumber values', function (): void { + // GIVEN + $page = PageNumber::of(3); + + // WHEN / THEN + expect($page->equals(PageNumber::of(3)))->toBeTrue() + ->and($page->equals(PageNumber::of(4)))->toBeFalse() + ->and($page->equals(null))->toBeFalse() + ->and($page->equals(new PageSize(1)))->toBeFalse(); +}); + +it('rejects zero and negative page numbers', function (int $invalidValue): void { + // GIVEN / WHEN / THEN + expect(static fn (): PageNumber => new PageNumber($invalidValue)) + ->toThrow(\InvalidArgumentException::class, 'Page number must be greater than 0'); +})->with([ + 'zero' => 0, + 'negative' => -3, +]); diff --git a/tests/Unit/Shared/Pagination/PageOfTest.php b/tests/Unit/Shared/Pagination/PageOfTest.php new file mode 100644 index 00000000..d533bef8 --- /dev/null +++ b/tests/Unit/Shared/Pagination/PageOfTest.php @@ -0,0 +1,46 @@ + 1]; + $item2 = (object) ['id' => 2]; + $pageOf = new PageOf($pagination, [$item1, $item2], 42); + + // WHEN + $returnedPagination = $pageOf->getPagination(); + $returnedTotal = $pageOf->getTotal(); + $returnedItems = $pageOf->getItems(); + + // THEN + expect($returnedPagination)->toBe($pagination) + ->and($returnedTotal)->toBe(42) + ->and($returnedItems)->toHaveCount(2) + ->and($returnedItems[0]->id)->toBe(1) + ->and($returnedItems[1]->id)->toBe(2); +}); + +it('returns cloned items so mutating returned objects does not affect internal state', function (): void { + // GIVEN + $pagination = Pagination::firstPage(); + $item = new \stdClass(); + $item->name = 'original'; + $pageOf = new PageOf($pagination, [$item], 1); + + // WHEN + $firstItems = $pageOf->getItems(); + $firstItems[0]->name = 'mutated'; + $secondItems = $pageOf->getItems(); + + // THEN + expect($secondItems[0]->name)->toBe('original'); +}); diff --git a/tests/Unit/Shared/Pagination/PageSizeTest.php b/tests/Unit/Shared/Pagination/PageSizeTest.php new file mode 100644 index 00000000..b3e4790c --- /dev/null +++ b/tests/Unit/Shared/Pagination/PageSizeTest.php @@ -0,0 +1,47 @@ +value())->toBe(25) + ->and($ofFifty->value())->toBe(50) + ->and($defaultFactory->value())->toBe(25) + ->and($maxBoundary->value())->toBe(10000) + ->and((string) $ofFifty)->toBe('50') + ->and(json_encode($ofFifty))->toBe('50'); +}); + +it('checks equality with same, different, and non-PageSize values', function (): void { + // GIVEN + $size = PageSize::of(25); + + // WHEN / THEN + expect($size->equals(PageSize::of(25)))->toBeTrue() + ->and($size->equals(PageSize::of(50)))->toBeFalse() + ->and($size->equals(null))->toBeFalse() + ->and($size->equals(new PageNumber(25)))->toBeFalse(); +}); + +it('rejects zero, negative, and above-max page sizes', function (int $invalidValue): void { + // GIVEN / WHEN / THEN + expect(static fn (): PageSize => new PageSize($invalidValue)) + ->toThrow(\InvalidArgumentException::class); +})->with([ + 'zero' => 0, + 'negative' => -1, + 'above max' => 10001, +]); diff --git a/tests/Unit/Shared/ValueObjects/CrmHashcodeTest.php b/tests/Unit/Shared/ValueObjects/CrmHashcodeTest.php new file mode 100644 index 00000000..99f5e973 --- /dev/null +++ b/tests/Unit/Shared/ValueObjects/CrmHashcodeTest.php @@ -0,0 +1,45 @@ +toString(); + + // WHEN + $fromUuid = new CrmHashcode($uuid); + $fromString = CrmHashcode::fromString($v4String); + + // THEN + expect($fromUuid->value)->toBe($v4String) + ->and((string) $fromUuid)->toBe($v4String) + ->and($fromString->value)->toBe($v4String) + ->and((string) $fromString)->toBe($v4String); +}); + +it('rejects non-v4 uuids with DomainException', function (): void { + // GIVEN + $v7 = Uuid::uuid7(); + $v1 = Uuid::uuid1(); + + // WHEN & THEN + expect(static fn (): CrmHashcode => new CrmHashcode($v7)) + ->toThrow(\DomainException::class) + ->and(static fn (): CrmHashcode => new CrmHashcode($v1)) + ->toThrow(\DomainException::class); +}); + +it('throws InvalidUuidStringException when fromString receives invalid uuid', function (): void { + // GIVEN / WHEN / THEN + expect(static fn (): CrmHashcode => CrmHashcode::fromString('not-a-uuid')) + ->toThrow(InvalidUuidStringException::class); +}); From 1b44f9d17893b6c9cad8d63a51cfbeb532e3c8cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 16:13:14 +0100 Subject: [PATCH 147/183] test(quality): resolve all PHPStan level 10 errors in Unit and Integration tests --- .../WithApp/App/Casts/CodeCastTest.php | 1 + .../App/Casts/DeliveryAddressCastTest.php | 1 + .../App/Casts/DiscountValueCastTest.php | 11 +- .../WithApp/App/Casts/EmailCastTest.php | 1 + .../App/Casts/EmployeeSitesCastTest.php | 1 + .../WithApp/App/Casts/MatriculeCastTest.php | 1 + .../WithApp/App/Casts/MoneyCastTest.php | 1 + .../App/Casts/NutritionalValuesCastTest.php | 1 + .../App/Casts/OrderEmployeeCastTest.php | 13 +- .../App/Casts/OrderLineProductCastTest.php | 7 +- .../App/Casts/OrderReferenceCastTest.php | 1 + .../ShopperEstablishmentCodeCastTest.php | 1 + .../App/Casts/ShopperServiceCodeCastTest.php | 1 + .../App/Casts/ShopperSiteCodeCastTest.php | 1 + .../Cqs/Actions/Basket/AddToBasketTest.php | 7 +- .../Cqs/Actions/Basket/EmptyBasketTest.php | 1 + .../Actions/Basket/RemoveFromBasketTest.php | 6 +- .../Actions/Common/ExecuteMassActionTest.php | 4 +- .../Customers/RegisterCustomerTest.php | 8 +- .../Actions/Orders/ApplyPickTimeSlotTest.php | 11 +- .../Orders/InitializeOrderTunnelTest.php | 1 + .../CreatePickupExceptionTest.php | 5 +- .../DeletePickupExceptionTest.php | 5 +- .../UpdatePickupExceptionTest.php | 5 +- .../ProductIncos/AssociateProductIncoTest.php | 5 +- .../Cqs/Actions/Ranges/CreateRangeTest.php | 5 +- .../Cqs/Actions/Ranges/DeleteRangeTest.php | 5 +- .../Cqs/Actions/Ranges/UpdateRangeTest.php | 5 +- .../App/Cqs/Actions/Shops/CreateShopTest.php | 5 +- .../App/Cqs/Actions/Shops/DeleteShopTest.php | 5 +- .../Shops/UpdateShopPickupExceptionsTest.php | 5 +- .../App/Cqs/Actions/Shops/UpdateShopTest.php | 5 +- .../Customers/GetCustomerByEmailQueryTest.php | 2 +- .../App/Cqs/Queries/Faqs/GetFaqsQueryTest.php | 4 +- .../Products/GetProductFormDataQueryTest.php | 2 +- .../Cqs/Queries/Shops/GetShopQueryTest.php | 4 +- .../App/Dto/PickupExceptionDtoTest.php | 1 + .../WithApp/App/Dto/ShopDtoTest.php | 15 +- .../WithApp/App/Dto/SlideDtoTest.php | 3 +- .../Frontend/OrderTunnelStepPolicyTest.php | 2 +- .../Services/ActionExecutorServiceTest.php | 43 ++- .../WithApp/App/Services/CrmServiceTest.php | 8 +- .../App/Services/EmployeeSyncServiceTest.php | 6 +- .../Services/EmployeeUpsertServiceTest.php | 6 +- .../App/Services/MailRegateServiceTest.php | 19 +- .../App/Services/ProductDtoAssemblerTest.php | 5 +- .../SessionBasketRepositoryTest.php | 4 +- .../Services/AppCustomerAuthServiceTest.php | 63 ++- .../Common/ExecuteMassActionInputTest.php | 8 +- .../Actions/Slides/UpdateSlideInputTest.php | 3 +- tests/Unit/Domain/Events/DtoTest.php | 3 +- .../Domain/Models/Entities/BasketTest.php | 67 ++-- .../Unit/Domain/Models/Entities/OrderTest.php | 39 +- .../Entities/PickupExceptionOnDateTest.php | 4 +- .../Models/ValueObjects/AttachedFileTest.php | 13 +- .../Models/ValueObjects/BasketProductTest.php | 58 ++- .../ValueObjects/ContactFormDataTest.php | 31 +- .../ValueObjects/NutritionalValuesTest.php | 27 +- .../Models/ValueObjects/OrderLineTest.php | 43 ++- .../ValueObjects/ProductPricingTest.php | 34 +- .../ValueObjects/ShopPickupOverrideTest.php | 12 +- .../Domain/Services/BasketServiceTest.php | 40 +- .../Unit/Domain/Services/OrderServiceTest.php | 1 + .../Domain/Services/ShopperServiceTest.php | 2 +- .../Serializers/BasketSerializerTest.php | 359 +++++++++--------- 65 files changed, 634 insertions(+), 432 deletions(-) diff --git a/tests/Integration/WithApp/App/Casts/CodeCastTest.php b/tests/Integration/WithApp/App/Casts/CodeCastTest.php index d81d6fb1..6f69b925 100644 --- a/tests/Integration/WithApp/App/Casts/CodeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/CodeCastTest.php @@ -53,6 +53,7 @@ it('throws exception when setting invalid code', function () { $model = \Mockery::mock(Model::class); // WHEN + /** @phpstan-ignore argument.type */ $cast->set($model, 'code', 'ABCDEFGH', []); // THEN diff --git a/tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php b/tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php index 9f2c35b3..ea1e9908 100644 --- a/tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php +++ b/tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php @@ -68,6 +68,7 @@ it('throws exception when setting invalid type', function () { $model = \Mockery::mock(Model::class); // WHEN + /** @phpstan-ignore argument.type */ $cast->set($model, 'address', 'invalid', []); // THEN diff --git a/tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php b/tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php index 82e1be2a..8aa29bb4 100644 --- a/tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php +++ b/tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php @@ -42,8 +42,9 @@ it('gets a discount value from amount', function () { ); // THEN - expect($value->value())->toBeInstanceOf(Money::class) - ->and($value->value()->getAmount())->toBe('1000'); + $amount = $value->value(); + assert($amount instanceof Money); + expect($amount->getAmount())->toBe('1000'); }); it('gets a discount value from amount string', function () { @@ -60,8 +61,9 @@ it('gets a discount value from amount string', function () { ); // THEN - expect($value->value())->toBeInstanceOf(Money::class) - ->and($value->value()->getAmount())->toBe('1000'); + $amount = $value->value(); + assert($amount instanceof Money); + expect($amount->getAmount())->toBe('1000'); }); it('throws exception when type is missing', function () { @@ -128,6 +130,7 @@ it('throws exception when setting invalid type', function () { $model = \Mockery::mock(Model::class); // WHEN + /** @phpstan-ignore argument.type */ $cast->set($model, 'discount', 10, []); // THEN diff --git a/tests/Integration/WithApp/App/Casts/EmailCastTest.php b/tests/Integration/WithApp/App/Casts/EmailCastTest.php index 36699d84..f6851055 100644 --- a/tests/Integration/WithApp/App/Casts/EmailCastTest.php +++ b/tests/Integration/WithApp/App/Casts/EmailCastTest.php @@ -59,6 +59,7 @@ it('throws exception when setting invalid email type', function () { $model = \Mockery::mock(Model::class); // WHEN + /** @phpstan-ignore argument.type */ $cast->set($model, 'email', 'test@example.com', []); // THEN diff --git a/tests/Integration/WithApp/App/Casts/EmployeeSitesCastTest.php b/tests/Integration/WithApp/App/Casts/EmployeeSitesCastTest.php index 528c1ca7..6a040d35 100644 --- a/tests/Integration/WithApp/App/Casts/EmployeeSitesCastTest.php +++ b/tests/Integration/WithApp/App/Casts/EmployeeSitesCastTest.php @@ -90,6 +90,7 @@ it('throws exception when setting invalid type', function (): void { $model = \Mockery::mock(Model::class); // WHEN + /** @phpstan-ignore argument.type */ expect(fn () => $cast->set($model, 'employee_sites', 12345, [])) // THEN ->toThrow(\UnexpectedValueException::class, 'Employee sites must be an array, string or null.'); diff --git a/tests/Integration/WithApp/App/Casts/MatriculeCastTest.php b/tests/Integration/WithApp/App/Casts/MatriculeCastTest.php index e2ef6690..8c91c873 100644 --- a/tests/Integration/WithApp/App/Casts/MatriculeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/MatriculeCastTest.php @@ -48,6 +48,7 @@ it('throws exception when setting invalid matricule type', function () { $model = \Mockery::mock(Model::class); // WHEN + /** @phpstan-ignore argument.type */ $cast->set($model, 'matricule', '1234567', []); // THEN diff --git a/tests/Integration/WithApp/App/Casts/MoneyCastTest.php b/tests/Integration/WithApp/App/Casts/MoneyCastTest.php index c5ebfa9f..d12e8126 100644 --- a/tests/Integration/WithApp/App/Casts/MoneyCastTest.php +++ b/tests/Integration/WithApp/App/Casts/MoneyCastTest.php @@ -54,6 +54,7 @@ it('throws exception when setting invalid money type', function () { $model = \Mockery::mock(Model::class); // WHEN + /** @phpstan-ignore argument.type */ $cast->set($model, 'price', '1000', []); // THEN diff --git a/tests/Integration/WithApp/App/Casts/NutritionalValuesCastTest.php b/tests/Integration/WithApp/App/Casts/NutritionalValuesCastTest.php index b543af29..1a7a98a7 100644 --- a/tests/Integration/WithApp/App/Casts/NutritionalValuesCastTest.php +++ b/tests/Integration/WithApp/App/Casts/NutritionalValuesCastTest.php @@ -74,6 +74,7 @@ it('throws exception when setting invalid type', function () { $model = \Mockery::mock(Model::class); // WHEN + /** @phpstan-ignore argument.type */ $cast->set($model, 'nutritional', 'invalid', []); // THEN diff --git a/tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php b/tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php index a68e7cc8..98019748 100644 --- a/tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php @@ -7,6 +7,9 @@ namespace Tests\Integration\WithApp\App\Casts; use App\Casts\OrderEmployeeCast; use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\OrderEmployee; +use Domain\Models\ValueObjects\ShopperEstablishmentCode; +use Domain\Models\ValueObjects\ShopperServiceCode; +use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Database\Eloquent\Model; it('gets null when value is null', function () { @@ -35,10 +38,6 @@ it('throws exception when getting invalid value type', function () { 'The value must be a string.' ); -use Domain\Models\ValueObjects\ShopperEstablishmentCode; -use Domain\Models\ValueObjects\ShopperServiceCode; -use Domain\Models\ValueObjects\ShopperSiteCode; - it('gets an order employee from json string', function () { // GIVEN $cast = new OrderEmployeeCast(); @@ -57,8 +56,8 @@ it('gets an order employee from json string', function () { $employee = $cast->get($model, 'employee', $json, []); // THEN - expect($employee)->toBeInstanceOf(OrderEmployee::class) - ->and($employee->matricule->value)->toBe('1234567') + assert($employee instanceof OrderEmployee); + expect($employee->matricule->value)->toBe('1234567') ->and($employee->firstname)->toBe('John') ->and($employee->lastname)->toBe('Doe') ->and($employee->facility->value)->toBe('FAC01') @@ -84,6 +83,7 @@ it('throws exception when setting invalid type', function () { $model = \Mockery::mock(Model::class); // WHEN + /** @phpstan-ignore argument.type */ $cast->set($model, 'employee', 'invalid', []); // THEN @@ -109,6 +109,7 @@ it('sets an order employee', function () { $value = $cast->set($model, 'employee', $employee, []); // THEN + assert(is_string($value)); expect($value)->toBeJson() ->and(json_decode($value, true))->toMatchArray([ 'matricule' => '1234567', diff --git a/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php b/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php index 1c0264cc..9dd90386 100644 --- a/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php +++ b/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php @@ -76,8 +76,7 @@ describe('OrderLineProductCast', function () { ->and($product->weight->value)->toBe(1000) ->and($product->weight->isVariable)->toBeFalse() ->and($product->taxRate)->toBe(TaxRate::TVA_5_5) - ->and($product->picture)->toBeInstanceOf(StorageFilePath::class) - ->and($product->picture->value)->toBe('pic.jpg'); + ->and($product->picture?->value)->toBe('pic.jpg'); }); it('gets an order line product with integer tax rate and null picture', function () { @@ -115,6 +114,7 @@ describe('OrderLineProductCast', function () { $model = \Mockery::mock(Model::class); // WHEN + /** @phpstan-ignore argument.type */ $cast->set($model, 'product', 'invalid', []); // THEN @@ -148,8 +148,9 @@ describe('OrderLineProductCast', function () { $data = json_decode($value, true); // THEN + assert(is_array($data)); expect($value)->toBeJson() - ->and($data)->toBeArray() + ->and($data) ->toHaveKey('weight', 1000) ->toHaveKey('weight_variable', false) ->and($data)->not->toHaveKey('weight_unit') diff --git a/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php b/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php index 9b43bd18..8a01f98b 100644 --- a/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php +++ b/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php @@ -69,6 +69,7 @@ it('throws exception when setting invalid reference type', function () { $value = UuidHelper::toBase58(Uuid::uuid7()); // WHEN + /** @phpstan-ignore argument.type */ $cast->set($model, 'reference', $value, []); // THEN diff --git a/tests/Integration/WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php b/tests/Integration/WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php index d3db47dd..36684fd6 100644 --- a/tests/Integration/WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php @@ -73,6 +73,7 @@ it('throws exception when setting invalid ShopperEstablishmentCode type', functi $model = \Mockery::mock(Model::class); // WHEN + /** @phpstan-ignore argument.type */ $cast->set($model, 'etablissement', 123, []); // THEN diff --git a/tests/Integration/WithApp/App/Casts/ShopperServiceCodeCastTest.php b/tests/Integration/WithApp/App/Casts/ShopperServiceCodeCastTest.php index b2553984..e66a078a 100644 --- a/tests/Integration/WithApp/App/Casts/ShopperServiceCodeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/ShopperServiceCodeCastTest.php @@ -73,6 +73,7 @@ it('throws exception when setting invalid ShopperServiceCode type', function () $model = \Mockery::mock(Model::class); // WHEN + /** @phpstan-ignore argument.type */ $cast->set($model, 'service', 123, []); // THEN diff --git a/tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php b/tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php index 4f3155fb..51594a6e 100644 --- a/tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php @@ -73,6 +73,7 @@ it('throws exception when setting invalid ShopperSiteCode type', function () { $model = \Mockery::mock(Model::class); // WHEN + /** @phpstan-ignore argument.type */ $cast->set($model, 'site', 123, []); // THEN diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php index caf5c79f..f0294da8 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php @@ -40,7 +40,9 @@ function makeBasketProductFixture(bool $status = true, bool $withInco = true): P $range = new Range(); $range->name = 'Gamme Panier ' . uniqid(); $range->status = true; - $range->order = ((int) Range::query()->max('order')) + 1; + /** @var int $maxOrder */ + $maxOrder = Range::query()->max('order') ?? 0; + $range->order = $maxOrder + 1; $range->picture_alt = 'alt'; $range->picture_title = 'title'; $range->saveOrFail(); @@ -78,6 +80,7 @@ describe('AddToBasket action', function (): void { it('adds an orderable product to session basket and increments quantity on repeated additions', function (): void { // GIVEN $product = makeBasketProductFixture(); + /** @var \Illuminate\Contracts\Session\Session $session */ $session = Session::driver(); $repository = new SessionBasketRepository($session, 'basket_', new BasketSerializer()); $dispatcher = new LaravelDomainEventDispatcher(); @@ -104,6 +107,7 @@ describe('AddToBasket action', function (): void { it('invalidates existing order builder in session when executed through ActionExecutorService', function (): void { // GIVEN $product = makeBasketProductFixture(); + /** @var \Illuminate\Contracts\Session\Session $session */ $session = Session::driver(); $repository = new SessionBasketRepository($session, 'basket_', new BasketSerializer()); $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); @@ -137,6 +141,7 @@ describe('AddToBasket action', function (): void { // GIVEN $inactiveProduct = makeBasketProductFixture(status: false, withInco: true); $noIncoProduct = makeBasketProductFixture(status: true, withInco: false); + /** @var \Illuminate\Contracts\Session\Session $session */ $session = Session::driver(); $basketSvc = new BasketService( new SessionBasketRepository($session, 'basket_', new BasketSerializer()), diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php index eff12633..86fa7928 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php @@ -69,6 +69,7 @@ describe('EmptyBasket action', function (): void { $inco->no_art = random_int(10000, 99999); $inco->saveOrFail(); + /** @var \Illuminate\Contracts\Session\Session $session */ $session = Session::driver(); $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); $dispatcher = new LaravelDomainEventDispatcher(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php index 5fbb9cc9..ab37e5a1 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php @@ -40,7 +40,9 @@ function makeRemovableProductFixture(): Product $range = new Range(); $range->name = 'Gamme Retrait Panier ' . uniqid(); $range->status = true; - $range->order = ((int) Range::query()->max('order')) + 1; + /** @var int $maxOrder */ + $maxOrder = Range::query()->max('order') ?? 0; + $range->order = $maxOrder + 1; $range->picture_alt = 'alt'; $range->picture_title = 'title'; $range->saveOrFail(); @@ -76,6 +78,7 @@ describe('RemoveFromBasket action', function (): void { it('decrements quantity and removes the line when RemoveQuantityFromBasketInput hits zero', function (): void { // GIVEN $product = makeRemovableProductFixture(); + /** @var \Illuminate\Contracts\Session\Session $session */ $session = Session::driver(); $basketSvc = new BasketService( new SessionBasketRepository($session, 'basket_', new BasketSerializer()), @@ -103,6 +106,7 @@ describe('RemoveFromBasket action', function (): void { // GIVEN $product1 = makeRemovableProductFixture(); $product2 = makeRemovableProductFixture(); + /** @var \Illuminate\Contracts\Session\Session $session */ $session = Session::driver(); $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); $dispatcher = new LaravelDomainEventDispatcher(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Common/ExecuteMassActionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ExecuteMassActionTest.php index 6d8f8753..0ac1e02f 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Common/ExecuteMassActionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Common/ExecuteMassActionTest.php @@ -43,7 +43,9 @@ function createMassActionProduct(): Product $product->picture_title = 'test title'; $product->picture_large_alt = 'test alt'; $product->picture_large_title = 'test title'; - $product->order = (int) Product::query()->max('order') + 1; + /** @var int $maxOrder */ + $maxOrder = Product::query()->max('order') ?? 0; + $product->order = $maxOrder + 1; $product->star = false; $product->saveOrFail(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php index d8e4b0fd..df76db1f 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php @@ -26,6 +26,7 @@ use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Auth\Notifications\VerifyEmail; use Illuminate\Database\Eloquent\ModelNotFoundException; +use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Notification; @@ -204,7 +205,7 @@ describe('RegisterCustomer action', function (): void { $employee->code = $code; $employee->nom = 'Inactive'; $employee->prenom = 'User'; - $employee->end_date = '2026-06-15'; + $employee->end_date = Carbon::parse('2026-06-15'); $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); $employee->site = new ShopperSiteCode('SITE'); $employee->service = new ShopperServiceCode('1'); @@ -443,8 +444,11 @@ describe('RegisterCustomer action', function (): void { { }; + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + // WHEN & THEN - expect(fn () => $action($invalidInput))->toThrow(\InvalidArgumentException::class); + expect(fn () => $callable($invalidInput))->toThrow(\InvalidArgumentException::class); }); it('acquires matricule lock via ActionExecutorService and returns LOCK_TIMEOUT when lock fails', function (): void { diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php index 027abcdd..13370599 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php @@ -35,6 +35,7 @@ use Domain\Services\OrderService; use Domain\Services\OrderTunnelService; use Domain\Services\PickupSchedulingService; use Domain\Services\ShopperService; +use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Session; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; @@ -62,6 +63,9 @@ describe('ApplyPickTimeSlot action', function (): void { Date::setTestNow(); }); + /** + * @return array{0: Customer, 1: Shop, 2: SessionOrderBuilderManager, 3: OrderTunnelService} + */ function makePickSlotEnvironment(): array { $shop = Shop::factory()->create(['default' => true]); @@ -77,7 +81,7 @@ describe('ApplyPickTimeSlot action', function (): void { $employee->code = new Code('ABCDEF'); $employee->nom = 'Durand'; $employee->prenom = 'Sophie'; - $employee->start_date = CarbonImmutable::parse('2025-01-01'); + $employee->start_date = Carbon::parse('2025-01-01'); $employee->etablissement = new ShopperEstablishmentCode('01'); $employee->site = new ShopperSiteCode('SITE'); $employee->service = new ShopperServiceCode('01'); @@ -106,6 +110,7 @@ describe('ApplyPickTimeSlot action', function (): void { ), ]); + /** @var \Illuminate\Contracts\Session\Session $session */ $session = Session::driver(); $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); $builderManager->save(OrderBuilder::fromBasket($basket, $customer->getId())); @@ -152,8 +157,8 @@ describe('ApplyPickTimeSlot action', function (): void { ->and($output->timeSlot?->getAt()->format('Y-m-d'))->toBe('2026-11-20'); $completed = $builderManager->get(); - expect($completed)->toBeInstanceOf(OrderBuilderCompleted::class) - ->and($completed?->getShopId()->equals($shop->getId()))->toBeTrue(); + assert($completed instanceof OrderBuilderCompleted); + expect($completed->getShopId()->equals($shop->getId()))->toBeTrue(); }); it('returns UNAVAILABLE when the requested date is blocked by a shop PickupException', function (): void { diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php index dccc41d3..90a716bf 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php @@ -39,6 +39,7 @@ use Ramsey\Uuid\Uuid; describe('InitializeOrderTunnel action', function (): void { it('stores OrderBuilderWithBasket in session for the shopper and basket', function (): void { // GIVEN + /** @var \Illuminate\Contracts\Session\Session $session */ $session = Session::driver(); $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); $shopRepo = new EloquentShopRepository(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php index 52e472d9..a0ecc755 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php @@ -41,7 +41,10 @@ describe('CreatePickupException action', function () { { }; + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + // WHEN & THEN - expect(fn () => $action($invalidInput))->toThrow(\InvalidArgumentException::class); + expect(fn () => $callable($invalidInput))->toThrow(\InvalidArgumentException::class); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php index 7a6fcb0e..53e6b377 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php @@ -34,7 +34,10 @@ describe('DeletePickupException action', function () { { }; + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + // WHEN & THEN - expect(fn () => $action($invalidInput))->toThrow(\InvalidArgumentException::class); + expect(fn () => $callable($invalidInput))->toThrow(\InvalidArgumentException::class); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php index 3af3227b..f963716c 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php @@ -54,7 +54,10 @@ describe('UpdatePickupException action', function () { { }; + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + // WHEN & THEN - expect(fn () => $action($invalidInput))->toThrow(\InvalidArgumentException::class); + expect(fn () => $callable($invalidInput))->toThrow(\InvalidArgumentException::class); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php index 210ee3bd..733f3b37 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php @@ -198,7 +198,10 @@ describe('AssociateProductInco action', function (): void { { }; + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + // WHEN & THEN - expect(fn () => $action($invalidInput))->toThrow(\InvalidArgumentException::class); + expect(fn () => $callable($invalidInput))->toThrow(\InvalidArgumentException::class); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php index 654085b2..b5f472d6 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php @@ -74,8 +74,11 @@ describe('CreateRange action', function () { { }; + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + // WHEN & THEN - expect(fn () => $action($invalidInput)) + expect(fn () => $callable($invalidInput)) ->toThrow(\InvalidArgumentException::class); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php index 41339510..7719010c 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php @@ -109,8 +109,11 @@ describe('DeleteRange action', function () { { }; + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + // WHEN & THEN - expect(fn () => $action($invalidInput)) + expect(fn () => $callable($invalidInput)) ->toThrow(\InvalidArgumentException::class); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php index cce8983d..0c769422 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php @@ -203,8 +203,11 @@ describe('UpdateRange action', function () { { }; + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + // WHEN & THEN - expect(fn () => $action($invalidInput)) + expect(fn () => $callable($invalidInput)) ->toThrow(\InvalidArgumentException::class); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php index 5e1c9a40..0f73e66a 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php @@ -55,8 +55,11 @@ describe('CreateShop action', function () { { }; + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + // WHEN & THEN - expect(fn () => $action($invalidInput)) + expect(fn () => $callable($invalidInput)) ->toThrow(\InvalidArgumentException::class); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php index 9ed27f84..26712129 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php @@ -34,8 +34,11 @@ describe('DeleteShop action', function () { { }; + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + // WHEN & THEN - expect(fn () => $action($invalidInput)) + expect(fn () => $callable($invalidInput)) ->toThrow(\InvalidArgumentException::class); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php index 467b8238..8e130c96 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php @@ -58,8 +58,11 @@ describe('UpdateShopPickupExceptions action', function () { { }; + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + // WHEN & THEN - expect(fn () => $action($invalidInput)) + expect(fn () => $callable($invalidInput)) ->toThrow(\InvalidArgumentException::class); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php index 4e4154e5..1ac678b6 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php @@ -62,8 +62,11 @@ describe('UpdateShop action', function () { { }; + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + // WHEN & THEN - expect(fn () => $action($invalidInput)) + expect(fn () => $callable($invalidInput)) ->toThrow(\InvalidArgumentException::class); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php index 7698b0fa..3e7a9557 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php @@ -28,7 +28,7 @@ describe('GetCustomerByEmailQuery', function (): void { // THEN expect($result)->toBeInstanceOf(ShopperId::class) - ->and($result->value->toString())->toBe($customer->id); + ->and($result?->value->toString())->toBe($customer->id); }); it('returns null when customer with email does not exist', function (): void { diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php index 179a739e..1e838f9c 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php @@ -32,7 +32,7 @@ describe('GetFaqsQuery', function (): void { // THEN expect($faqs)->toHaveCount(2) ->and($faqs->first())->toBeInstanceOf(FaqDto::class) - ->and($faqs->first()->question)->toBe('First question?') - ->and($faqs->last()->question)->toBe('Second question?'); + ->and($faqs->first()?->question)->toBe('First question?') + ->and($faqs->last()?->question)->toBe('Second question?'); }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductFormDataQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductFormDataQueryTest.php index 88a294db..f8804950 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductFormDataQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductFormDataQueryTest.php @@ -106,7 +106,7 @@ describe('GetProductFormDataQuery', function (): void { ->and($output->product?->tax_rate)->toBe(TaxRate::TVA_20) ->and($output->product?->invoicing_unit)->toBe(InvoicingUnit::PCE) ->and($output->product?->order_unit)->toBe(OrderUnit::PCE) - ->and(array_map(static fn ($t): int => $t->id, $output->product?->tags ?? []))->toBe([$tag->id]) + ->and(array_map(static fn ($t): int => $t->id, $output->product !== null ? $output->product->tags : []))->toBe([$tag->id]) ->and($output->selectedProds->pluck('id')->all())->toBe([(string) $productAssociated->id]) ->and($output->selectedProds->first())->toBeInstanceOf(ProductDto::class) ->and($output->existingProds->pluck('id')->all())->toContain((string) $productNotAssociated->id) diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopQueryTest.php index 137af7a1..a871fd58 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopQueryTest.php @@ -9,9 +9,9 @@ use App\Cqs\Queries\Shops\GetShopQuery; use App\Cqs\Queries\Shops\GetShopQueryInput; use App\Models\PickupException; use App\Models\Shop; -use Carbon\Carbon; use Domain\Enums\RepeatFrequency; use Illuminate\Database\Eloquent\ModelNotFoundException; +use Illuminate\Support\Carbon; use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; use Infrastructure\Adapters\Repositories\EloquentShopRepository; @@ -50,7 +50,7 @@ describe('GetShopQuery', function (): void { ->and($result->city)->toBe('Paris') ->and($result->default)->toBeTrue() ->and($result->pickupExceptions)->toHaveCount(1) - ->and($result->pickupExceptions->first()?->label)->toBe('Noël'); + ->and($result->pickupExceptions?->first()?->label)->toBe('Noël'); }); it('throws ModelNotFoundException when no default shop exists', function (): void { diff --git a/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php b/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php index 8ce8b20e..004336f7 100644 --- a/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php @@ -43,6 +43,7 @@ describe('PickupExceptionDto Integration', function () { $loadedShop = Shop::query()->with('pickupExceptions')->find($shop->id); $loadedException = $loadedShop?->pickupExceptions->first(); + assert($loadedException !== null); // WHEN $dto = PickupExceptionDto::fromModel($loadedException); diff --git a/tests/Integration/WithApp/App/Dto/ShopDtoTest.php b/tests/Integration/WithApp/App/Dto/ShopDtoTest.php index c9bdccca..2e5df4b9 100644 --- a/tests/Integration/WithApp/App/Dto/ShopDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/ShopDtoTest.php @@ -60,10 +60,15 @@ describe('ShopDto Integration', function () { $dto = ShopDto::fromModel($shop); // THEN - expect($dto->pickupExceptions)->not->toBeNull() - ->and($dto->pickupExceptions)->toHaveCount(1) - ->and($dto->pickupExceptions->first()->id)->toBe($exception->id) - ->and($dto->pickupExceptions->first()->pivot)->not->toBeNull() - ->and($dto->pickupExceptions->first()->pivot->replacement_date?->format('Y-m-d'))->toBe('2026-06-01'); + $pickupExceptions = $dto->pickupExceptions; + assert($pickupExceptions !== null); + $firstException = $pickupExceptions->first(); + assert($firstException !== null); + $pivot = $firstException->pivot; + assert($pivot !== null); + + expect($pickupExceptions)->toHaveCount(1) + ->and($firstException->id)->toBe($exception->id) + ->and($pivot->replacement_date?->format('Y-m-d'))->toBe('2026-06-01'); }); }); diff --git a/tests/Integration/WithApp/App/Dto/SlideDtoTest.php b/tests/Integration/WithApp/App/Dto/SlideDtoTest.php index 801823a4..5accd241 100644 --- a/tests/Integration/WithApp/App/Dto/SlideDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/SlideDtoTest.php @@ -9,6 +9,7 @@ use App\Lib\PublicS3Disk; use App\Models\Slide; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Storage; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('SlideDto integration', function (): void { beforeEach(function (): void { @@ -31,7 +32,7 @@ describe('SlideDto integration', function (): void { $slide->id = 42; $slide->title = 'Bannière Été'; $slide->text = '

Découvrez notre nouvelle collection

'; - $slide->picture = 'storage/modelfiles/slides/26/06/01/ab/summer.jpg'; + $slide->picture = new StorageFilePath('storage/modelfiles/slides/26/06/01/ab/summer.jpg'); $slide->picture_alt = 'Collection Été'; $slide->picture_title = 'Bannière promotionnelle été'; $slide->link = 'https://example.com/ete'; diff --git a/tests/Integration/WithApp/App/Policies/Frontend/OrderTunnelStepPolicyTest.php b/tests/Integration/WithApp/App/Policies/Frontend/OrderTunnelStepPolicyTest.php index cac204da..43a3f6ed 100644 --- a/tests/Integration/WithApp/App/Policies/Frontend/OrderTunnelStepPolicyTest.php +++ b/tests/Integration/WithApp/App/Policies/Frontend/OrderTunnelStepPolicyTest.php @@ -21,7 +21,7 @@ function createFakeGate(bool $returns): object { } - public function allows($ability, $arguments = []) + public function allows(string $ability, mixed $arguments = []): bool { return $this->returns; } diff --git a/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php b/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php index 19c71a47..4026cea5 100644 --- a/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php +++ b/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php @@ -127,12 +127,12 @@ describe('ActionExecutorService', function (): void { public function __construct( private readonly Lock $inner, private readonly ArrayStore $store, - private ?int &$levelAtAcquire, - private ?int &$levelAfterCommit, - private bool &$lockHeldAfterCommit, - private ?string &$capturedKey, - private ?int &$capturedTtl, - private ?int &$capturedWait, + public ?int &$levelAtAcquire, + public ?int &$levelAfterCommit, + public bool &$lockHeldAfterCommit, + public ?string &$capturedKey, + public ?int &$capturedTtl, + public ?int &$capturedWait, ) { } @@ -168,8 +168,8 @@ describe('ActionExecutorService', function (): void { { public function __construct( private readonly ArrayStore $store, - private ?int &$levelInsideAction, - private bool &$lockHeldInsideAction, + public ?int &$levelInsideAction, + public bool &$lockHeldInsideAction, ) { } @@ -302,7 +302,7 @@ describe('ActionExecutorService', function (): void { $action = new #[Locked(ttlSeconds: 30, waitSeconds: 10)] class ($invoked) implements Action, HandlesLockTimeout, ProvidesLockKey { public function __construct( - private bool &$invoked, + public bool &$invoked, ) { } @@ -409,7 +409,7 @@ describe('ActionExecutorService', function (): void { /** @param list $sequence */ public function __construct( private readonly Lock $inner, - private array &$sequence, + public array &$sequence, ) { } @@ -432,7 +432,7 @@ describe('ActionExecutorService', function (): void { { /** @param list $sequence */ public function __construct( - private array &$sequence, + public array &$sequence, ) { } @@ -465,7 +465,7 @@ describe('ActionExecutorService', function (): void { { /** @param list $sequence */ public function __construct( - private array &$sequence, + public array &$sequence, private readonly LaravelDomainEventDispatcher $eventDispatcher, ) { } @@ -484,6 +484,7 @@ describe('ActionExecutorService', function (): void { #[\Override] public function onSuccess(ActionInput $input, mixed $result): void { + assert(is_string($result)); $this->sequence[] = "action:onSuccess:{$result}"; } }; @@ -524,7 +525,7 @@ describe('ActionExecutorService', function (): void { $action = new class ($onSuccessCalled) implements Action, HandlesSuccess { public function __construct( - private bool &$onSuccessCalled, + public bool &$onSuccessCalled, ) { } @@ -573,7 +574,7 @@ describe('ActionExecutorService', function (): void { $action = new #[Locked(key: 'test:timeout')] class ($onSuccessCalled) implements Action, HandlesLockTimeout, HandlesSuccess { public function __construct( - private bool &$onSuccessCalled, + public bool &$onSuccessCalled, ) { } @@ -637,8 +638,8 @@ describe('ActionExecutorService', function (): void { $action = new class ($onSuccessCalled, $capturedException) implements Action, HandlesFailure, HandlesSuccess { public function __construct( - private bool &$onSuccessCalled, - private ?\Throwable &$capturedException, + public bool &$onSuccessCalled, + public ?\Throwable &$capturedException, ) { } @@ -700,8 +701,8 @@ describe('ActionExecutorService', function (): void { $action = new #[Locked(key: 'test:locked:failure')] class ($onSuccessCalled, $lockReleasedInHook, $store) implements Action, HandlesFailure, HandlesSuccess { public function __construct( - private bool &$onSuccessCalled, - private bool &$lockReleasedInHook, + public bool &$onSuccessCalled, + public bool &$lockReleasedInHook, private readonly ArrayStore $store, ) { } @@ -721,7 +722,7 @@ describe('ActionExecutorService', function (): void { public function onFailure(ActionInput $input, \Throwable $exception): void { $lock = $this->store->lock('test:locked:failure', 30); - $this->lockReleasedInHook = $lock->get(); + $this->lockReleasedInHook = (bool) $lock->get(); if ($this->lockReleasedInHook) { $lock->release(); @@ -770,7 +771,7 @@ describe('ActionExecutorService', function (): void { $action = new #[Locked(key: 'test:timeout:failure')] class ($capturedException) implements Action, HandlesFailure { public function __construct( - private ?\Throwable &$capturedException, + public ?\Throwable &$capturedException, ) { } @@ -821,7 +822,7 @@ describe('ActionExecutorService', function (): void { $action = new #[WithoutTransaction] class ($txLevelInsideAction, $postHookEvent, $eventDispatcher) implements Action, HandlesSuccess { public function __construct( - private ?int &$txLevelInsideAction, + public ?int &$txLevelInsideAction, private readonly Event $event, private readonly LaravelDomainEventDispatcher $dispatcher, ) { diff --git a/tests/Integration/WithApp/App/Services/CrmServiceTest.php b/tests/Integration/WithApp/App/Services/CrmServiceTest.php index 5b4d7efd..9a2ae38e 100644 --- a/tests/Integration/WithApp/App/Services/CrmServiceTest.php +++ b/tests/Integration/WithApp/App/Services/CrmServiceTest.php @@ -57,7 +57,7 @@ describe('CrmService', function (): void { $cacheRepository->shouldReceive('remember') ->once() - ->with($cacheKey, \Mockery::any(), \Mockery::on(function ($closure) use ($crmApi, $libCustomer, $uuid) { + ->with($cacheKey, \Mockery::any(), \Mockery::on(function (\Closure $closure) use ($crmApi, $libCustomer, $uuid) { $crmApi->shouldReceive('getCustomer')->with((string) $uuid)->once()->andReturn($libCustomer); $result = $closure(); @@ -92,7 +92,7 @@ describe('CrmService', function (): void { // THEN expect($firstCall)->toBeInstanceOf(CrmCustomer::class) - ->and($firstCall->hashcode)->toBe($uuid) + ->and($firstCall instanceof CrmCustomer ? $firstCall->hashcode : null)->toBe($uuid) ->and($secondCall)->toBe($firstCall); }); @@ -134,7 +134,7 @@ describe('CrmService', function (): void { // THEN expect($result)->toBeInstanceOf(CrmCustomer::class) - ->and($result->email)->toBe($email); + ->and($result instanceof CrmCustomer ? $result->email : null)->toBe($email); }); it('returns null on modelNotFound ApiErrorException and caches result', function (): void { @@ -147,7 +147,7 @@ describe('CrmService', function (): void { $cacheRepository->shouldReceive('remember') ->once() - ->with($cacheKey, \Mockery::any(), \Mockery::on(function ($closure) use ($crmApi, $uuid) { + ->with($cacheKey, \Mockery::any(), \Mockery::on(function (\Closure $closure) use ($crmApi, $uuid) { $exception = \Mockery::mock(ApiErrorException::class); $exception->shouldReceive('getApiError')->andReturn(ApiError::modelNotFound); $crmApi->shouldReceive('getCustomer')->with((string) $uuid)->once()->andThrow($exception); diff --git a/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php b/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php index ac42c1a7..06ce0514 100644 --- a/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php +++ b/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php @@ -50,7 +50,11 @@ describe('EmployeeSyncService', function (): void { $upsertService->shouldReceive('upsertEmployees') ->with(\Mockery::on(static function (array $data): bool { - return count($data) === 1 && $data[0]->matricule->value === '1234567'; + return count($data) === 1 + && is_object($data[0]) + && isset($data[0]->matricule) + && $data[0]->matricule instanceof Matricule + && $data[0]->matricule->value === '1234567'; })) ->once() ->andReturn(new EmployeeUpsertServiceResult( diff --git a/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php b/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php index e88ef850..1682ea30 100644 --- a/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php +++ b/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php @@ -47,7 +47,11 @@ describe('EmployeeUpsertService', function (): void { $storageService->shouldReceive('upsertEmployees') ->once() ->with(\Mockery::on(static function (array $data): bool { - return count($data) === 1 && $data[0]->matricule->value === '1234567'; + return count($data) === 1 + && is_object($data[0]) + && isset($data[0]->matricule) + && $data[0]->matricule instanceof Matricule + && $data[0]->matricule->value === '1234567'; })); $storageService->shouldReceive('getImportedAfter') diff --git a/tests/Integration/WithApp/App/Services/MailRegateServiceTest.php b/tests/Integration/WithApp/App/Services/MailRegateServiceTest.php index 9563b72a..047cbb50 100644 --- a/tests/Integration/WithApp/App/Services/MailRegateServiceTest.php +++ b/tests/Integration/WithApp/App/Services/MailRegateServiceTest.php @@ -31,7 +31,7 @@ describe('MailRegateService', function (): void { $reference = new OrderReference($uuid); $orderReferenceValue = (string) $reference; $employeeMatricule = new Matricule('1234567'); - $pickupDay = CarbonImmutable::create(2025, 1, 1); + $pickupDay = CarbonImmutable::parse('2025-01-01'); $line1 = new OrderPlacedLine( productName: 'Product 1', @@ -70,12 +70,15 @@ describe('MailRegateService', function (): void { \Mockery::type('array'), \Mockery::on(function (array $rows) use ($orderReferenceValue): bool { return count($rows) === 3 - && $rows[0][5] === 'UB' - && $rows[1][5] === 'UEA' - && $rows[2][5] === 'KGM' - && $rows[0][0] === '45' - && $rows[0][7] === '01/01/2025' - && $rows[0][9] === $orderReferenceValue; + && is_array($rows[0]) + && is_array($rows[1]) + && is_array($rows[2]) + && $rows[0][5] === 'UB' + && $rows[1][5] === 'UEA' + && $rows[2][5] === 'KGM' + && $rows[0][0] === '45' + && $rows[0][7] === '01/01/2025' + && $rows[0][9] === $orderReferenceValue; }) ) ->andReturn('csv_content'); @@ -103,7 +106,7 @@ describe('MailRegateService', function (): void { $reference = new OrderReference(Uuid::uuid7()); $employeeMatricule = new Matricule('1234567'); - $pickupDay = CarbonImmutable::create(2025, 1, 1); + $pickupDay = CarbonImmutable::parse('2025-01-01'); $csvGenerator = \Mockery::mock(CsvGenerator::class); $csvGenerator->shouldReceive('generate')->once()->andReturn('csv_content'); diff --git a/tests/Integration/WithApp/App/Services/ProductDtoAssemblerTest.php b/tests/Integration/WithApp/App/Services/ProductDtoAssemblerTest.php index b15ead8b..1ea85f28 100644 --- a/tests/Integration/WithApp/App/Services/ProductDtoAssemblerTest.php +++ b/tests/Integration/WithApp/App/Services/ProductDtoAssemblerTest.php @@ -21,6 +21,7 @@ use Money\Money; function assemblerTestProduct(string $name, bool $status = true): Product { + /** @var int $sequence */ static $sequence = 0; $sequence++; @@ -125,8 +126,8 @@ describe('GetPublishedProductWithPricingQuery', function (): void { ); // THEN - expect($dto)->not->toBeNull() - ->and($dto->product->name)->toBe('Produit Publié') + assert($dto !== null); + expect($dto->product->name)->toBe('Produit Publié') ->and($dto->pricing->hasDiscount)->toBeFalse(); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php index e91d4e98..f70bb985 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php @@ -54,8 +54,8 @@ describe('SessionBasketRepository', function () { $retrievedBasket = $repository->find($basketId); // THEN - expect($retrievedBasket)->toBeInstanceOf(Basket::class) - ->and($retrievedBasket->id->value->toString())->toBe($basketId->value->toString()) + assert($retrievedBasket !== null); + expect($retrievedBasket->id->value->toString())->toBe($basketId->value->toString()) ->and($retrievedBasket->items())->toHaveCount(1); $retrievedProduct = $retrievedBasket->items()[$product->id->value->toString()]; diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php index 3049ccdc..d4eaa838 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php @@ -12,7 +12,6 @@ use Domain\Enums\Country; use Domain\Exceptions\AuthServiceException; use Domain\Models\ValueObjects\CrmCustomer; use Domain\Models\ValueObjects\Email; -use Domain\Services\ShopperService; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\StatefulGuard; use Infrastructure\Adapters\Services\AppCustomerAuthService; @@ -23,12 +22,12 @@ use Shared\ValueObjects\CrmHashcode; describe('AppCustomerAuthService', function (): void { it('checks abilities with customer', function (): void { // GIVEN - $guard = Mockery::mock(StatefulGuard::class); - $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); - $customer = new class () extends Customer + $guard = Mockery::mock(StatefulGuard::class); + $crmService = Mockery::mock(CrmService::class); + $customer = new class () extends Customer { - public function can($abilities, $arguments = []) + /** @param iterable|string $abilities */ + public function can($abilities, $arguments = []): bool { return $abilities === 'view-order'; } @@ -36,7 +35,7 @@ describe('AppCustomerAuthService', function (): void { $guard->shouldReceive('user')->andReturn($customer); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $result = $service->canWithCustomer('view-order'); @@ -49,10 +48,9 @@ describe('AppCustomerAuthService', function (): void { // GIVEN $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); $guard->shouldReceive('user')->andReturn(null); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $result = $service->canWithCustomer('view-order'); @@ -66,13 +64,10 @@ describe('AppCustomerAuthService', function (): void { /** @var StatefulGuard&\Mockery\MockInterface $guard */ $guard = Mockery::spy(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); $customer->id = (string) Uuid::uuid7(); - $shopperService->shouldReceive('canCustomerPassOrdersApp')->withAnyArgs()->andReturn(true); - - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $service->logIn($customer); @@ -85,15 +80,15 @@ describe('AppCustomerAuthService', function (): void { // GIVEN $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); $invalidCustomer = new class () implements CustomerDetails { }; - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN + /** @phpstan-ignore argument.type */ $action = fn () => $service->logIn($invalidCustomer); // THEN @@ -105,9 +100,8 @@ describe('AppCustomerAuthService', function (): void { /** @var StatefulGuard&\Mockery\MockInterface $guard */ $guard = Mockery::spy(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $service->logout(); @@ -120,10 +114,9 @@ describe('AppCustomerAuthService', function (): void { // GIVEN $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); $guard->shouldReceive('check')->andReturn(true); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $check = $service->check(); @@ -138,11 +131,10 @@ describe('AppCustomerAuthService', function (): void { // GIVEN $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); $guard->shouldReceive('user')->andReturn($customer); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $returned = $service->getCustomer(); @@ -156,7 +148,6 @@ describe('AppCustomerAuthService', function (): void { // GIVEN $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); $user = new class () implements Authenticatable { @@ -180,7 +171,7 @@ describe('AppCustomerAuthService', function (): void { return 'password'; } - public function getRememberToken() + public function getRememberToken(): string { return ''; } @@ -196,7 +187,7 @@ describe('AppCustomerAuthService', function (): void { }; $guard->shouldReceive('user')->andReturn($user); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $action = fn () => $service->getCustomer(); @@ -209,12 +200,11 @@ describe('AppCustomerAuthService', function (): void { // GIVEN $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); $customer->id = 'cust-123'; $guard->shouldReceive('user')->andReturn($customer); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $returned = $service->getCustomerAsMandatory(); @@ -227,10 +217,9 @@ describe('AppCustomerAuthService', function (): void { // GIVEN $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); $guard->shouldReceive('user')->andReturn(null); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $action = fn () => $service->getCustomerAsMandatory(); @@ -243,13 +232,12 @@ describe('AppCustomerAuthService', function (): void { // GIVEN $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); $customer->email = new Email('test@example.com'); $crmService->shouldReceive('resetPasswordFor')->with($customer->email, 'newpass')->andReturn(true); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $result = $service->resetPasswordFor($customer, 'newpass'); @@ -262,7 +250,6 @@ describe('AppCustomerAuthService', function (): void { // GIVEN $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); $hashcode = new CrmHashcode(Uuid::uuid4()); $customer->hashcode = $hashcode; @@ -288,7 +275,7 @@ describe('AppCustomerAuthService', function (): void { $crmService->shouldReceive('getCustomerFromHashCode')->with($customer->hashcode)->andReturn($crmCustomer); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $result = $service->hasVerifiedEmail($customer); @@ -301,14 +288,13 @@ describe('AppCustomerAuthService', function (): void { // GIVEN $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); $hashcode = new CrmHashcode(Uuid::uuid4()); $customer->hashcode = $hashcode; $crmService->shouldReceive('getCustomerFromHashCode')->with($customer->hashcode)->andReturn(null); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $result = $service->hasVerifiedEmail($customer); @@ -321,7 +307,6 @@ describe('AppCustomerAuthService', function (): void { // GIVEN $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); $hashcode = new CrmHashcode(Uuid::uuid4()); $customer->hashcode = $hashcode; @@ -350,7 +335,7 @@ describe('AppCustomerAuthService', function (): void { $activation->result = true; $crmService->shouldReceive('activate')->with($crmCustomer)->andReturn($activation); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $result = $service->verifyEmail($customer); @@ -363,14 +348,13 @@ describe('AppCustomerAuthService', function (): void { // GIVEN $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); $hashcode = new CrmHashcode(Uuid::uuid4()); $customer->hashcode = $hashcode; $crmService->shouldReceive('getCustomerFromHashCode')->with($customer->hashcode)->andReturn(null); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $result = $service->verifyEmail($customer); @@ -383,7 +367,6 @@ describe('AppCustomerAuthService', function (): void { // GIVEN $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); - $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); $hashcode = new CrmHashcode(Uuid::uuid4()); $customer->hashcode = $hashcode; @@ -391,7 +374,7 @@ describe('AppCustomerAuthService', function (): void { $exception = new CrmServiceException('Crm Error'); $crmService->shouldReceive('getCustomerFromHashCode')->with($customer->hashcode)->andReturn($exception); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $action = fn () => $service->hasVerifiedEmail($customer); diff --git a/tests/Unit/App/Cqs/Actions/Common/ExecuteMassActionInputTest.php b/tests/Unit/App/Cqs/Actions/Common/ExecuteMassActionInputTest.php index 76cf5cfa..c60630f5 100644 --- a/tests/Unit/App/Cqs/Actions/Common/ExecuteMassActionInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Common/ExecuteMassActionInputTest.php @@ -31,10 +31,10 @@ describe('ExecuteMassActionInput', function (): void { $invalidModelClass = \stdClass::class; // WHEN & THEN - expect(fn () => new ExecuteMassActionInput( - modelClass: $invalidModelClass, - action: MassActionType::Star, - modelKeyList: [1], + expect(fn () => (new \ReflectionClass(ExecuteMassActionInput::class))->newInstance( + $invalidModelClass, + MassActionType::Star, + [1], ))->toThrow(\InvalidArgumentException::class); }); diff --git a/tests/Unit/App/Cqs/Actions/Slides/UpdateSlideInputTest.php b/tests/Unit/App/Cqs/Actions/Slides/UpdateSlideInputTest.php index 3cb2636b..4cca2abe 100644 --- a/tests/Unit/App/Cqs/Actions/Slides/UpdateSlideInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Slides/UpdateSlideInputTest.php @@ -6,12 +6,13 @@ namespace Tests\Unit\App\Cqs\Actions\Slides; use App\Cqs\Actions\Slides\UpdateSlideInput; use App\Models\Slide; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('UpdateSlideInput', function (): void { it('creates a valid UpdateSlideInput instance with existing slide picture', function (): void { // GIVEN $slide = new Slide(); - $slide->picture = 'storage/modelfiles/slides/existing.jpg'; + $slide->picture = new StorageFilePath('storage/modelfiles/slides/existing.jpg'); $title = 'Slide Modifié'; // WHEN diff --git a/tests/Unit/Domain/Events/DtoTest.php b/tests/Unit/Domain/Events/DtoTest.php index 2ad2786f..e23a3791 100644 --- a/tests/Unit/Domain/Events/DtoTest.php +++ b/tests/Unit/Domain/Events/DtoTest.php @@ -191,11 +191,10 @@ describe('SalariesHaveBeenSynced', function () { it('throws exception if SalariesHaveBeenSynced gets non-matricule', function () { // GIVEN - /** @var array $matricules */ $matricules = ['1234567']; // WHEN - $action = fn () => new SalariesHaveBeenSynced($matricules); + $action = fn () => (new \ReflectionClass(SalariesHaveBeenSynced::class))->newInstance($matricules); // THEN expect($action)->toThrow(\UnexpectedValueException::class); }); diff --git a/tests/Unit/Domain/Models/Entities/BasketTest.php b/tests/Unit/Domain/Models/Entities/BasketTest.php index 94f6f135..89e580d0 100644 --- a/tests/Unit/Domain/Models/Entities/BasketTest.php +++ b/tests/Unit/Domain/Models/Entities/BasketTest.php @@ -19,29 +19,48 @@ use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('Basket and BasketProduct', function (): void { + /** + * @param array{ + * id?: ProductId, + * name?: string, + * qty?: int, + * unitPriceHt?: Money, + * unitDiscount?: Money, + * taxRate?: TaxRate, + * weightGrams?: int, + * brand?: ProductBrand, + * incoId?: IncoId|null, + * orderUnit?: OrderUnit, + * slug?: string, + * picture?: StorageFilePath|null, + * description?: string|null, + * weightVariable?: bool, + * discountRate?: DiscountRate, + * priceKgTtc?: Money, + * options?: array, + * } $overrides + */ function getNewBasketProduct(array $overrides = []): BasketProduct { - $data = array_merge([ - 'id' => new ProductId(Uuid::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')), - 'name' => 'Poulet Rôti', - 'qty' => 2, - 'unitPriceHt' => Money::EUR(1000), - 'unitDiscount' => Money::EUR(200), - 'taxRate' => TaxRate::TVA_5_5, - 'weightGrams' => 1200, - 'brand' => ProductBrand::marie, - 'incoId' => new IncoId(45), - 'orderUnit' => OrderUnit::PCE, - 'slug' => 'poulet-roti', - 'picture' => new StorageFilePath('images/poulet.jpg'), - 'description' => 'Un bon poulet rôti', - 'weightVariable' => true, - 'discountRate' => DiscountRate::fromRatio(0.2), - 'priceKgTtc' => Money::EUR(1500), - 'options' => ['extra' => 'crispy'], - ], $overrides); - - return new BasketProduct(...$data); + return new BasketProduct( + id: $overrides['id'] ?? new ProductId(Uuid::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')), + name: $overrides['name'] ?? 'Poulet Rôti', + qty: $overrides['qty'] ?? 2, + unitPriceHt: $overrides['unitPriceHt'] ?? Money::EUR(1000), + unitDiscount: $overrides['unitDiscount'] ?? Money::EUR(200), + taxRate: $overrides['taxRate'] ?? TaxRate::TVA_5_5, + weightGrams: $overrides['weightGrams'] ?? 1200, + brand: $overrides['brand'] ?? ProductBrand::marie, + incoId: $overrides['incoId'] ?? new IncoId(45), + orderUnit: $overrides['orderUnit'] ?? OrderUnit::PCE, + slug: $overrides['slug'] ?? 'poulet-roti', + picture: $overrides['picture'] ?? new StorageFilePath('images/poulet.jpg'), + description: $overrides['description'] ?? 'Un bon poulet rôti', + weightVariable: $overrides['weightVariable'] ?? true, + discountRate: $overrides['discountRate'] ?? DiscountRate::fromRatio(0.2), + priceKgTtc: $overrides['priceKgTtc'] ?? Money::EUR(1500), + options: $overrides['options'] ?? ['extra' => 'crispy'], + ); } it('can instantiate a basket product with all new typed properties', function (): void { @@ -83,7 +102,7 @@ describe('Basket and BasketProduct', function (): void { expect($item->taxRate)->toBe(TaxRate::TVA_5_5); expect($item->weightGrams)->toBe(1200); expect($item->brand)->toBe(ProductBrand::marie); - expect($item->incoId->value)->toBe(45); + expect($item->incoId?->value)->toBe(45); expect($item->orderUnit)->toBe(OrderUnit::PCE); expect($item->slug)->toBe('poulet-roti'); expect((string) $item->picture)->toBe('images/poulet.jpg'); @@ -114,7 +133,7 @@ describe('Basket and BasketProduct', function (): void { $updatedItem = $basket->items()[(string) $productId->value]; expect($updatedItem->qty)->toBe(5); expect($updatedItem->brand)->toBe(ProductBrand::marie); - expect($updatedItem->incoId->value)->toBe(45); + expect($updatedItem->incoId?->value)->toBe(45); expect($updatedItem->orderUnit)->toBe(OrderUnit::PCE); expect($updatedItem->slug)->toBe('poulet-roti'); expect((string) $updatedItem->picture)->toBe('images/poulet.jpg'); @@ -131,7 +150,7 @@ describe('Basket additional coverage', function (): void { // GIVEN $basketId = new BasketId(Uuid::uuid7()); // WHEN - $action = fn () => new Basket($basketId, ['not-an-item']); + $action = fn () => (new \ReflectionClass(Basket::class))->newInstance($basketId, ['not-an-item']); // THEN expect($action)->toThrow(\DomainException::class); }); diff --git a/tests/Unit/Domain/Models/Entities/OrderTest.php b/tests/Unit/Domain/Models/Entities/OrderTest.php index ac2572c3..c4345814 100644 --- a/tests/Unit/Domain/Models/Entities/OrderTest.php +++ b/tests/Unit/Domain/Models/Entities/OrderTest.php @@ -38,6 +38,19 @@ use Money\Money; use Ramsey\Uuid\Uuid; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; +/** + * @param array{ + * productName?: string, + * quantity?: int, + * unitPriceHt?: Money, + * unitDiscount?: Money, + * unitTax?: Money, + * totalHt?: Money, + * totalDiscount?: Money, + * totalTax?: Money, + * totalTtc?: Money, + * } $overrides + */ function makeOrderLine(array $overrides = []): OrderLine { $product = new OrderLineProduct( @@ -66,6 +79,19 @@ function makeOrderLine(array $overrides = []): OrderLine ); } +/** + * @param array{ + * id?: OrderId, + * shopId?: ShopId, + * reference?: OrderReference, + * employee?: OrderEmployee, + * deliveryAddress?: DeliveryAddress, + * pickupTimeSlot?: PickupTimeSlot, + * status?: OrderStatus, + * total?: Money, + * lines?: array, + * } $overrides + */ function makeOrder(array $overrides = []): Order { return new Order( @@ -137,10 +163,21 @@ describe('Order - Instantiation', function (): void { it('throws if lines contain non-OrderLine instances', function (): void { // GIVEN + $order = makeOrder(); $lines = ['not-an-order-line']; // WHEN - $action = fn () => makeOrder(['lines' => $lines]); + $action = fn () => (new \ReflectionClass(Order::class))->newInstance( + $order->id, + $order->shopId, + $order->reference, + $order->employee, + $order->deliveryAddress, + $order->pickupTimeSlot, + $order->status, + Money::EUR(3798), + $lines, + ); // THEN expect($action)->toThrow(\DomainException::class, 'All lines must be instances of OrderLine'); diff --git a/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php b/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php index 33aaebec..cdbb4b77 100644 --- a/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php +++ b/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php @@ -54,8 +54,8 @@ describe('PickupExceptionOnDate', function (): void { it('determines if exception falls on a pickup day', function (): void { // GIVEN - $fridayDate = CarbonImmutable::create(2025, 1, 3); // 2025-01-03 is Friday - $mondayDate = CarbonImmutable::create(2025, 1, 6); // 2025-01-06 is Monday + $fridayDate = CarbonImmutable::parse('2025-01-03'); // 2025-01-03 is Friday + $mondayDate = CarbonImmutable::parse('2025-01-06'); // 2025-01-06 is Monday $fridayException = new PickupExceptionOnDate( new PickupExceptionId(Uuid::uuid7()), diff --git a/tests/Unit/Domain/Models/ValueObjects/AttachedFileTest.php b/tests/Unit/Domain/Models/ValueObjects/AttachedFileTest.php index c16ee833..baeec1a9 100644 --- a/tests/Unit/Domain/Models/ValueObjects/AttachedFileTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/AttachedFileTest.php @@ -8,15 +8,14 @@ use Domain\Models\ValueObjects\AttachedFile; describe('AttachedFile', function () { + /** @param array{path?: string, originalName?: string, mimeType?: string} $overrides */ function getNewAttachedFile(array $overrides = []): AttachedFile { - $data = array_merge([ - 'path' => 'path/to/file', - 'originalName' => 'file.pdf', - 'mimeType' => 'application/pdf', - ], $overrides); - - return new AttachedFile(...$data); + return new AttachedFile( + path: $overrides['path'] ?? 'path/to/file', + originalName: $overrides['originalName'] ?? 'file.pdf', + mimeType: $overrides['mimeType'] ?? 'application/pdf', + ); } it('can instantiate', function () { diff --git a/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php b/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php index 66960ff4..8afad6f9 100644 --- a/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php @@ -21,28 +21,46 @@ describe('BasketProduct', function () { return new Money($amount, new Currency('EUR')); } + /** + * @param array{ + * id?: ProductId, + * name?: string, + * qty?: int, + * unitPriceHt?: Money, + * unitDiscount?: Money, + * taxRate?: TaxRate, + * weightGrams?: int, + * brand?: ProductBrand, + * incoId?: \Domain\Models\ValueObjects\IncoId|null, + * orderUnit?: OrderUnit, + * slug?: string, + * picture?: \Uwil\Storage\Lib\ValueObjects\StorageFilePath|null, + * description?: string|null, + * weightVariable?: bool, + * discountRate?: DiscountRate, + * priceKgTtc?: Money, + * } $overrides + */ function getNewProduct(array $overrides = []): BasketProduct { - $data = array_merge([ - 'id' => new ProductId(Uuid::uuid7()), - 'name' => 'Product Name', - 'qty' => 1, - 'unitPriceHt' => getMoney(100), - 'unitDiscount' => getMoney(10), - 'taxRate' => TaxRate::TVA_20, - 'weightGrams' => 500, - 'brand' => ProductBrand::none, - 'incoId' => null, - 'orderUnit' => OrderUnit::PCE, - 'slug' => 'product-slug', - 'picture' => null, - 'description' => null, - 'weightVariable' => false, - 'discountRate' => DiscountRate::fromRatio(0.1), - 'priceKgTtc' => getMoney(240), - ], $overrides); - - return new BasketProduct(...$data); + return new BasketProduct( + id: $overrides['id'] ?? new ProductId(Uuid::uuid7()), + name: $overrides['name'] ?? 'Product Name', + qty: $overrides['qty'] ?? 1, + unitPriceHt: $overrides['unitPriceHt'] ?? getMoney(100), + unitDiscount: $overrides['unitDiscount'] ?? getMoney(10), + taxRate: $overrides['taxRate'] ?? TaxRate::TVA_20, + weightGrams: $overrides['weightGrams'] ?? 500, + brand: $overrides['brand'] ?? ProductBrand::none, + incoId: $overrides['incoId'] ?? null, + orderUnit: $overrides['orderUnit'] ?? OrderUnit::PCE, + slug: $overrides['slug'] ?? 'product-slug', + picture: $overrides['picture'] ?? null, + description: $overrides['description'] ?? null, + weightVariable: $overrides['weightVariable'] ?? false, + discountRate: $overrides['discountRate'] ?? DiscountRate::fromRatio(0.1), + priceKgTtc: $overrides['priceKgTtc'] ?? getMoney(240), + ); } // --- Tests d'instanciation et de validation (Invariants) --- diff --git a/tests/Unit/Domain/Models/ValueObjects/ContactFormDataTest.php b/tests/Unit/Domain/Models/ValueObjects/ContactFormDataTest.php index 981fbd6d..dba19bb9 100644 --- a/tests/Unit/Domain/Models/ValueObjects/ContactFormDataTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/ContactFormDataTest.php @@ -10,19 +10,28 @@ use Ramsey\Uuid\Uuid; describe('ContactFormData', function () { + /** + * @param array{ + * lastName?: string, + * firstName?: string, + * email?: string, + * subject?: string, + * message?: string, + * orderRef?: \Domain\Models\ValueObjects\OrderReference|null, + * file?: \Domain\Models\ValueObjects\AttachedFile|null, + * } $overrides + */ function getNewContactFormData(array $overrides = []): ContactFormData { - $data = array_merge([ - 'lastName' => 'Doe', - 'firstName' => 'John', - 'email' => 'john@example.com', - 'subject' => 'Inquiry', - 'message' => 'This is a message.', - 'orderRef' => null, - 'file' => null, - ], $overrides); - - return new ContactFormData(...$data); + return new ContactFormData( + lastName: $overrides['lastName'] ?? 'Doe', + firstName: $overrides['firstName'] ?? 'John', + email: $overrides['email'] ?? 'john@example.com', + subject: $overrides['subject'] ?? 'Inquiry', + message: $overrides['message'] ?? 'This is a message.', + orderRef: $overrides['orderRef'] ?? null, + file: $overrides['file'] ?? null, + ); } it('can instantiate', function () { diff --git a/tests/Unit/Domain/Models/ValueObjects/NutritionalValuesTest.php b/tests/Unit/Domain/Models/ValueObjects/NutritionalValuesTest.php index 02d7fc9b..a78b4ef8 100644 --- a/tests/Unit/Domain/Models/ValueObjects/NutritionalValuesTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/NutritionalValuesTest.php @@ -8,9 +8,34 @@ use Domain\Models\ValueObjects\NutritionalValues; describe('NutritionalValues', function () { + /** + * @param array{ + * refWeightG?: float|null, + * kj?: float|null, + * kcal?: float|null, + * fatG?: float|null, + * satFatG?: float|null, + * carbG?: float|null, + * sugarG?: float|null, + * proteinG?: float|null, + * saltG?: float|null, + * dailyEnergy?: float|null, + * } $overrides + */ function getNewNutritionalValues(array $overrides = []): NutritionalValues { - return new NutritionalValues(...$overrides); + return new NutritionalValues( + refWeightG: $overrides['refWeightG'] ?? null, + kj: $overrides['kj'] ?? null, + kcal: $overrides['kcal'] ?? null, + fatG: $overrides['fatG'] ?? null, + satFatG: $overrides['satFatG'] ?? null, + carbG: $overrides['carbG'] ?? null, + sugarG: $overrides['sugarG'] ?? null, + proteinG: $overrides['proteinG'] ?? null, + saltG: $overrides['saltG'] ?? null, + dailyEnergy: $overrides['dailyEnergy'] ?? null, + ); } it('can instantiate', function () { diff --git a/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php b/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php index cb601c10..a6c58fbe 100644 --- a/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php @@ -16,23 +16,36 @@ use Money\Money; use Ramsey\Uuid\Uuid; describe('OrderLine', function (): void { + /** + * @param array{ + * incoId?: IncoId, + * originalId?: ProductId, + * name?: string, + * weight?: ProductWeight, + * brand?: ProductBrand, + * orderUnit?: OrderUnit, + * price?: Money, + * discountedPrice?: Money, + * priceKgTtc?: Money, + * taxRate?: TaxRate, + * picture?: \Uwil\Storage\Lib\ValueObjects\StorageFilePath|null, + * } $overrides + */ function getNewOrderLineProduct(array $overrides = []): OrderLineProduct { - $data = array_merge([ - 'incoId' => new IncoId(1), - 'originalId' => new ProductId(Uuid::uuid7()), - 'name' => 'poulet blanc', - 'weight' => new ProductWeight(200, false), - 'brand' => ProductBrand::loue, - 'orderUnit' => OrderUnit::KGM, - 'price' => Money::EUR(100), - 'discountedPrice' => Money::EUR(100), - 'priceKgTtc' => Money::EUR(500), - 'taxRate' => TaxRate::TVA_20, - 'picture' => null, - ], $overrides); - - return new OrderLineProduct(...$data); + return new OrderLineProduct( + incoId: $overrides['incoId'] ?? new IncoId(1), + originalId: $overrides['originalId'] ?? new ProductId(Uuid::uuid7()), + name: $overrides['name'] ?? 'poulet blanc', + weight: $overrides['weight'] ?? new ProductWeight(200, false), + brand: $overrides['brand'] ?? ProductBrand::loue, + orderUnit: $overrides['orderUnit'] ?? OrderUnit::KGM, + price: $overrides['price'] ?? Money::EUR(100), + discountedPrice: $overrides['discountedPrice'] ?? Money::EUR(100), + priceKgTtc: $overrides['priceKgTtc'] ?? Money::EUR(500), + taxRate: $overrides['taxRate'] ?? TaxRate::TVA_20, + picture: $overrides['picture'] ?? null, + ); } it('can instantiate correctly', function (): void { diff --git a/tests/Unit/Domain/Models/ValueObjects/ProductPricingTest.php b/tests/Unit/Domain/Models/ValueObjects/ProductPricingTest.php index 35a91189..72a46686 100644 --- a/tests/Unit/Domain/Models/ValueObjects/ProductPricingTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/ProductPricingTest.php @@ -16,20 +16,30 @@ describe('ProductPricing', function () { return new Money($amount, new Currency('EUR')); } + /** + * @param array{ + * basePriceHt?: Money, + * basePriceTtc?: Money, + * discountAmountHt?: Money, + * discountedPriceHt?: Money, + * discountedPriceTtc?: Money, + * priceKgTtc?: Money, + * discountRate?: DiscountRate, + * hasDiscount?: bool, + * } $overrides + */ function getNewProductPricing(array $overrides = []): ProductPricing { - $data = array_merge([ - 'basePriceHt' => getPricingMoney(1000), - 'basePriceTtc' => getPricingMoney(1200), - 'discountAmountHt' => getPricingMoney(100), - 'discountedPriceHt' => getPricingMoney(900), - 'discountedPriceTtc' => getPricingMoney(1080), - 'priceKgTtc' => getPricingMoney(2000), - 'discountRate' => DiscountRate::fromRatio(0.1), - 'hasDiscount' => false, - ], $overrides); - - return new ProductPricing(...$data); + return new ProductPricing( + basePriceHt: $overrides['basePriceHt'] ?? getPricingMoney(1000), + basePriceTtc: $overrides['basePriceTtc'] ?? getPricingMoney(1200), + discountAmountHt: $overrides['discountAmountHt'] ?? getPricingMoney(100), + discountedPriceHt: $overrides['discountedPriceHt'] ?? getPricingMoney(900), + discountedPriceTtc: $overrides['discountedPriceTtc'] ?? getPricingMoney(1080), + priceKgTtc: $overrides['priceKgTtc'] ?? getPricingMoney(2000), + discountRate: $overrides['discountRate'] ?? DiscountRate::fromRatio(0.1), + hasDiscount: $overrides['hasDiscount'] ?? false, + ); } it('can instantiate', function () { diff --git a/tests/Unit/Domain/Models/ValueObjects/ShopPickupOverrideTest.php b/tests/Unit/Domain/Models/ValueObjects/ShopPickupOverrideTest.php index e821d0cb..5ba7c9fe 100644 --- a/tests/Unit/Domain/Models/ValueObjects/ShopPickupOverrideTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/ShopPickupOverrideTest.php @@ -80,14 +80,14 @@ describe('ShopPickupOverride', function (): void { // GIVEN $exception = new PickupExceptionOnDate( new PickupExceptionId(Uuid::uuid7()), - CarbonImmutable::create(2025, 5, 1), + CarbonImmutable::parse('2025-05-01'), 'Labour Day', false, RepeatFrequency::YEARLY, false ); - $defaultDeadline = CarbonImmutable::create(2025, 4, 28, 14, 0, 0); + $defaultDeadline = CarbonImmutable::parse('2025-04-28 14:00:00'); $blockedOverride = new ShopPickupOverride( exception: $exception, @@ -95,10 +95,10 @@ describe('ShopPickupOverride', function (): void { orderDeadlineAt: null ); - $customDeadline = CarbonImmutable::create(2025, 4, 29, 12, 0, 0); + $customDeadline = CarbonImmutable::parse('2025-04-29 12:00:00'); $activeOverride = new ShopPickupOverride( exception: $exception, - replacementDate: CarbonImmutable::create(2025, 5, 2), + replacementDate: CarbonImmutable::parse('2025-05-02'), orderDeadlineAt: $customDeadline ); @@ -108,8 +108,8 @@ describe('ShopPickupOverride', function (): void { ->and($activeOverride->hasReplacement())->toBeTrue() ->and($activeOverride->effectiveDeadline($defaultDeadline)->equalTo($customDeadline))->toBeTrue(); - $beforeCustom = CarbonImmutable::create(2025, 4, 29, 10, 0, 0); - $afterCustom = CarbonImmutable::create(2025, 4, 29, 15, 0, 0); + $beforeCustom = CarbonImmutable::parse('2025-04-29 10:00:00'); + $afterCustom = CarbonImmutable::parse('2025-04-29 15:00:00'); expect($activeOverride->isDeadlinePassed($beforeCustom, $defaultDeadline))->toBeFalse() ->and($activeOverride->isDeadlinePassed($afterCustom, $defaultDeadline))->toBeTrue(); diff --git a/tests/Unit/Domain/Services/BasketServiceTest.php b/tests/Unit/Domain/Services/BasketServiceTest.php index 7389fd74..8ec78b91 100644 --- a/tests/Unit/Domain/Services/BasketServiceTest.php +++ b/tests/Unit/Domain/Services/BasketServiceTest.php @@ -26,29 +26,27 @@ use Ramsey\Uuid\Uuid; use Shared\DDD\DomainEventDispatcher; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; -/** @param array $overrides */ +/** @param array{id?: ProductId, qty?: int, unitPriceHt?: Money, unitDiscount?: Money} $overrides */ function makeBasketProduct(array $overrides = []): BasketProduct { - $data = array_merge([ - 'id' => new ProductId(Uuid::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')), - 'name' => 'Poulet Rôti', - 'qty' => 1, - 'unitPriceHt' => Money::EUR(1000), - 'unitDiscount' => Money::EUR(0), - 'taxRate' => TaxRate::TVA_5_5, - 'weightGrams' => 1200, - 'brand' => ProductBrand::marie, - 'incoId' => new IncoId(45), - 'orderUnit' => OrderUnit::PCE, - 'slug' => 'poulet-roti', - 'picture' => new StorageFilePath('images/poulet.jpg'), - 'description' => 'Un bon poulet', - 'weightVariable' => false, - 'discountRate' => DiscountRate::fromRatio(0.0), - 'priceKgTtc' => Money::EUR(1500), - ], $overrides); - - return new BasketProduct(...$data); + return new BasketProduct( + id: $overrides['id'] ?? new ProductId(Uuid::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')), + name: 'Poulet Rôti', + qty: $overrides['qty'] ?? 1, + unitPriceHt: $overrides['unitPriceHt'] ?? Money::EUR(1000), + unitDiscount: $overrides['unitDiscount'] ?? Money::EUR(0), + taxRate: TaxRate::TVA_5_5, + weightGrams: 1200, + brand: ProductBrand::marie, + incoId: new IncoId(45), + orderUnit: OrderUnit::PCE, + slug: 'poulet-roti', + picture: new StorageFilePath('images/poulet.jpg'), + description: 'Un bon poulet', + weightVariable: false, + discountRate: DiscountRate::fromRatio(0.0), + priceKgTtc: Money::EUR(1500), + ); } describe('BasketService', function (): void { diff --git a/tests/Unit/Domain/Services/OrderServiceTest.php b/tests/Unit/Domain/Services/OrderServiceTest.php index e6a90b71..09df7d18 100644 --- a/tests/Unit/Domain/Services/OrderServiceTest.php +++ b/tests/Unit/Domain/Services/OrderServiceTest.php @@ -247,6 +247,7 @@ describe('Order Creation', function () { expect($product->incoId->value)->toBe(45); expect($product->orderUnit)->toBe(OrderUnit::PCE); expect($product->picture)->toBeInstanceOf(StorageFilePath::class); + assert($product->picture instanceof StorageFilePath); expect($product->picture->value)->toBe('images/poulet.jpg'); }); diff --git a/tests/Unit/Domain/Services/ShopperServiceTest.php b/tests/Unit/Domain/Services/ShopperServiceTest.php index 74955a85..87901734 100644 --- a/tests/Unit/Domain/Services/ShopperServiceTest.php +++ b/tests/Unit/Domain/Services/ShopperServiceTest.php @@ -104,7 +104,7 @@ describe('ShopperService', function (): void { $service = new ShopperService($shopRepo, $shopperRepo); $shopper = new Shopper( - isset($id) ? $id : new ShopperId(Uuid::uuid7()), + new ShopperId(Uuid::uuid7()), new Email('test@test.com'), new Matricule('1234567'), 'Nom', diff --git a/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php b/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php index 447a4145..f71ef3db 100644 --- a/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php +++ b/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php @@ -20,189 +20,188 @@ use Ramsey\Uuid\Uuid; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; it('serializes and deserializes basket correctly', function () { - describe('BasketSerializer', function () { - // GIVEN - $serializer = new BasketSerializer(); + // GIVEN + $serializer = new BasketSerializer(); - $basketIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); - $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); + $basketIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); + $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); - $basketProduct = new BasketProduct( - id: new ProductId(Uuid::fromString($productIdStr)), - name: 'Product 1', - qty: 2, - unitPriceHt: new Money(1000, new Currency('EUR')), - unitDiscount: new Money(100, new Currency('EUR')), - taxRate: TaxRate::TVA_20, - weightGrams: 500, - brand: ProductBrand::loue, - incoId: new IncoId(12345), - orderUnit: OrderUnit::PCE, - slug: 'product-1', - picture: new StorageFilePath('pic.png'), - description: 'desc', - weightVariable: true, - discountRate: DiscountRate::fromRatio(0.1), - priceKgTtc: new Money(2000, new Currency('EUR')), - options: ['color' => 'red'] - ); + $basketProduct = new BasketProduct( + id: new ProductId(Uuid::fromString($productIdStr)), + name: 'Product 1', + qty: 2, + unitPriceHt: new Money(1000, new Currency('EUR')), + unitDiscount: new Money(100, new Currency('EUR')), + taxRate: TaxRate::TVA_20, + weightGrams: 500, + brand: ProductBrand::loue, + incoId: new IncoId(12345), + orderUnit: OrderUnit::PCE, + slug: 'product-1', + picture: new StorageFilePath('pic.png'), + description: 'desc', + weightVariable: true, + discountRate: DiscountRate::fromRatio(0.1), + priceKgTtc: new Money(2000, new Currency('EUR')), + options: ['color' => 'red'] + ); - $basket = new Basket( - id: new BasketId(Uuid::fromString($basketIdStr)), - items: [$productIdStr => $basketProduct] - ); + $basket = new Basket( + id: new BasketId(Uuid::fromString($basketIdStr)), + items: [$productIdStr => $basketProduct] + ); - // WHEN - $array = $serializer->toArray($basket); - $array = json_decode(json_encode($array), true); - $deserializedBasket = $serializer->fromArray($array); + // WHEN + $array = $serializer->toArray($basket); + $json = json_encode($array, JSON_THROW_ON_ERROR); + /** @var array{id: string, items: array>} $array */ + $array = json_decode($json, true, 512, JSON_THROW_ON_ERROR); + $deserializedBasket = $serializer->fromArray($array); - // THEN - expect($array)->toBeArray() - ->and($array['id'])->toBe($basketIdStr) - ->and($array['items'][0]['id'])->toBe($productIdStr) - ->and($array['items'][0]['name'])->toBe('Product 1') - ->and($array['items'][0]['taxRate'])->toBe(TaxRate::TVA_20->value) - ->and($deserializedBasket->id->value->toString())->toBe($basketIdStr) - ->and($deserializedBasket->items())->toHaveCount(1) - ->and($deserializedBasket->items()[$productIdStr]->name)->toBe('Product 1') - ->and($deserializedBasket->items()[$productIdStr]->weightVariable)->toBeTrue() - ->and($deserializedBasket->items()[$productIdStr]->options)->toBe(['color' => 'red']) - ->and($array['items'][0]['discountRateBp'])->toBe(1000) - ->and($deserializedBasket->items()[$productIdStr]->discountRate->basisPoints())->toBe(1000); - }); - - it('hydrates the discount rate from the legacy float ratio stored in older sessions', function (float $legacyRatio, int $expectedBasisPoints) { - // GIVEN - $serializer = new BasketSerializer(); - $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); - $data = [ - 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), - 'items' => [ - [ - 'id' => $productIdStr, - 'name' => 'Test', - 'qty' => 1, - 'unitPriceHt' => ['amount' => 1000, 'currency' => 'EUR'], - 'unitDiscount' => ['amount' => 100, 'currency' => 'EUR'], - 'taxRate' => TaxRate::TVA_20->value, - 'weightGrams' => 500, - 'orderUnit' => OrderUnit::PCE->value, - 'slug' => 'test', - 'weightVariable' => false, - 'discountRate' => $legacyRatio, - 'priceKgTtc' => ['amount' => 2000, 'currency' => 'EUR'], - ], - ], - ]; - - // WHEN - $basket = $serializer->fromArray($data); - - // THEN - expect($basket->items()[$productIdStr]->discountRate->basisPoints())->toBe($expectedBasisPoints); - })->with([ - 'regular ratio' => [0.15, 1500], - 'no discount' => [0.0, 0], - 'out of range value is clamped' => [20.0, 10000], - ]); - - it('throws exception if currency is missing during deserialization', function () { - // GIVEN - $serializer = new BasketSerializer(); - $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); - $data = [ - 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), - 'items' => [ - [ - 'id' => $productIdStr, - 'name' => 'Test', - 'qty' => 1, - 'unitPriceHt' => ['amount' => 1000, 'currency' => ''], - 'unitDiscount' => ['amount' => 100, 'currency' => 'EUR'], - 'taxRate' => TaxRate::TVA_20->value, - 'weightGrams' => 500, - 'orderUnit' => OrderUnit::PCE->value, - 'slug' => 'test', - 'weightVariable' => false, - 'priceKgTtc' => ['amount' => 2000, 'currency' => 'EUR'], - ], - ], - ]; - - // WHEN - $action = fn () => $serializer->fromArray($data); - - // THEN - expect($action)->toThrow( - \DomainException::class, - 'Currency is required for unitPriceHt of item with id ' . $productIdStr - ); - }); - - it('throws exception if currency is missing for unitDiscount', function () { - // GIVEN - $serializer = new BasketSerializer(); - $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); - $data = [ - 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), - 'items' => [ - [ - 'id' => $productIdStr, - 'name' => 'Test', - 'qty' => 1, - 'unitPriceHt' => ['amount' => 1000, 'currency' => 'EUR'], - 'unitDiscount' => ['amount' => 100, 'currency' => ''], - 'taxRate' => TaxRate::TVA_20->value, - 'weightGrams' => 500, - 'orderUnit' => OrderUnit::PCE->value, - 'slug' => 'test', - 'weightVariable' => false, - 'priceKgTtc' => ['amount' => 2000, 'currency' => 'EUR'], - ], - ], - ]; - - // WHEN - $action = fn () => $serializer->fromArray($data); - - // THEN - expect($action)->toThrow( - \DomainException::class, - 'Currency is required for unitDiscount of item with id ' . $productIdStr - ); - }); - - it('throws exception if currency is missing for priceKgTtc', function () { - // GIVEN - $serializer = new BasketSerializer(); - $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); - $data = [ - 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), - 'items' => [ - [ - 'id' => $productIdStr, - 'name' => 'Test', - 'qty' => 1, - 'unitPriceHt' => ['amount' => 1000, 'currency' => 'EUR'], - 'unitDiscount' => ['amount' => 100, 'currency' => 'EUR'], - 'taxRate' => TaxRate::TVA_20->value, - 'weightGrams' => 500, - 'orderUnit' => OrderUnit::PCE->value, - 'slug' => 'test', - 'weightVariable' => false, - 'priceKgTtc' => ['amount' => 2000, 'currency' => ''], - ], - ], - ]; - - // WHEN - $action = fn () => $serializer->fromArray($data); - - // THEN - expect($action)->toThrow( - \DomainException::class, - 'Currency is required for priceKgTtc of item with id ' . $productIdStr - ); - }); + // THEN + expect($array['id'])->toBe($basketIdStr) + ->and($array['items'][0]['id'])->toBe($productIdStr) + ->and($array['items'][0]['name'])->toBe('Product 1') + ->and($array['items'][0]['taxRate'])->toBe(TaxRate::TVA_20->value) + ->and($deserializedBasket->id->value->toString())->toBe($basketIdStr) + ->and($deserializedBasket->items())->toHaveCount(1) + ->and($deserializedBasket->items()[$productIdStr]->name)->toBe('Product 1') + ->and($deserializedBasket->items()[$productIdStr]->weightVariable)->toBeTrue() + ->and($deserializedBasket->items()[$productIdStr]->options)->toBe(['color' => 'red']) + ->and($array['items'][0]['discountRateBp'])->toBe(1000) + ->and($deserializedBasket->items()[$productIdStr]->discountRate->basisPoints())->toBe(1000); +}); + +it('hydrates the discount rate from the legacy float ratio stored in older sessions', function (float $legacyRatio, int $expectedBasisPoints) { + // GIVEN + $serializer = new BasketSerializer(); + $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); + $data = [ + 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), + 'items' => [ + [ + 'id' => $productIdStr, + 'name' => 'Test', + 'qty' => 1, + 'unitPriceHt' => ['amount' => 1000, 'currency' => 'EUR'], + 'unitDiscount' => ['amount' => 100, 'currency' => 'EUR'], + 'taxRate' => TaxRate::TVA_20->value, + 'weightGrams' => 500, + 'orderUnit' => OrderUnit::PCE->value, + 'slug' => 'test', + 'weightVariable' => false, + 'discountRate' => $legacyRatio, + 'priceKgTtc' => ['amount' => 2000, 'currency' => 'EUR'], + ], + ], + ]; + + // WHEN + $basket = $serializer->fromArray($data); + + // THEN + expect($basket->items()[$productIdStr]->discountRate->basisPoints())->toBe($expectedBasisPoints); +})->with([ + 'regular ratio' => [0.15, 1500], + 'no discount' => [0.0, 0], + 'out of range value is clamped' => [20.0, 10000], +]); + +it('throws exception if currency is missing during deserialization', function () { + // GIVEN + $serializer = new BasketSerializer(); + $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); + $data = [ + 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), + 'items' => [ + [ + 'id' => $productIdStr, + 'name' => 'Test', + 'qty' => 1, + 'unitPriceHt' => ['amount' => 1000, 'currency' => ''], + 'unitDiscount' => ['amount' => 100, 'currency' => 'EUR'], + 'taxRate' => TaxRate::TVA_20->value, + 'weightGrams' => 500, + 'orderUnit' => OrderUnit::PCE->value, + 'slug' => 'test', + 'weightVariable' => false, + 'priceKgTtc' => ['amount' => 2000, 'currency' => 'EUR'], + ], + ], + ]; + + // WHEN + $action = fn () => $serializer->fromArray($data); + + // THEN + expect($action)->toThrow( + \DomainException::class, + 'Currency is required for unitPriceHt of item with id ' . $productIdStr + ); +}); + +it('throws exception if currency is missing for unitDiscount', function () { + // GIVEN + $serializer = new BasketSerializer(); + $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); + $data = [ + 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), + 'items' => [ + [ + 'id' => $productIdStr, + 'name' => 'Test', + 'qty' => 1, + 'unitPriceHt' => ['amount' => 1000, 'currency' => 'EUR'], + 'unitDiscount' => ['amount' => 100, 'currency' => ''], + 'taxRate' => TaxRate::TVA_20->value, + 'weightGrams' => 500, + 'orderUnit' => OrderUnit::PCE->value, + 'slug' => 'test', + 'weightVariable' => false, + 'priceKgTtc' => ['amount' => 2000, 'currency' => 'EUR'], + ], + ], + ]; + + // WHEN + $action = fn () => $serializer->fromArray($data); + + // THEN + expect($action)->toThrow( + \DomainException::class, + 'Currency is required for unitDiscount of item with id ' . $productIdStr + ); +}); + +it('throws exception if currency is missing for priceKgTtc', function () { + // GIVEN + $serializer = new BasketSerializer(); + $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); + $data = [ + 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), + 'items' => [ + [ + 'id' => $productIdStr, + 'name' => 'Test', + 'qty' => 1, + 'unitPriceHt' => ['amount' => 1000, 'currency' => 'EUR'], + 'unitDiscount' => ['amount' => 100, 'currency' => 'EUR'], + 'taxRate' => TaxRate::TVA_20->value, + 'weightGrams' => 500, + 'orderUnit' => OrderUnit::PCE->value, + 'slug' => 'test', + 'weightVariable' => false, + 'priceKgTtc' => ['amount' => 2000, 'currency' => ''], + ], + ], + ]; + + // WHEN + $action = fn () => $serializer->fromArray($data); + + // THEN + expect($action)->toThrow( + \DomainException::class, + 'Currency is required for priceKgTtc of item with id ' . $productIdStr + ); }); From 08c9028f915c8529191324be83c46331f72b48f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 16:26:51 +0100 Subject: [PATCH 148/183] test: update tests to use Assert for type checking - Refactored tests to utilize Webmozart Assert for type assertions. - Improved clarity and consistency in test expectations across multiple test files. - Ensured that all relevant tests now check for expected types and values. --- ...licHolydaysOnShopsPickupExceptionsTest.php | 28 +++++++++---- .../App/Console/Commands/UserCreateTest.php | 10 ++++- .../Bo/EmployeeSyncFeatureTest.php | 2 + .../Bo/PickupExceptionsControllerTest.php | 2 + .../Bo/ProductIncosControllerTest.php | 2 + .../Controllers/Bo/ProductsControllerTest.php | 10 +++-- .../Controllers/Bo/RangesControllerTest.php | 2 +- .../Controllers/Bo/ShopsControllerTest.php | 2 + .../Controllers/Bo/SlidesControllerTest.php | 11 ++++- .../Fo/Auth/LoginControllerTest.php | 3 +- .../Fo/Auth/RegisterControllerTest.php | 22 ++++++---- .../Fo/Customers/OrderControllerTest.php | 10 +++-- .../Fo/Pages/ContactControllerTest.php | 3 +- .../Fo/Pages/HomeControllerTest.php | 7 ++-- .../Fo/ProductCharacterizationTest.php | 26 ++++++++++-- .../Controllers/Fo/TunnelControllerTest.php | 41 ++++++++++--------- .../EnsureCustomerEmailIsVerifiedTest.php | 3 +- .../App/Http/Middleware/TrustProxiesTest.php | 3 ++ ...opsPickupExceptionsUsingApiForYearTest.php | 10 ++++- .../App/Providers/AuthServiceProviderTest.php | 4 ++ .../Feature/App/Providers/DateMacrosTest.php | 18 ++++++-- 21 files changed, 153 insertions(+), 66 deletions(-) diff --git a/tests/Feature/App/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptionsTest.php b/tests/Feature/App/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptionsTest.php index 63b4dfc2..51910ba1 100644 --- a/tests/Feature/App/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptionsTest.php +++ b/tests/Feature/App/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptionsTest.php @@ -7,6 +7,8 @@ namespace Tests\Feature\App\Console\Commands; use App\Jobs\UpsertShopsPickupExceptionsUsingApiForYear; use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Date; +use Illuminate\Testing\PendingCommand; +use Webmozart\Assert\Assert; afterEach(function (): void { Date::setTestNow(); @@ -19,9 +21,11 @@ it('dispatches the job for next year when year argument is omitted', function () Bus::fake(); // WHEN - $this->artisan('uwil:upsert-shops-hollydays') - // THEN - ->assertSuccessful(); + $command = $this->artisan('uwil:upsert-shops-hollydays'); + Assert::isInstanceOf($command, PendingCommand::class); + + // THEN + $command->assertSuccessful()->execute(); Bus::assertDispatched(UpsertShopsPickupExceptionsUsingApiForYear::class); }); @@ -32,9 +36,11 @@ it('dispatches the job for the specified numeric year', function (): void { Bus::fake(); // WHEN - $this->artisan('uwil:upsert-shops-hollydays', ['year' => '2027']) - // THEN - ->assertSuccessful(); + $command = $this->artisan('uwil:upsert-shops-hollydays', ['year' => '2027']); + Assert::isInstanceOf($command, PendingCommand::class); + + // THEN + $command->assertSuccessful()->execute(); Bus::assertDispatched(UpsertShopsPickupExceptionsUsingApiForYear::class); }); @@ -45,10 +51,14 @@ it('fails when year argument is not numeric', function (): void { Bus::fake(); // WHEN - $this->artisan('uwil:upsert-shops-hollydays', ['year' => 'abc']) - // THEN + $command = $this->artisan('uwil:upsert-shops-hollydays', ['year' => 'abc']); + Assert::isInstanceOf($command, PendingCommand::class); + + // THEN + $command ->expectsOutput('The year must be a number') - ->assertFailed(); + ->assertFailed() + ->execute(); Bus::assertNotDispatched(UpsertShopsPickupExceptionsUsingApiForYear::class); }); diff --git a/tests/Feature/App/Console/Commands/UserCreateTest.php b/tests/Feature/App/Console/Commands/UserCreateTest.php index 415ba285..d130bfae 100644 --- a/tests/Feature/App/Console/Commands/UserCreateTest.php +++ b/tests/Feature/App/Console/Commands/UserCreateTest.php @@ -7,6 +7,8 @@ namespace Tests\Feature\App\Console\Commands; use App\Models\User; use Domain\Enums\UserRole; use Illuminate\Support\Facades\Hash; +use Illuminate\Testing\PendingCommand; +use Webmozart\Assert\Assert; it('creates an admin user via uwil:user:create command using Executor', function (): void { /** @var \Tests\TestCase $this */ @@ -14,7 +16,10 @@ it('creates an admin user via uwil:user:create command using Executor', function $roleChoice = UserRole::Admin->value() . ' : ' . UserRole::Admin->label(); // WHEN / THEN - $this->artisan('uwil:user:create') + $command = $this->artisan('uwil:user:create'); + Assert::isInstanceOf($command, PendingCommand::class); + + $command ->expectsQuestion('What is the firstname?', 'Alice') ->expectsQuestion('What is the lastname?', 'Martin') ->expectsQuestion('What is the email?', 'alice.martin@ldc.fr') @@ -22,7 +27,8 @@ it('creates an admin user via uwil:user:create command using Executor', function ->expectsQuestion('Confirm : What is the password?', 'Str0ng!Password') ->expectsQuestion('What is the role ?', $roleChoice) ->expectsOutput('User created.') - ->assertSuccessful(); + ->assertSuccessful() + ->execute(); $user = User::query()->where('email', 'alice.martin@ldc.fr')->first(); expect($user)->not->toBeNull() diff --git a/tests/Feature/App/Http/Controllers/Bo/EmployeeSyncFeatureTest.php b/tests/Feature/App/Http/Controllers/Bo/EmployeeSyncFeatureTest.php index 607d22e9..70fa5cf2 100644 --- a/tests/Feature/App/Http/Controllers/Bo/EmployeeSyncFeatureTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/EmployeeSyncFeatureTest.php @@ -19,6 +19,7 @@ use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Contracts\Cache\Repository as CacheRepository; use Psr\Log\NullLogger; +use Webmozart\Assert\Assert; describe('Employee Sync Feature E2E', function (): void { it('configures sites in back office and synchronizes employees from Arcadia API into database', function (): void { @@ -72,6 +73,7 @@ describe('Employee Sync Feature E2E', function (): void { // THEN // Employee exists in database with all attributes populated $employee = Employee::query()->where('matricule', '7654321')->first(); + Assert::notNull($employee); expect($employee)->not->toBeNull() ->and($employee->nom)->toBe('Martin') ->and($employee->prenom)->toBe('Alice') diff --git a/tests/Feature/App/Http/Controllers/Bo/PickupExceptionsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/PickupExceptionsControllerTest.php index cf77ddc2..32f2c074 100644 --- a/tests/Feature/App/Http/Controllers/Bo/PickupExceptionsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/PickupExceptionsControllerTest.php @@ -10,6 +10,7 @@ use App\Models\User; use Domain\Enums\RepeatFrequency; use Domain\Enums\UserRole; use Illuminate\Support\Facades\Gate; +use Webmozart\Assert\Assert; use function Pest\Laravel\from; use function Pest\Laravel\get; @@ -59,6 +60,7 @@ describe('PickupExceptionsController', function () { // THEN $pickupException = PickupException::query()->where('label', 'Fête du Travail')->first(); + Assert::notNull($pickupException); expect($pickupException)->not->toBeNull() ->and($pickupException->repeatable)->toBeTrue() ->and($pickupException->repeat_frequency)->toBe(RepeatFrequency::YEARLY); diff --git a/tests/Feature/App/Http/Controllers/Bo/ProductIncosControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/ProductIncosControllerTest.php index ae06fdb9..2335788b 100644 --- a/tests/Feature/App/Http/Controllers/Bo/ProductIncosControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/ProductIncosControllerTest.php @@ -22,6 +22,7 @@ use Domain\Enums\Units\OrderUnit; use Domain\Enums\UserRole; use Domain\Models\ValueObjects\NutritionalValues; use Money\Money; +use Webmozart\Assert\Assert; describe('ProductIncosController', function () { beforeEach(function () { @@ -206,6 +207,7 @@ describe('ProductIncosController', function () { // THEN $inco = ProductInco::query()->where('product_id', $this->product->id)->first(); + Assert::notNull($inco); expect($inco)->not->toBeNull() ->and($inco->no_art)->toBe(27996) ->and($inco->nutriscore)->toBe(Nutriscore::A) diff --git a/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php index b34e12ef..a392a759 100644 --- a/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php @@ -24,6 +24,7 @@ use Domain\Models\ValueObjects\DiscountValue; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Gate; use Money\Money; +use Webmozart\Assert\Assert; use function Pest\Laravel\from; use function Pest\Laravel\patch; @@ -182,8 +183,8 @@ describe('ProductsController', function () { 'height' => StoreProductRequest::PICTURE_LARGE_HEIGHT, ]); - $response->assertSee(json_encode($expectedPictureHelper), false); - $response->assertSee(json_encode($expectedLargePictureHelper), false); + $response->assertSee(json_encode($expectedPictureHelper, JSON_THROW_ON_ERROR), false); + $response->assertSee(json_encode($expectedLargePictureHelper, JSON_THROW_ON_ERROR), false); }); it('renders empty string instead of null for ckeditor text when old input is null', function () { @@ -248,6 +249,7 @@ describe('ProductsController', function () { $response->assertSessionHasNoErrors(); expect($response->status())->toBe(302); $product = Product::query()->where('name', 'New Product')->first(); + Assert::notNull($product); expect($product)->not->toBeNull(); $response->assertRedirect("/bo/products/{$product->slug}/edit"); }); @@ -316,8 +318,8 @@ describe('ProductsController', function () { ->toContain('"value":[{"id":' . $tag->id) ->toMatch('/id="product-weight"[^>]+value="1\.5"/') ->toContain('id="orderable-start" name="orderable_start" type="datetime-local"') - ->toContain('value="' . Date::toLocalInput($orderableStart) . '"') - ->toContain('value="' . Date::toLocalInput($orderableEnd) . '"'); + ->toContain('value="' . Carbon::parse($orderableStart)->setTimezone('Europe/Paris')->format('Y-m-d\TH:i') . '"') + ->toContain('value="' . Carbon::parse($orderableEnd)->setTimezone('Europe/Paris')->format('Y-m-d\TH:i') . '"'); }); it('can update a product', function () { diff --git a/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php index 12f62b3c..4c291084 100644 --- a/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php @@ -58,7 +58,7 @@ describe('RangesController', function () { 'height' => StoreRangeRequest::PICTURE_HEIGHT, ]); - $response->assertSee(json_encode($expectedHelper), false); + $response->assertSee(json_encode($expectedHelper, JSON_THROW_ON_ERROR), false); }); it('can store a range', function () { diff --git a/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php index 7a96d708..c0365671 100644 --- a/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php @@ -10,6 +10,7 @@ use App\Models\Shop; use App\Models\User; use Domain\Enums\UserRole; use Illuminate\Support\Facades\Gate; +use Webmozart\Assert\Assert; use function Pest\Laravel\from; use function Pest\Laravel\get; @@ -93,6 +94,7 @@ describe('ShopsController', function () { // THEN $shop = Shop::query()->where('name', 'New Shop')->first(); + Assert::notNull($shop); expect($shop)->not->toBeNull(); $response->assertRedirect("/bo/shops/{$shop->id}/edit"); }); diff --git a/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php index 47e4059c..2207c8e2 100644 --- a/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php @@ -9,7 +9,9 @@ use App\Http\Requests\Bo\Slides\StoreSlideRequest; use App\Models\Slide; use App\Models\User; use Domain\Enums\UserRole; +use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Support\Facades\Gate; +use Webmozart\Assert\Assert; use function Pest\Laravel\from; use function Pest\Laravel\get; @@ -35,7 +37,11 @@ describe('SlidesController', function (): void { // THEN expect($response->status())->toBe(200); $response->assertViewIs('bo.slides.index'); - $response->assertViewHas('slides', fn ($slides) => $slides->items()[0] instanceof SlideDto); + $response->assertViewHas('slides', static function (mixed $slides): bool { + Assert::isInstanceOf($slides, LengthAwarePaginator::class); + + return $slides->items()[0] instanceof SlideDto; + }); $response->assertSee(__('Visible')); }); @@ -58,7 +64,7 @@ describe('SlidesController', function (): void { 'height' => StoreSlideRequest::PICTURE_HEIGHT, ]); - $response->assertSee(json_encode($expectedHelper), false); + $response->assertSee(json_encode($expectedHelper, JSON_THROW_ON_ERROR), false); }); it('can store a slide', function (): void { @@ -81,6 +87,7 @@ describe('SlidesController', function (): void { // THEN $slide = Slide::query()->where('title', 'New Slide Title')->first(); + Assert::notNull($slide); expect($slide)->not->toBeNull(); $response->assertRedirect("/bo/slides/{$slide->id}/edit"); }); diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php index 3ad1d4fb..362b5d67 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php @@ -28,6 +28,7 @@ use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\View; use Illuminate\Support\Str; +use Ramsey\Uuid\Uuid; use Shared\ValueObjects\CrmHashcode; describe('LoginController', function () { @@ -118,7 +119,7 @@ describe('LoginController', function () { Cache::flush(); $user = \Mockery::mock(Customer::class)->makePartial(); $user->shouldReceive('getAuthIdentifier')->andReturn(1); - $user->hashcode = 'dummy_hashcode'; + $user->hashcode = new CrmHashcode(Uuid::uuid4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php index 5367162b..a4fd68bd 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php @@ -20,12 +20,13 @@ use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; -use Illuminate\Contracts\View\View as ViewContract; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\View; +use Illuminate\Support\ViewErrorBag; use Ramsey\Uuid\Uuid; use Shared\ValueObjects\CrmHashcode; +use Webmozart\Assert\Assert; describe('RegisterController', function () { it('can access get /auth/inscription', function () { @@ -138,8 +139,8 @@ describe('RegisterController', function () { $result = $controller->submitForm($request, $action); // THEN - expect($result)->toBeInstanceOf(ViewContract::class) - ->and($result->name())->toBe('fo.auth.verify'); + Assert::isInstanceOf($result, \Illuminate\View\View::class); + expect($result->name())->toBe('fo.auth.verify'); }); it('redirects back with matricule error when RegisterCustomer returns EMPLOYEE_ALREADY_REGISTERED', function (): void { @@ -180,9 +181,10 @@ describe('RegisterController', function () { $result = $controller->submitForm($request, $action); // THEN - expect($result)->toBeInstanceOf(RedirectResponse::class); + Assert::isInstanceOf($result, RedirectResponse::class); $errors = $result->getSession()?->get('errors'); - expect($errors?->get('matricule'))->toBe([__('This employee already has an account.')]); + Assert::isInstanceOf($errors, ViewErrorBag::class); + expect($errors->get('matricule'))->toBe([__('This employee already has an account.')]); }); it('redirects back with matricule error when RegisterCustomer returns LOCK_TIMEOUT', function (): void { @@ -223,9 +225,10 @@ describe('RegisterController', function () { $result = $controller->submitForm($request, $action); // THEN - expect($result)->toBeInstanceOf(RedirectResponse::class); + Assert::isInstanceOf($result, RedirectResponse::class); $errors = $result->getSession()?->get('errors'); - expect($errors?->get('matricule'))->toBe([__('Registration is already in progress. Please try again in a moment.')]); + Assert::isInstanceOf($errors, ViewErrorBag::class); + expect($errors->get('matricule'))->toBe([__('Registration is already in progress. Please try again in a moment.')]); }); it('redirects back with matricule error when RegisterCustomer returns EMPLOYEE_INACTIVE', function (): void { @@ -266,8 +269,9 @@ describe('RegisterController', function () { $result = $controller->submitForm($request, $action); // THEN - expect($result)->toBeInstanceOf(RedirectResponse::class); + Assert::isInstanceOf($result, RedirectResponse::class); $errors = $result->getSession()?->get('errors'); - expect($errors?->get('matricule'))->toBe([__('This employee account is no longer active.')]); + Assert::isInstanceOf($errors, ViewErrorBag::class); + expect($errors->get('matricule'))->toBe([__('This employee account is no longer active.')]); }); }); diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php index ce6063f9..1729e719 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php @@ -177,9 +177,13 @@ describe('OrderController', function () { expect($response->status())->toBe(200); $response->assertViewIs('fo.customer.orders.index'); $response->assertViewHas('orders', function ($orders) use ($ref): bool { - return $orders instanceof LengthAwarePaginator - && $orders->total() === 1 - && (string) $orders->first()->reference === $ref; + if (! $orders instanceof LengthAwarePaginator || $orders->total() !== 1) { + return false; + } + + $first = $orders->items()[0] ?? null; + + return is_object($first) && property_exists($first, 'reference') && ($first->reference instanceof \Stringable || is_string($first->reference)) && (string) $first->reference === $ref; }); }); diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php index 2dad6ca4..e5338af3 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php @@ -16,6 +16,7 @@ use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\View; +use Mockery\MockInterface; use Ramsey\Uuid\Uuid; use Uwil\Storage\Contracts\StorageService; use Uwil\Storage\Lib\ValueObjects\DiskName; @@ -103,7 +104,7 @@ describe('ContactController', function (): void { // GIVEN Queue::fake(); $file = UploadedFile::fake()->create('piece.pdf', 100, 'application/pdf'); - $this->mock(StorageService::class, function ($mock): void { + $this->mock(StorageService::class, function (MockInterface $mock): void { $mock->shouldReceive('storeUploadedOntoDisk') ->once() ->with( diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php index 4bc4f93e..4fe02123 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php @@ -22,6 +22,7 @@ use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\View; use Money\Money; use Ramsey\Uuid\Uuid; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('HomeController', function () { beforeEach(function (): void { @@ -65,7 +66,7 @@ describe('HomeController', function () { $range = new Range(); $range->name = 'Boucherie'; $range->slug = 'boucherie'; - $range->picture = 'ranges/boucherie.jpg'; + $range->picture = new StorageFilePath('ranges/boucherie.jpg'); $range->picture_alt = 'Boucherie'; $range->picture_title = 'Boucherie'; $range->status = true; @@ -154,7 +155,7 @@ describe('HomeController', function () { $range = new Range(); $range->name = 'Boucherie'; $range->slug = 'boucherie'; - $range->picture = 'ranges/boucherie.jpg'; + $range->picture = new StorageFilePath('ranges/boucherie.jpg'); $range->picture_alt = 'Boucherie'; $range->picture_title = 'Boucherie'; $range->status = true; @@ -237,7 +238,7 @@ describe('HomeController', function () { $range = new Range(); $range->name = 'Volaille'; $range->slug = 'volaille'; - $range->picture = 'ranges/volaille.jpg'; + $range->picture = new StorageFilePath('ranges/volaille.jpg'); $range->picture_alt = 'Volaille'; $range->picture_title = 'Volaille'; $range->status = true; diff --git a/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php b/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php index a7742dcb..2b6cb007 100644 --- a/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php @@ -31,6 +31,7 @@ use Money\Money; use Ramsey\Uuid\Uuid; use Shared\ValueObjects\CrmHashcode; use Tests\TestCase; +use Webmozart\Assert\Assert; use function Pest\Laravel\actingAs; use function Pest\Laravel\get; @@ -129,6 +130,7 @@ describe('FO product pricing & orderability (characterization)', function (): vo // THEN $response->assertOk(); $row = $response->json('data.0'); + Assert::isArray($row); expect($row['priceTtc'])->toBeNull() ->and($row['priceKgTtc'])->toBeNull() ->and($row['discountedPriceTtc'])->toBeNull(); @@ -147,8 +149,11 @@ describe('FO product pricing & orderability (characterization)', function (): vo // THEN $response->assertOk(); $row = $response->json('data.0'); - expect($row['priceTtc'])->toHaveKeys(['amount', 'currency', 'formatted']) - ->and($row['priceTtc']['currency'])->toBe('EUR') + Assert::isArray($row); + $priceTtc = $row['priceTtc']; + Assert::isArray($priceTtc); + expect($priceTtc)->toHaveKeys(['amount', 'currency', 'formatted']) + ->and($priceTtc['currency'])->toBe('EUR') ->and($row['priceKgTtc'])->not->toBeNull() ->and($row['discountedPriceTtc'])->not->toBeNull(); }); @@ -165,7 +170,14 @@ describe('FO product pricing & orderability (characterization)', function (): vo // THEN $row = $response->json('data.0'); - expect((int) $row['discountedPriceTtc']['amount'])->toBeLessThan((int) $row['priceTtc']['amount']) + Assert::isArray($row); + $discountedPriceTtc = $row['discountedPriceTtc']; + $priceTtc = $row['priceTtc']; + Assert::isArray($discountedPriceTtc); + Assert::isArray($priceTtc); + Assert::numeric($discountedPriceTtc['amount']); + Assert::numeric($priceTtc['amount']); + expect((int) $discountedPriceTtc['amount'])->toBeLessThan((int) $priceTtc['amount']) ->and($row['showStrippedPrice'])->toBeTrue(); }); @@ -181,7 +193,12 @@ describe('FO product pricing & orderability (characterization)', function (): vo // THEN $row = $response->json('data.0'); - expect($row['discountedPriceTtc']['amount'])->toBe($row['priceTtc']['amount']) + Assert::isArray($row); + $discountedPriceTtc = $row['discountedPriceTtc']; + $priceTtc = $row['priceTtc']; + Assert::isArray($discountedPriceTtc); + Assert::isArray($priceTtc); + expect($discountedPriceTtc['amount'])->toBe($priceTtc['amount']) ->and($row['showStrippedPrice'])->toBeFalse(); }); @@ -197,6 +214,7 @@ describe('FO product pricing & orderability (characterization)', function (): vo // THEN $row = $response->json('data.0'); + Assert::isArray($row); expect($row['is_orderable'])->toBeFalse() ->and($row['can_add_to_basket'])->toBeFalse(); }); diff --git a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php index c71d7b3e..3bdc7869 100644 --- a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php @@ -52,6 +52,7 @@ use Domain\Services\OrderTunnelService; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\View; +use Mockery\MockInterface; use Money\Money; use Ramsey\Uuid\Uuid; use Sentry\State\HubInterface; @@ -200,7 +201,7 @@ describe('TunnelController', function (): void { Gate::before(fn () => true); $basket = new Basket(new BasketId(Uuid::uuid7())); - $this->mock(Executor::class, function ($mock) use ($basket): void { + $this->mock(Executor::class, function (MockInterface $mock) use ($basket): void { $mock->shouldReceive('execute') ->once() ->andReturn(new GetBasketSummaryQueryOutput( @@ -241,7 +242,7 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); - $this->mock(Executor::class, function ($mock): void { + $this->mock(Executor::class, function (MockInterface $mock): void { $mock->shouldReceive('execute') ->once(); }); @@ -287,7 +288,7 @@ describe('TunnelController', function (): void { default: true, ); - $this->mock(Executor::class, function ($mock) use ($shopDto): void { + $this->mock(Executor::class, function (MockInterface $mock) use ($shopDto): void { $mock->shouldReceive('execute') ->once() ->andReturn(new GetPickTimeSlotQueryOutput( @@ -343,19 +344,19 @@ describe('TunnelController', function (): void { site: new ShopperSiteCode('SITE'), service: new ShopperServiceCode('101'), ); - $this->mock(ShopperRepository::class, function ($mock) use ($shopper): void { + $this->mock(ShopperRepository::class, function (MockInterface $mock) use ($shopper): void { $mock->shouldReceive('getByIdOrFail')->andReturn($shopper); }); $basket = new Basket(new BasketId(Uuid::uuid7())); $builder = \Mockery::mock(OrderBuilderWithBasket::class); $builder->shouldReceive('getBasket')->andReturn($basket); - $this->mock(OrderTunnelService::class, function ($mock) use ($builder): void { + $this->mock(OrderTunnelService::class, function (MockInterface $mock) use ($builder): void { $mock->shouldReceive('getBuilderFromBasketOrFail')->andReturn($builder); $mock->shouldReceive('assertBasketWeeklyAmountWithinLimitFor'); }); $slot = new PickupTimeSlot(now(), new \DateInterval('PT1H')); - $this->mock(Executor::class, function ($mock) use ($slot): void { + $this->mock(Executor::class, function (MockInterface $mock) use ($slot): void { $mock->shouldReceive('execute') ->once() ->andReturn(ApplyPickTimeSlotOutput::matched($slot)); @@ -404,18 +405,18 @@ describe('TunnelController', function (): void { site: new ShopperSiteCode('SITE'), service: new ShopperServiceCode('101'), ); - $this->mock(ShopperRepository::class, function ($mock) use ($shopper): void { + $this->mock(ShopperRepository::class, function (MockInterface $mock) use ($shopper): void { $mock->shouldReceive('getByIdOrFail')->andReturn($shopper); }); $basket = new Basket(new BasketId(Uuid::uuid7())); $builder = \Mockery::mock(OrderBuilderWithBasket::class); $builder->shouldReceive('getBasket')->andReturn($basket); - $this->mock(OrderTunnelService::class, function ($mock) use ($builder): void { + $this->mock(OrderTunnelService::class, function (MockInterface $mock) use ($builder): void { $mock->shouldReceive('getBuilderFromBasketOrFail')->andReturn($builder); $mock->shouldReceive('assertBasketWeeklyAmountWithinLimitFor'); }); - $this->mock(Executor::class, function ($mock): void { + $this->mock(Executor::class, function (MockInterface $mock): void { $mock->shouldReceive('execute') ->once() ->andReturn(ApplyPickTimeSlotOutput::unavailable()); @@ -470,7 +471,7 @@ describe('TunnelController', function (): void { default: true, ); - $this->mock(Executor::class, function ($mock) use ($basket, $builder, $shopDto): void { + $this->mock(Executor::class, function (MockInterface $mock) use ($basket, $builder, $shopDto): void { $mock->shouldReceive('execute') ->once() ->andReturn(new GetOrderConfirmationQueryOutput( @@ -516,7 +517,7 @@ describe('TunnelController', function (): void { $orderId = new OrderId(Uuid::uuid7()); $orderReference = new OrderReference(Uuid::uuid7()); - $this->mock(Executor::class, function ($mock) use ($orderId, $orderReference): void { + $this->mock(Executor::class, function (MockInterface $mock) use ($orderId, $orderReference): void { $mock->shouldReceive('execute') ->once() ->with(\Mockery::type(PlacePendingOrder::class), \Mockery::type(PlacePendingOrderInput::class)) @@ -564,7 +565,7 @@ describe('TunnelController', function (): void { $orderId = new OrderId(Uuid::uuid7()); $orderReference = new OrderReference(Uuid::uuid7()); - $this->mock(Executor::class, function ($mock) use ($orderId, $orderReference): void { + $this->mock(Executor::class, function (MockInterface $mock) use ($orderId, $orderReference): void { $mock->shouldReceive('execute') ->once() ->with(\Mockery::type(PlacePendingOrder::class), \Mockery::type(PlacePendingOrderInput::class)) @@ -613,7 +614,7 @@ describe('TunnelController', function (): void { $orderId = new OrderId(Uuid::uuid7()); $orderReference = new OrderReference(Uuid::uuid7()); - $this->mock(Executor::class, function ($mock) use ($orderId, $orderReference): void { + $this->mock(Executor::class, function (MockInterface $mock) use ($orderId, $orderReference): void { $mock->shouldReceive('execute') ->once() ->with(\Mockery::type(PlacePendingOrder::class), \Mockery::type(PlacePendingOrderInput::class)) @@ -660,7 +661,7 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); - $this->mock(Executor::class, function ($mock): void { + $this->mock(Executor::class, function (MockInterface $mock): void { $mock->shouldReceive('execute') ->once() ->andReturn(PlacePendingOrderOutput::weeklyLimitExceeded( @@ -700,7 +701,7 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); - $this->mock(Executor::class, function ($mock): void { + $this->mock(Executor::class, function (MockInterface $mock): void { $mock->shouldReceive('execute') ->once() ->andReturn(PlacePendingOrderOutput::expiredTimeSlot('Invalid or unavailable time slot')); @@ -740,7 +741,7 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); - $this->mock(Executor::class, function ($mock): void { + $this->mock(Executor::class, function (MockInterface $mock): void { $mock->shouldReceive('execute') ->once() ->andReturn(PlacePendingOrderOutput::unorderableProduct( @@ -782,7 +783,7 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); - $this->mock(Executor::class, function ($mock): void { + $this->mock(Executor::class, function (MockInterface $mock): void { $mock->shouldReceive('execute') ->once() ->andReturn(PlacePendingOrderOutput::basketPriceChanged( @@ -824,7 +825,7 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); - $this->mock(Executor::class, function ($mock): void { + $this->mock(Executor::class, function (MockInterface $mock): void { $mock->shouldReceive('execute') ->once() ->andReturn(PlacePendingOrderOutput::lockTimeout()); @@ -862,7 +863,7 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); - $this->mock(Executor::class, function ($mock): void { + $this->mock(Executor::class, function (MockInterface $mock): void { $mock->shouldReceive('execute') ->once() ->andReturn(PlacePendingOrderOutput::inactiveShopper('Employee account is no longer active.')); @@ -972,7 +973,7 @@ describe('TunnelController', function (): void { ->with(\Mockery::type(RegateExportFailedException::class)); $this->app->instance(HubInterface::class, $sentryHub); - $this->mock(Executor::class, function ($mock): void { + $this->mock(Executor::class, function (MockInterface $mock): void { $mock->shouldReceive('execute') ->once() ->andThrow(new RegateExportFailedException('SMTP transport down')); diff --git a/tests/Feature/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php b/tests/Feature/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php index 6e4494d8..87cdc285 100644 --- a/tests/Feature/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php +++ b/tests/Feature/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php @@ -13,6 +13,7 @@ use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\URL; use Infrastructure\Adapters\Services\AppCustomerAuthService; use Symfony\Component\HttpKernel\Exception\HttpException; +use Webmozart\Assert\Assert; describe('EnsureCustomerEmailIsVerified', function () { it('redirects to fo.auth.verification.notice if customer is not verified', function () { @@ -35,7 +36,7 @@ describe('EnsureCustomerEmailIsVerified', function () { }); // THEN - expect($response)->toBeInstanceOf(RedirectResponse::class); + Assert::isInstanceOf($response, RedirectResponse::class); expect($response->getTargetUrl())->toBe('http://localhost/verification-notice'); }); diff --git a/tests/Feature/App/Http/Middleware/TrustProxiesTest.php b/tests/Feature/App/Http/Middleware/TrustProxiesTest.php index c39e6ab3..6a54572d 100644 --- a/tests/Feature/App/Http/Middleware/TrustProxiesTest.php +++ b/tests/Feature/App/Http/Middleware/TrustProxiesTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Middleware; use Illuminate\Http\Request; +use Webmozart\Assert\Assert; describe('TrustProxies and clientIp resolution', function (): void { it('resolves clientIp from valid X-Real-Ip header when present', function (): void { @@ -21,6 +22,7 @@ describe('TrustProxies and clientIp resolution', function (): void { $clientIp = $this->app->make('clientIp'); // THEN + Assert::string($clientIp); expect($clientIp)->toBe('203.0.113.42'); }); @@ -38,6 +40,7 @@ describe('TrustProxies and clientIp resolution', function (): void { $clientIp = $this->app->make('clientIp'); // THEN + Assert::string($clientIp); expect($clientIp)->toBe('198.51.100.25'); }); diff --git a/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php b/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php index 4610c005..742ba164 100644 --- a/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php +++ b/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php @@ -9,6 +9,7 @@ use App\Models\PickupException; use App\Models\Shop; use Domain\Enums\RepeatFrequency; use Illuminate\Support\Facades\Http; +use Webmozart\Assert\Assert; it('throws an exception if the year is before 2026', function (): void { // GIVEN @@ -38,13 +39,18 @@ it('upserts holidays from the api and syncs them to all shops', function (): voi expect(PickupException::query()->count())->toBe(2); $newYear = PickupException::query()->where('label', '1er janvier')->first(); + Assert::notNull($newYear); expect($newYear)->not->toBeNull() ->and($newYear->date->format('Y-m-d'))->toBe('2026-01-01') ->and($newYear->repeatable)->toBeTrue() ->and($newYear->repeat_frequency)->toBe(RepeatFrequency::YEARLY); - expect($shops->first()->pickupExceptions()->count())->toBe(2) - ->and($shops->last()->pickupExceptions()->count())->toBe(2); + $firstShop = $shops->first(); + $lastShop = $shops->last(); + Assert::notNull($firstShop); + Assert::notNull($lastShop); + expect($firstShop->pickupExceptions()->count())->toBe(2) + ->and($lastShop->pickupExceptions()->count())->toBe(2); }); it('updates existing pickup exceptions without creating duplicates', function (): void { diff --git a/tests/Feature/App/Providers/AuthServiceProviderTest.php b/tests/Feature/App/Providers/AuthServiceProviderTest.php index 668364de..51d39ad9 100644 --- a/tests/Feature/App/Providers/AuthServiceProviderTest.php +++ b/tests/Feature/App/Providers/AuthServiceProviderTest.php @@ -9,9 +9,11 @@ use Domain\Models\ValueObjects\Email; use Illuminate\Auth\Notifications\ResetPassword; use Illuminate\Auth\Notifications\VerifyEmail; use Illuminate\Http\Request; +use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\URL; use Illuminate\Support\Str; +use Webmozart\Assert\Assert; describe('AuthServiceProvider auth URL callbacks', function (): void { it('registers VerifyEmail URL callback during boot without instantiating AuthController', function (): void { @@ -26,6 +28,7 @@ describe('AuthServiceProvider auth URL callbacks', function (): void { // WHEN $mail = $notification->toMail($customer); + Assert::isInstanceOf($mail, MailMessage::class); /** @var string $actionUrl */ $actionUrl = $mail->actionUrl; $relativeUrl = (string) parse_url($actionUrl, \PHP_URL_PATH) . '?' . (string) parse_url($actionUrl, \PHP_URL_QUERY); @@ -49,6 +52,7 @@ describe('AuthServiceProvider auth URL callbacks', function (): void { // WHEN $mail = $notification->toMail($customer); + Assert::isInstanceOf($mail, MailMessage::class); /** @var string $actionUrl */ $actionUrl = $mail->actionUrl; $relativeUrl = (string) parse_url($actionUrl, \PHP_URL_PATH) . '?' . (string) parse_url($actionUrl, \PHP_URL_QUERY); diff --git a/tests/Feature/App/Providers/DateMacrosTest.php b/tests/Feature/App/Providers/DateMacrosTest.php index 8ef493b6..212b35b6 100644 --- a/tests/Feature/App/Providers/DateMacrosTest.php +++ b/tests/Feature/App/Providers/DateMacrosTest.php @@ -6,6 +6,7 @@ namespace Tests\Feature\App\Providers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Date; +use Webmozart\Assert\Assert; describe('AppServiceProvider Date macros', function (): void { it('uses valid client_timezone from request', function (): void { @@ -15,8 +16,12 @@ describe('AppServiceProvider Date macros', function (): void { $utcDate = new \DateTimeImmutable('2026-06-15 14:00:00', new \DateTimeZone('UTC')); // WHEN + /** @phpstan-ignore staticMethod.notFound */ $localInput = Date::toLocalInput($utcDate); - $forHumans = Date::forHumans($utcDate); + /** @phpstan-ignore staticMethod.notFound */ + $forHumans = Date::forHumans($utcDate); + Assert::string($localInput); + Assert::string($forHumans); // THEN expect($localInput)->toBe('2026-06-15T10:00') @@ -30,8 +35,12 @@ describe('AppServiceProvider Date macros', function (): void { $utcDate = new \DateTimeImmutable('2026-06-15 14:00:00', new \DateTimeZone('UTC')); // WHEN + /** @phpstan-ignore staticMethod.notFound */ $localInput = Date::toLocalInput($utcDate); - $forHumans = Date::forHumans($utcDate); + /** @phpstan-ignore staticMethod.notFound */ + $forHumans = Date::forHumans($utcDate); + Assert::string($localInput); + Assert::string($forHumans); // THEN expect($localInput)->toBe('2026-06-15T16:00') @@ -47,11 +56,12 @@ describe('AppServiceProvider Date macros', function (): void { $utcMidnight = Date::createFromFormat('!Y-m-d', '2026-05-08', 'UTC'); // WHEN + /** @phpstan-ignore staticMethod.notFound */ $formatted = Date::forHumansDate($utcMidnight); + Assert::string($formatted); // THEN - expect($formatted)->toBeString() - ->and($formatted)->toContain('08/05/2026') + expect($formatted)->toContain('08/05/2026') ->and($formatted)->not->toContain('à'); }); }); From 14fd20c30328415e4be06fb063e6c99e91fb4d8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 16:29:17 +0100 Subject: [PATCH 149/183] test(quality): resolve PHPStan level 10 errors in Feature tests and wrap long test lines --- .../Controllers/Bo/OrdersControllerTest.php | 90 +++++++++++++++-- .../Fo/Customers/OrderControllerTest.php | 23 ++++- .../EnsureCustomerEmailIsVerifiedTest.php | 4 +- .../Requests/Basket/AddBasketRequestTest.php | 24 ++++- .../Actions/Products/CreateProductTest.php | 10 +- .../Cqs/Actions/Ranges/CreateRangeTest.php | 10 +- .../Cqs/Actions/Ranges/UpdateRangeTest.php | 10 +- .../WithApp/App/Dto/OrderLineDtoTest.php | 9 +- .../Services/ActionExecutorServiceTest.php | 98 +++++++++---------- .../Services/OrderOwnershipServiceTest.php | 27 ++++- .../EloquentPickupExceptionRepositoryTest.php | 16 ++- .../Actions/Orders/PlacePendingOrderTest.php | 2 +- .../Events/AnOrderHasBeenPlacedTest.php | 18 +++- .../ValueObjects/OrderLineProductTest.php | 78 +++++++++++++-- 14 files changed, 332 insertions(+), 87 deletions(-) diff --git a/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php index 8173a078..efba6867 100644 --- a/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php @@ -60,7 +60,14 @@ describe('Bo\OrdersController', function (): void { 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(2500, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('1000101'), 'Alice', 'Smith', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('1000101'), + 'Alice', + 'Smith', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->toDateString(), ]); @@ -87,7 +94,14 @@ describe('Bo\OrdersController', function (): void { 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(2500, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule((string) (1000100 + $i)), 'Alice', 'Smith', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule((string) (1000100 + $i)), + 'Alice', + 'Smith', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->toDateString(), ]); @@ -117,7 +131,14 @@ describe('Bo\OrdersController', function (): void { 'reference' => $reference, 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(1500, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('1000102'), 'Bob', 'Jones', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('1000102'), + 'Bob', + 'Jones', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->toDateString(), ]); @@ -145,7 +166,14 @@ describe('Bo\OrdersController', function (): void { 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(1000, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('1000198'), 'Old', 'Order', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('1000198'), + 'Old', + 'Order', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->addDays(7)->toDateString(), ]); @@ -155,7 +183,14 @@ describe('Bo\OrdersController', function (): void { 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(2000, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('1000199'), 'New', 'Order', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('1000199'), + 'New', + 'Order', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->addDays(7)->toDateString(), ]); @@ -181,7 +216,14 @@ describe('Bo\OrdersController', function (): void { 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(3000, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('1000103'), 'Charlie', 'Brown', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('1000103'), + 'Charlie', + 'Brown', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->addDays(7)->toDateString(), ]); @@ -191,7 +233,14 @@ describe('Bo\OrdersController', function (): void { 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(4000, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('1000104'), 'Past', 'Order', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('1000104'), + 'Past', + 'Order', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->toDateString(), ]); @@ -241,7 +290,14 @@ describe('Bo\OrdersController', function (): void { 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(4000, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('1000999'), 'Jean', 'Dupont', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('1000999'), + 'Jean', + 'Dupont', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->toDateString(), ]); @@ -265,7 +321,14 @@ describe('Bo\OrdersController', function (): void { 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(2000, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('1000104'), 'David', 'Clark', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('1000104'), + 'David', + 'Clark', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->toDateString(), ]); @@ -304,7 +367,14 @@ describe('Bo\OrdersController', function (): void { 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::CANCELED->value, 'total' => new Money(2000, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('1000105'), 'Eve', 'Stone', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('1000105'), + 'Eve', + 'Stone', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->toDateString(), ]); diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php index 1729e719..0bbd1288 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php @@ -141,7 +141,14 @@ describe('OrderController', function () { 'reference' => $reference, 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(5000, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('8888001'), 'Jean', 'Dupont', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('8888001'), + 'Jean', + 'Dupont', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->toDateString(), ]); @@ -183,7 +190,10 @@ describe('OrderController', function () { $first = $orders->items()[0] ?? null; - return is_object($first) && property_exists($first, 'reference') && ($first->reference instanceof \Stringable || is_string($first->reference)) && (string) $first->reference === $ref; + return is_object($first) + && property_exists($first, 'reference') + && ($first->reference instanceof \Stringable || is_string($first->reference)) + && (string) $first->reference === $ref; }); }); @@ -228,7 +238,14 @@ describe('OrderController', function () { 'reference' => $reference, 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(5000, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('8888002'), 'Paul', 'Martin', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('8888002'), + 'Paul', + 'Martin', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->toDateString(), ]); diff --git a/tests/Feature/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php b/tests/Feature/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php index 87cdc285..7d76b095 100644 --- a/tests/Feature/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php +++ b/tests/Feature/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php @@ -28,7 +28,9 @@ describe('EnsureCustomerEmailIsVerified', function () { $request = Request::create('/some-url', 'GET'); URL::shouldReceive('route')->with('fo.auth.verification.notice')->andReturn('http://localhost/verification-notice'); - Redirect::shouldReceive('guest')->with('http://localhost/verification-notice')->andReturn(new RedirectResponse('http://localhost/verification-notice')); + Redirect::shouldReceive('guest') + ->with('http://localhost/verification-notice') + ->andReturn(new RedirectResponse('http://localhost/verification-notice')); // WHEN $response = $middleware->handle($request, function ($req) { diff --git a/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php b/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php index 3410854e..9f4dd9b1 100644 --- a/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php +++ b/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php @@ -42,7 +42,13 @@ function makeAddBasketRequest(): AddBasketRequest describe('AddBasketRequest', function () { it('authorizes when product exists and gate allows', function () { // GIVEN - $range = Range::query()->first() ?? Range::query()->forceCreate(['name' => 'Test', 'slug' => 'test', 'order' => 1, 'picture_alt' => '', 'picture_title' => '']); + $range = Range::query()->first() ?? Range::query()->forceCreate([ + 'name' => 'Test', + 'slug' => 'test', + 'order' => 1, + 'picture_alt' => '', + 'picture_title' => '', + ]); $product = Product::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'name' => 'Test', @@ -92,7 +98,13 @@ describe('AddBasketRequest', function () { it('does not authorize when gate denies', function () { // GIVEN - $range = Range::query()->first() ?? Range::query()->forceCreate(['name' => 'Test', 'slug' => 'test', 'order' => 1, 'picture_alt' => '', 'picture_title' => '']); + $range = Range::query()->first() ?? Range::query()->forceCreate([ + 'name' => 'Test', + 'slug' => 'test', + 'order' => 1, + 'picture_alt' => '', + 'picture_title' => '', + ]); $product = Product::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'name' => 'Test', @@ -130,7 +142,13 @@ describe('AddBasketRequest', function () { it('validates correct rules', function () { // GIVEN - $range = Range::query()->first() ?? Range::query()->forceCreate(['name' => 'Test', 'slug' => 'test', 'order' => 1, 'picture_alt' => '', 'picture_title' => '']); + $range = Range::query()->first() ?? Range::query()->forceCreate([ + 'name' => 'Test', + 'slug' => 'test', + 'order' => 1, + 'picture_alt' => '', + 'picture_title' => '', + ]); $product = Product::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'name' => 'Test', diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php index 1f406510..a8df85d1 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php @@ -196,11 +196,17 @@ describe('CreateProduct action', function (): void { ->andReturnTrue(); $storage->shouldReceive('fileExistsOnDisk') ->once() - ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/orphan-large.jpg'), $disk->disk) + ->with( + \Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/orphan-large.jpg'), + $disk->disk, + ) ->andReturnTrue(); $storage->shouldReceive('removeFromDisk') ->once() - ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/orphan-large.jpg'), $disk->disk) + ->with( + \Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/orphan-large.jpg'), + $disk->disk, + ) ->andReturnTrue(); $action = new CreateProduct( diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php index b5f472d6..15d128cf 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php @@ -99,11 +99,17 @@ describe('CreateRange action', function () { ->andReturn(new StorageFilePath('media/orphan-create-range.jpg')); $storage->shouldReceive('fileExistsOnDisk') ->once() - ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'media/orphan-create-range.jpg'), $disk->disk) + ->with( + \Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'media/orphan-create-range.jpg'), + $disk->disk, + ) ->andReturnTrue(); $storage->shouldReceive('removeFromDisk') ->once() - ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'media/orphan-create-range.jpg'), $disk->disk) + ->with( + \Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'media/orphan-create-range.jpg'), + $disk->disk, + ) ->andReturnTrue(); $action = new CreateRange( diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php index 0c769422..6756cdfa 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php @@ -156,11 +156,17 @@ describe('UpdateRange action', function () { $storage->shouldReceive('storeFileOntoDisk')->once()->andReturn($newPicture); $storage->shouldReceive('fileExistsOnDisk') ->once() - ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'media/orphan-new-range.jpg'), $disk->disk) + ->with( + \Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'media/orphan-new-range.jpg'), + $disk->disk, + ) ->andReturnTrue(); $storage->shouldReceive('removeFromDisk') ->once() - ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'media/orphan-new-range.jpg'), $disk->disk) + ->with( + \Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'media/orphan-new-range.jpg'), + $disk->disk, + ) ->andReturnTrue(); $action = new UpdateRange( diff --git a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php index e3743241..1f0107c3 100644 --- a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php @@ -52,7 +52,14 @@ describe('OrderLineDto Integration', function (): void { 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, 'total' => Money::EUR(4154), - 'employee' => new OrderEmployee(new Matricule('8888001'), 'Jean', 'Dupont', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('8888001'), + 'Jean', + 'Dupont', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->toDateString(), ]); diff --git a/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php b/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php index 4026cea5..a3922c21 100644 --- a/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php +++ b/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php @@ -113,26 +113,26 @@ describe('ActionExecutorService', function (): void { $store = new ArrayStore(); $innerLock = new LaravelCacheLock(new Repository($store)); $initialLevel = DB::transactionLevel(); - $levelAtAcquire = null; - $levelInsideAction = null; - $lockHeldInsideAction = false; - $levelAfterCommit = null; - $lockHeldAfterCommit = false; - $capturedKey = null; - $capturedTtl = null; - $capturedWait = null; + $lvl1 = null; + $lvl2 = null; + $held2 = false; + $lvl3 = null; + $held3 = false; + $key = null; + $ttl = null; + $wait = null; - $recordingLock = new class ($innerLock, $store, $levelAtAcquire, $levelAfterCommit, $lockHeldAfterCommit, $capturedKey, $capturedTtl, $capturedWait) implements Lock + $recordingLock = new class ($innerLock, $store, $lvl1, $lvl3, $held3, $key, $ttl, $wait) implements Lock { public function __construct( private readonly Lock $inner, private readonly ArrayStore $store, - public ?int &$levelAtAcquire, - public ?int &$levelAfterCommit, - public bool &$lockHeldAfterCommit, - public ?string &$capturedKey, - public ?int &$capturedTtl, - public ?int &$capturedWait, + public ?int &$lvl1, + public ?int &$lvl3, + public bool &$held3, + public ?string &$key, + public ?int &$ttl, + public ?int &$wait, ) { } @@ -143,18 +143,18 @@ describe('ActionExecutorService', function (): void { int $ttlSeconds = 30, int $waitSeconds = 10, ): mixed { - $this->capturedKey = $key; - $this->capturedTtl = $ttlSeconds; - $this->capturedWait = $waitSeconds; - $this->levelAtAcquire = DB::transactionLevel(); + $this->key = $key; + $this->ttl = $ttlSeconds; + $this->wait = $waitSeconds; + $this->lvl1 = DB::transactionLevel(); return $this->inner->synchronize( key: $key, callback: function () use ($callback, $key, $ttlSeconds): mixed { $result = $callback(); - $this->levelAfterCommit = DB::transactionLevel(); - $this->lockHeldAfterCommit = ! $this->store->lock($key, $ttlSeconds)->get(); + $this->lvl3 = DB::transactionLevel(); + $this->held3 = ! $this->store->lock($key, $ttlSeconds)->get(); return $result; }, @@ -164,12 +164,12 @@ describe('ActionExecutorService', function (): void { } }; - $action = new #[Locked(ttlSeconds: 45, waitSeconds: 7)] class ($store, $levelInsideAction, $lockHeldInsideAction) implements Action, ProvidesLockKey + $action = new #[Locked(ttlSeconds: 45, waitSeconds: 7)] class ($store, $lvl2, $held2) implements Action, ProvidesLockKey { public function __construct( private readonly ArrayStore $store, - public ?int &$levelInsideAction, - public bool &$lockHeldInsideAction, + public ?int &$lvl2, + public bool &$held2, ) { } @@ -182,8 +182,8 @@ describe('ActionExecutorService', function (): void { #[\Override] public function __invoke(ActionInput $input): string { - $this->levelInsideAction = DB::transactionLevel(); - $this->lockHeldInsideAction = ! $this->store->lock('test:lock:order', 45)->get(); + $this->lvl2 = DB::transactionLevel(); + $this->held2 = ! $this->store->lock('test:lock:order', 45)->get(); return 'committed'; } @@ -200,14 +200,14 @@ describe('ActionExecutorService', function (): void { // THEN expect($result)->toBe('committed') - ->and($capturedKey)->toBe('test:lock:order') - ->and($capturedTtl)->toBe(45) - ->and($capturedWait)->toBe(7) - ->and($levelAtAcquire)->toBe($initialLevel) - ->and($levelInsideAction)->toBe($initialLevel + 1) - ->and($lockHeldInsideAction)->toBeTrue() - ->and($levelAfterCommit)->toBe($initialLevel) - ->and($lockHeldAfterCommit)->toBeTrue() + ->and($key)->toBe('test:lock:order') + ->and($ttl)->toBe(45) + ->and($wait)->toBe(7) + ->and($lvl1)->toBe($initialLevel) + ->and($lvl2)->toBe($initialLevel + 1) + ->and($held2)->toBeTrue() + ->and($lvl3)->toBe($initialLevel) + ->and($held3)->toBeTrue() ->and($store->lock('test:lock:order', 45)->get())->toBeTrue(); }); @@ -696,13 +696,13 @@ describe('ActionExecutorService', function (): void { $eventDispatcher->shouldReceive('discard')->once(); $eventDispatcher->shouldNotReceive('flush'); - $onSuccessCalled = false; - $lockReleasedInHook = false; - $action = new #[Locked(key: 'test:locked:failure')] class ($onSuccessCalled, $lockReleasedInHook, $store) implements Action, HandlesFailure, HandlesSuccess + $ok = false; + $free = false; + $action = new #[Locked(key: 'test:locked:failure')] class ($ok, $free, $store) implements Action, HandlesFailure, HandlesSuccess { public function __construct( - public bool &$onSuccessCalled, - public bool &$lockReleasedInHook, + public bool &$ok, + public bool &$free, private readonly ArrayStore $store, ) { } @@ -722,9 +722,9 @@ describe('ActionExecutorService', function (): void { public function onFailure(ActionInput $input, \Throwable $exception): void { $lock = $this->store->lock('test:locked:failure', 30); - $this->lockReleasedInHook = (bool) $lock->get(); + $this->free = (bool) $lock->get(); - if ($this->lockReleasedInHook) { + if ($this->free) { $lock->release(); } } @@ -732,7 +732,7 @@ describe('ActionExecutorService', function (): void { #[\Override] public function onSuccess(ActionInput $input, mixed $result): void { - $this->onSuccessCalled = true; + $this->ok = true; } }; @@ -747,8 +747,8 @@ describe('ActionExecutorService', function (): void { ->toThrow(\DomainException::class, 'Locked domain failure'); expect(Tag::query()->where('label', 'Locked rollback test')->exists())->toBeFalse() - ->and($onSuccessCalled)->toBeFalse() - ->and($lockReleasedInHook)->toBeTrue() + ->and($ok)->toBeFalse() + ->and($free)->toBeTrue() ->and($store->lock('test:locked:failure', 30)->get())->toBeTrue(); }); @@ -818,11 +818,11 @@ describe('ActionExecutorService', function (): void { $eventDispatcher->shouldReceive('flush')->once()->ordered(); $eventDispatcher->shouldReceive('dispatch')->once()->with($postHookEvent)->ordered(); - $txLevelInsideAction = null; - $action = new #[WithoutTransaction] class ($txLevelInsideAction, $postHookEvent, $eventDispatcher) implements Action, HandlesSuccess + $txLevel = null; + $action = new #[WithoutTransaction] class ($txLevel, $postHookEvent, $eventDispatcher) implements Action, HandlesSuccess { public function __construct( - public ?int &$txLevelInsideAction, + public ?int &$txLevel, private readonly Event $event, private readonly LaravelDomainEventDispatcher $dispatcher, ) { @@ -831,7 +831,7 @@ describe('ActionExecutorService', function (): void { #[\Override] public function __invoke(ActionInput $input): string { - $this->txLevelInsideAction = DB::transactionLevel(); + $this->txLevel = DB::transactionLevel(); return 'exported'; } @@ -855,6 +855,6 @@ describe('ActionExecutorService', function (): void { // THEN expect($result)->toBe('exported') - ->and($txLevelInsideAction)->toBe($baseTx); + ->and($txLevel)->toBe($baseTx); }); }); diff --git a/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php b/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php index 87981f17..0592e1f2 100644 --- a/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php +++ b/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php @@ -68,7 +68,14 @@ describe('OrderOwnershipService', function () { 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(1000, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('1000301'), 'John', 'Doe', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('1000301'), + 'John', + 'Doe', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), ]); @@ -108,7 +115,14 @@ describe('OrderOwnershipService', function () { 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(1000, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('1000999'), 'Other', 'Person', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('1000999'), + 'Other', + 'Person', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), ]); @@ -134,7 +148,14 @@ describe('OrderOwnershipService', function () { 'reference' => new OrderReference(Uuid::uuid7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(1000, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('1000999'), 'Other', 'Person', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'employee' => new OrderEmployee( + new Matricule('1000999'), + 'Other', + 'Person', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), ]); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php index 4e316351..efaa9bc4 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php @@ -16,7 +16,13 @@ use Ramsey\Uuid\Uuid; it('retrieves exceptions within a period for a shop', function () { // GIVEN $shopUuid = Uuid::uuid7(); - $shop = Shop::query()->forceCreate(['id' => $shopUuid->toString(), 'name' => 'Shop 1', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); + $shop = Shop::query()->forceCreate([ + 'id' => $shopUuid->toString(), + 'name' => 'Shop 1', + 'postcode' => '75000', + 'city' => 'Paris', + 'address' => 'Addr', + ]); $exUuid = Uuid::uuid7(); $ex1 = PickupException::query()->forceCreate([ @@ -75,7 +81,13 @@ it('retrieves all exceptions', function () { it('retrieves exceptions associated with a shop', function () { // GIVEN $shopUuid = Uuid::uuid7(); - $shop = Shop::query()->forceCreate(['id' => $shopUuid->toString(), 'name' => 'Shop 1', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); + $shop = Shop::query()->forceCreate([ + 'id' => $shopUuid->toString(), + 'name' => 'Shop 1', + 'postcode' => '75000', + 'city' => 'Paris', + 'address' => 'Addr', + ]); $exUuid = Uuid::uuid7(); $ex1 = PickupException::query()->forceCreate([ diff --git a/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php index 73d40df6..6e85b58b 100644 --- a/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php +++ b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -159,7 +159,7 @@ describe('PlacePendingOrder', function (): void { ], ]); - it('persists refreshed basket and returns basketPriceChanged output when placePendingOrder throws BasketPriceChangedException', function (): void { + it('persists refreshed basket and returns basketPriceChanged when BasketPriceChangedException is thrown', function (): void { // GIVEN $input = new PlacePendingOrderInput(); $builder = \Mockery::mock(OrderBuilderCompleted::class); diff --git a/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php b/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php index fa95f53e..d0ef4c7a 100644 --- a/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php +++ b/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php @@ -28,7 +28,14 @@ describe('AnOrderHasBeenPlaced', function () { $reference = new OrderReference(Uuid::uuid7()); $totalTtc = new Money(1000, new Currency('EUR')); $matricule = new Matricule('1234567'); - $employee = new OrderEmployee($matricule, 'John', 'Doe', new ShopperEstablishmentCode('ETAB01'), new ShopperSiteCode('SITEA'), new ShopperServiceCode('101')); + $employee = new OrderEmployee( + $matricule, + 'John', + 'Doe', + new ShopperEstablishmentCode('ETAB01'), + new ShopperSiteCode('SITEA'), + new ShopperServiceCode('101'), + ); $shop = new OrderPlacedShop('Shop', 'Address', '12345', 'City'); $pickupDay = new \DateTimeImmutable(); $lines = [ @@ -50,7 +57,14 @@ describe('AnOrderHasBeenPlaced', function () { $reference = new OrderReference(Uuid::uuid7()); $totalTtc = new Money(1000, new Currency('EUR')); $matricule = new Matricule('1234567'); - $employee = new OrderEmployee($matricule, 'John', 'Doe', new ShopperEstablishmentCode('ETAB01'), new ShopperSiteCode('SITEA'), new ShopperServiceCode('101')); + $employee = new OrderEmployee( + $matricule, + 'John', + 'Doe', + new ShopperEstablishmentCode('ETAB01'), + new ShopperSiteCode('SITEA'), + new ShopperServiceCode('101'), + ); $shop = new OrderPlacedShop('Shop', 'Address', '12345', 'City'); $pickupDay = new \DateTimeImmutable(); $lines = []; diff --git a/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php b/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php index 35cc5a57..3d262ae6 100644 --- a/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php @@ -54,7 +54,18 @@ describe('OrderLineProduct', function (): void { it('throws exception if name is empty', function (): void { // GIVEN // WHEN - $action = fn () => new OrderLineProduct(new IncoId(1), new ProductId(Uuid::uuid7()), '', new ProductWeight(1, false), ProductBrand::marie, OrderUnit::KGM, Money::EUR(100), Money::EUR(100), Money::EUR(100), TaxRate::TVA_5_5); + $action = fn () => new OrderLineProduct( + new IncoId(1), + new ProductId(Uuid::uuid7()), + '', + new ProductWeight(1, false), + ProductBrand::marie, + OrderUnit::KGM, + Money::EUR(100), + Money::EUR(100), + Money::EUR(100), + TaxRate::TVA_5_5, + ); // THEN expect($action)->toThrow(\DomainException::class, 'Product name cannot be empty'); }); @@ -62,7 +73,18 @@ describe('OrderLineProduct', function (): void { it('throws exception if price is negative', function (): void { // GIVEN // WHEN - $action = fn () => new OrderLineProduct(new IncoId(1), new ProductId(Uuid::uuid7()), 'Name', new ProductWeight(1, false), ProductBrand::marie, OrderUnit::KGM, Money::EUR(-100), Money::EUR(100), Money::EUR(100), TaxRate::TVA_5_5); + $action = fn () => new OrderLineProduct( + new IncoId(1), + new ProductId(Uuid::uuid7()), + 'Name', + new ProductWeight(1, false), + ProductBrand::marie, + OrderUnit::KGM, + Money::EUR(-100), + Money::EUR(100), + Money::EUR(100), + TaxRate::TVA_5_5, + ); // THEN expect($action)->toThrow(\DomainException::class, 'Product price cannot be negative'); }); @@ -70,7 +92,18 @@ describe('OrderLineProduct', function (): void { it('throws exception if discounted price is negative', function (): void { // GIVEN // WHEN - $action = fn () => new OrderLineProduct(new IncoId(1), new ProductId(Uuid::uuid7()), 'Name', new ProductWeight(1, false), ProductBrand::marie, OrderUnit::KGM, Money::EUR(100), Money::EUR(-100), Money::EUR(100), TaxRate::TVA_5_5); + $action = fn () => new OrderLineProduct( + new IncoId(1), + new ProductId(Uuid::uuid7()), + 'Name', + new ProductWeight(1, false), + ProductBrand::marie, + OrderUnit::KGM, + Money::EUR(100), + Money::EUR(-100), + Money::EUR(100), + TaxRate::TVA_5_5, + ); // THEN expect($action)->toThrow(\DomainException::class, 'Product discounted price cannot be negative'); }); @@ -78,7 +111,18 @@ describe('OrderLineProduct', function (): void { it('throws exception if price per kg ttc is negative', function (): void { // GIVEN // WHEN - $action = fn () => new OrderLineProduct(new IncoId(1), new ProductId(Uuid::uuid7()), 'Name', new ProductWeight(1, false), ProductBrand::marie, OrderUnit::KGM, Money::EUR(100), Money::EUR(100), Money::EUR(-100), TaxRate::TVA_5_5); + $action = fn () => new OrderLineProduct( + new IncoId(1), + new ProductId(Uuid::uuid7()), + 'Name', + new ProductWeight(1, false), + ProductBrand::marie, + OrderUnit::KGM, + Money::EUR(100), + Money::EUR(100), + Money::EUR(-100), + TaxRate::TVA_5_5, + ); // THEN expect($action)->toThrow(\DomainException::class, 'Price per kg TTC cannot be negative'); }); @@ -86,7 +130,18 @@ describe('OrderLineProduct', function (): void { it('throws exception if discounted price is greater than price', function (): void { // GIVEN // WHEN - $action = fn () => new OrderLineProduct(new IncoId(1), new ProductId(Uuid::uuid7()), 'Name', new ProductWeight(1, false), ProductBrand::marie, OrderUnit::KGM, Money::EUR(100), Money::EUR(150), Money::EUR(100), TaxRate::TVA_5_5); + $action = fn () => new OrderLineProduct( + new IncoId(1), + new ProductId(Uuid::uuid7()), + 'Name', + new ProductWeight(1, false), + ProductBrand::marie, + OrderUnit::KGM, + Money::EUR(100), + Money::EUR(150), + Money::EUR(100), + TaxRate::TVA_5_5, + ); // THEN expect($action)->toThrow(\DomainException::class, 'Product discounted price cannot be greater than original price'); }); @@ -94,7 +149,18 @@ describe('OrderLineProduct', function (): void { it('throws exception if price per kg ttc is zero', function (): void { // GIVEN // WHEN - $action = fn () => new OrderLineProduct(new IncoId(1), new ProductId(Uuid::uuid7()), 'Name', new ProductWeight(1, false), ProductBrand::marie, OrderUnit::KGM, Money::EUR(100), Money::EUR(100), Money::EUR(0), TaxRate::TVA_5_5); + $action = fn () => new OrderLineProduct( + new IncoId(1), + new ProductId(Uuid::uuid7()), + 'Name', + new ProductWeight(1, false), + ProductBrand::marie, + OrderUnit::KGM, + Money::EUR(100), + Money::EUR(100), + Money::EUR(0), + TaxRate::TVA_5_5, + ); // THEN expect($action)->toThrow(\DomainException::class, 'Price per kg TTC has to be positive'); }); From b4384c00a757860618de8c503e280c3fe1859510 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 16:34:21 +0100 Subject: [PATCH 150/183] chore(lint): resolve remaining PHPCS warnings across domain, infra, shared, and unit tests --- .../ExpiredPickupTimeSlotException.php | 1 + .../OrderTunnel/InactiveShopperException.php | 1 + .../MissingOrderBuilderException.php | 1 + .../UnorderableProductException.php | 1 + domain/Models/Entities/Product.php | 55 ++++---- .../Adapters/Serializers/BasketSerializer.php | 123 +++++++++--------- shared/Filesystem/TemporaryFileFactory.php | 6 +- .../Domain/Models/Entities/BasketTest.php | 49 +++---- .../Models/ValueObjects/BasketProductTest.php | 40 +++--- .../ValueObjects/NutritionalValuesTest.php | 13 +- .../Models/ValueObjects/OrderLineTest.php | 39 ++---- 11 files changed, 142 insertions(+), 187 deletions(-) diff --git a/domain/Exceptions/OrderTunnel/ExpiredPickupTimeSlotException.php b/domain/Exceptions/OrderTunnel/ExpiredPickupTimeSlotException.php index 95092ba9..a359f51d 100644 --- a/domain/Exceptions/OrderTunnel/ExpiredPickupTimeSlotException.php +++ b/domain/Exceptions/OrderTunnel/ExpiredPickupTimeSlotException.php @@ -6,6 +6,7 @@ namespace Domain\Exceptions\OrderTunnel; class ExpiredPickupTimeSlotException extends \DomainException { + // phpcs:ignore Generic.CodeAnalysis.UselessOverridingMethod.Found -- Customizes default exception message. public function __construct( string $message = 'Invalid or unavailable time slot', int $code = 0, diff --git a/domain/Exceptions/OrderTunnel/InactiveShopperException.php b/domain/Exceptions/OrderTunnel/InactiveShopperException.php index d305c7f4..6cae3532 100644 --- a/domain/Exceptions/OrderTunnel/InactiveShopperException.php +++ b/domain/Exceptions/OrderTunnel/InactiveShopperException.php @@ -6,6 +6,7 @@ namespace Domain\Exceptions\OrderTunnel; class InactiveShopperException extends \DomainException { + // phpcs:ignore Generic.CodeAnalysis.UselessOverridingMethod.Found -- Customizes default exception message. public function __construct( string $message = 'Employee account is no longer active.', int $code = 0, diff --git a/domain/Exceptions/OrderTunnel/MissingOrderBuilderException.php b/domain/Exceptions/OrderTunnel/MissingOrderBuilderException.php index 72d60fc4..c7d35c0f 100644 --- a/domain/Exceptions/OrderTunnel/MissingOrderBuilderException.php +++ b/domain/Exceptions/OrderTunnel/MissingOrderBuilderException.php @@ -6,6 +6,7 @@ namespace Domain\Exceptions\OrderTunnel; class MissingOrderBuilderException extends \DomainException { + // phpcs:ignore Generic.CodeAnalysis.UselessOverridingMethod.Found -- Customizes default exception message. public function __construct( string $message = 'Order builder is missing or not in expected state.', int $code = 0, diff --git a/domain/Exceptions/OrderTunnel/UnorderableProductException.php b/domain/Exceptions/OrderTunnel/UnorderableProductException.php index ef18d5f1..65779c7e 100644 --- a/domain/Exceptions/OrderTunnel/UnorderableProductException.php +++ b/domain/Exceptions/OrderTunnel/UnorderableProductException.php @@ -6,6 +6,7 @@ namespace Domain\Exceptions\OrderTunnel; class UnorderableProductException extends \DomainException { + // phpcs:ignore Generic.CodeAnalysis.UselessOverridingMethod.Found -- Customizes default exception message. public function __construct( string $message = 'One or more products in your basket are no longer available for order.', int $code = 0, diff --git a/domain/Models/Entities/Product.php b/domain/Models/Entities/Product.php index 5e876902..2da0b872 100644 --- a/domain/Models/Entities/Product.php +++ b/domain/Models/Entities/Product.php @@ -122,31 +122,7 @@ final class Product implements Entity public function priceKgTtc(): Money { if ($this->invoicing_unit === InvoicingUnit::KGM) { - // * The product price is already a price per kg: it is the reference for the kg price - $discountAmountKgHt = $this->validDiscount?->calculateDiscountAmount($this->price) - ?? new Money(0, $this->price->getCurrency()); - - $grams = $this->product_weight?->toGrams() ?? 0; - - if ( - $this->validDiscount !== null - && ! $this->validDiscount->isPercentage() - && $this->sell_unit === SellUnit::PCE - && $grams > 0 - ) { - // * A fixed amount applies to the piece: bring it back to a per-kg amount - $discountAmountKgHt = $discountAmountKgHt - ->multiply(self::GRAMS_PER_KG) - ->divide($grams, self::ROUNDING); - } - - $discountedKgPriceHt = $this->price->subtract($discountAmountKgHt); - - if ($discountedKgPriceHt->isNegative()) { - $discountedKgPriceHt = new Money(0, $this->price->getCurrency()); - } - - return $this->tax_rate->applyTo($discountedKgPriceHt); + return $this->discountedKgPriceTtc(); } $priceTtc = $this->discountedPriceTtc(); @@ -163,6 +139,35 @@ final class Product implements Entity return $priceTtc; } + private function discountedKgPriceTtc(): Money + { + // * The product price is already a price per kg: it is the reference for the kg price + $discountAmountKgHt = $this->validDiscount?->calculateDiscountAmount($this->price) + ?? new Money(0, $this->price->getCurrency()); + + $grams = $this->product_weight?->toGrams() ?? 0; + + if ( + $this->validDiscount !== null + && ! $this->validDiscount->isPercentage() + && $this->sell_unit === SellUnit::PCE + && $grams > 0 + ) { + // * A fixed amount applies to the piece: bring it back to a per-kg amount + $discountAmountKgHt = $discountAmountKgHt + ->multiply(self::GRAMS_PER_KG) + ->divide($grams, self::ROUNDING); + } + + $discountedKgPriceHt = $this->price->subtract($discountAmountKgHt); + + if ($discountedKgPriceHt->isNegative()) { + $discountedKgPriceHt = new Money(0, $this->price->getCurrency()); + } + + return $this->tax_rate->applyTo($discountedKgPriceHt); + } + public function discountRate(): DiscountRate { if ($this->validDiscount?->isPercentage()) { diff --git a/infra/Adapters/Serializers/BasketSerializer.php b/infra/Adapters/Serializers/BasketSerializer.php index cc7465c1..d90c5648 100644 --- a/infra/Adapters/Serializers/BasketSerializer.php +++ b/infra/Adapters/Serializers/BasketSerializer.php @@ -60,71 +60,10 @@ class BasketSerializer $hydratedItems = []; - foreach ($rawItems as $itemData) { - $itemData = Arr::wrap($itemData); - $id = Arr::string($itemData, 'id'); - $name = Arr::string($itemData, 'name'); - $qty = Arr::integer($itemData, 'qty'); - $unitPriceHt = Arr::array($itemData, 'unitPriceHt'); - $unitPriceHtCurrency = Arr::string($unitPriceHt, 'currency'); - $unitDiscount = Arr::array($itemData, 'unitDiscount'); - $unitDiscountCurrency = Arr::string($unitDiscount, 'currency'); - $taxRate = Arr::integer($itemData, 'taxRate'); - $weightGrams = Arr::integer($itemData, 'weightGrams'); - $brand = Arr::get($itemData, 'brand'); // using get because it can be null - $incoId = Arr::get($itemData, 'incoId'); - $orderUnit = Arr::string($itemData, 'orderUnit'); - $slug = Arr::string($itemData, 'slug'); - $picture = Arr::get($itemData, 'picture'); - $description = Arr::get($itemData, 'description'); - $weightVariable = Arr::boolean($itemData, 'weightVariable'); - $discountRate = $this->hydrateDiscountRate($itemData); - $priceKgTtc = Arr::array($itemData, 'priceKgTtc'); - $priceKgTtcCurrency = Arr::string($priceKgTtc, 'currency'); - $options = Arr::array($itemData, 'options', []); - - foreach ($options as $key => $option) { - Assert::string($key); - } - - if (empty($unitPriceHtCurrency)) { - throw new \DomainException("Currency is required for unitPriceHt of item with id $id"); - } - if (empty($unitDiscountCurrency)) { - throw new \DomainException("Currency is required for unitDiscount of item with id $id"); - } - if (empty($priceKgTtcCurrency)) { - throw new \DomainException("Currency is required for priceKgTtc of item with id $id"); - } - - $hydratedItems[$id] = new BasketProduct( - id: new ProductId(Uuid::fromString($id)), - name: $name, - qty: $qty, - unitPriceHt: new Money( - is_scalar($a = Arr::get($unitPriceHt, 'amount', 0)) ? (int) $a : 0, - new Currency($unitPriceHtCurrency) - ), - unitDiscount: new Money( - is_scalar($a = Arr::get($unitDiscount, 'amount', 0)) ? (int) $a : 0, - new Currency($unitDiscountCurrency) - ), - taxRate: TaxRate::from($taxRate), - weightGrams: $weightGrams, - brand: is_string($brand) && $brand !== '' ? ProductBrand::from($brand) : null, - incoId: is_scalar($incoId) && $incoId !== 0 ? new IncoId((int) $incoId) : null, - orderUnit: OrderUnit::from($orderUnit), - slug: $slug, - picture: is_string($picture) && $picture !== '' ? new StorageFilePath($picture) : null, - description: is_string($description) && $description !== '' ? $description : null, - weightVariable: $weightVariable, - discountRate: $discountRate, - priceKgTtc: new Money( - is_scalar($a = Arr::get($priceKgTtc, 'amount', 0)) ? (int) $a : 0, - new Currency($priceKgTtcCurrency) - ), - options: $options - ); + foreach ($rawItems as $rawItem) { + $itemData = Arr::wrap($rawItem); + $id = Arr::string($itemData, 'id'); + $hydratedItems[$id] = $this->hydrateBasketProduct($id, $itemData); } return new Basket( @@ -133,6 +72,60 @@ class BasketSerializer ); } + /** + * @param array $itemData + */ + private function hydrateBasketProduct(string $id, array $itemData): BasketProduct + { + $brand = Arr::get($itemData, 'brand'); // using get because it can be null + $incoId = Arr::get($itemData, 'incoId'); + $picture = Arr::get($itemData, 'picture'); + $description = Arr::get($itemData, 'description'); + $options = Arr::array($itemData, 'options', []); + + foreach ($options as $key => $option) { + Assert::string($key); + } + + return new BasketProduct( + id: new ProductId(Uuid::fromString($id)), + name: Arr::string($itemData, 'name'), + qty: Arr::integer($itemData, 'qty'), + unitPriceHt: $this->hydrateMoney($id, 'unitPriceHt', Arr::array($itemData, 'unitPriceHt')), + unitDiscount: $this->hydrateMoney($id, 'unitDiscount', Arr::array($itemData, 'unitDiscount')), + taxRate: TaxRate::from(Arr::integer($itemData, 'taxRate')), + weightGrams: Arr::integer($itemData, 'weightGrams'), + brand: is_string($brand) && $brand !== '' ? ProductBrand::from($brand) : null, + incoId: is_scalar($incoId) && $incoId !== 0 ? new IncoId((int) $incoId) : null, + orderUnit: OrderUnit::from(Arr::string($itemData, 'orderUnit')), + slug: Arr::string($itemData, 'slug'), + picture: is_string($picture) && $picture !== '' ? new StorageFilePath($picture) : null, + description: is_string($description) && $description !== '' ? $description : null, + weightVariable: Arr::boolean($itemData, 'weightVariable'), + discountRate: $this->hydrateDiscountRate($itemData), + priceKgTtc: $this->hydrateMoney($id, 'priceKgTtc', Arr::array($itemData, 'priceKgTtc')), + options: $options + ); + } + + /** + * @param array $moneyData + */ + private function hydrateMoney(string $itemId, string $field, array $moneyData): Money + { + $currency = Arr::string($moneyData, 'currency'); + if ($currency === '') { + throw new \DomainException("Currency is required for {$field} of item with id {$itemId}"); + } + + $rawAmount = Arr::get($moneyData, 'amount', 0); + + return new Money( + is_scalar($rawAmount) ? (int) $rawAmount : 0, + new Currency($currency) + ); + } + /** * Reads the discount rate in basis points; falls back to the legacy float ratio * (key "discountRate") stored in sessions created before the DiscountRate value object. diff --git a/shared/Filesystem/TemporaryFileFactory.php b/shared/Filesystem/TemporaryFileFactory.php index d8e1e863..a85fdf62 100644 --- a/shared/Filesystem/TemporaryFileFactory.php +++ b/shared/Filesystem/TemporaryFileFactory.php @@ -116,7 +116,9 @@ final class TemporaryFileFactory if ($extension !== '') { $targetPath = $baseTempPath . '.' . $extension; if (! rename($baseTempPath, $targetPath)) { - @unlink($baseTempPath); + if (is_file($baseTempPath)) { + unlink($baseTempPath); + } throw new TemporaryFileException('Could not rename temporary file with extension.'); } $baseTempPath = $targetPath; @@ -131,7 +133,7 @@ final class TemporaryFileFactory { foreach ($this->temporaryFilePaths as $path) { if (is_file($path)) { - @unlink($path); + unlink($path); } } diff --git a/tests/Unit/Domain/Models/Entities/BasketTest.php b/tests/Unit/Domain/Models/Entities/BasketTest.php index 89e580d0..fdb4f57c 100644 --- a/tests/Unit/Domain/Models/Entities/BasketTest.php +++ b/tests/Unit/Domain/Models/Entities/BasketTest.php @@ -22,44 +22,29 @@ describe('Basket and BasketProduct', function (): void { /** * @param array{ * id?: ProductId, - * name?: string, * qty?: int, - * unitPriceHt?: Money, - * unitDiscount?: Money, - * taxRate?: TaxRate, - * weightGrams?: int, - * brand?: ProductBrand, - * incoId?: IncoId|null, - * orderUnit?: OrderUnit, - * slug?: string, - * picture?: StorageFilePath|null, - * description?: string|null, - * weightVariable?: bool, - * discountRate?: DiscountRate, - * priceKgTtc?: Money, - * options?: array, * } $overrides */ function getNewBasketProduct(array $overrides = []): BasketProduct { return new BasketProduct( - id: $overrides['id'] ?? new ProductId(Uuid::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')), - name: $overrides['name'] ?? 'Poulet Rôti', - qty: $overrides['qty'] ?? 2, - unitPriceHt: $overrides['unitPriceHt'] ?? Money::EUR(1000), - unitDiscount: $overrides['unitDiscount'] ?? Money::EUR(200), - taxRate: $overrides['taxRate'] ?? TaxRate::TVA_5_5, - weightGrams: $overrides['weightGrams'] ?? 1200, - brand: $overrides['brand'] ?? ProductBrand::marie, - incoId: $overrides['incoId'] ?? new IncoId(45), - orderUnit: $overrides['orderUnit'] ?? OrderUnit::PCE, - slug: $overrides['slug'] ?? 'poulet-roti', - picture: $overrides['picture'] ?? new StorageFilePath('images/poulet.jpg'), - description: $overrides['description'] ?? 'Un bon poulet rôti', - weightVariable: $overrides['weightVariable'] ?? true, - discountRate: $overrides['discountRate'] ?? DiscountRate::fromRatio(0.2), - priceKgTtc: $overrides['priceKgTtc'] ?? Money::EUR(1500), - options: $overrides['options'] ?? ['extra' => 'crispy'], + id: $overrides['id'] ?? new ProductId(Uuid::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')), + name: 'Poulet Rôti', + qty: $overrides['qty'] ?? 2, + unitPriceHt: Money::EUR(1000), + unitDiscount: Money::EUR(200), + taxRate: TaxRate::TVA_5_5, + weightGrams: 1200, + brand: ProductBrand::marie, + incoId: new IncoId(45), + orderUnit: OrderUnit::PCE, + slug: 'poulet-roti', + picture: new StorageFilePath('images/poulet.jpg'), + description: 'Un bon poulet rôti', + weightVariable: true, + discountRate: DiscountRate::fromRatio(0.2), + priceKgTtc: Money::EUR(1500), + options: ['extra' => 'crispy'], ); } diff --git a/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php b/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php index 8afad6f9..cb871fe1 100644 --- a/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php @@ -23,43 +23,35 @@ describe('BasketProduct', function () { /** * @param array{ - * id?: ProductId, * name?: string, * qty?: int, * unitPriceHt?: Money, * unitDiscount?: Money, * taxRate?: TaxRate, * weightGrams?: int, - * brand?: ProductBrand, - * incoId?: \Domain\Models\ValueObjects\IncoId|null, - * orderUnit?: OrderUnit, * slug?: string, - * picture?: \Uwil\Storage\Lib\ValueObjects\StorageFilePath|null, - * description?: string|null, - * weightVariable?: bool, - * discountRate?: DiscountRate, * priceKgTtc?: Money, * } $overrides */ function getNewProduct(array $overrides = []): BasketProduct { return new BasketProduct( - id: $overrides['id'] ?? new ProductId(Uuid::uuid7()), - name: $overrides['name'] ?? 'Product Name', - qty: $overrides['qty'] ?? 1, - unitPriceHt: $overrides['unitPriceHt'] ?? getMoney(100), - unitDiscount: $overrides['unitDiscount'] ?? getMoney(10), - taxRate: $overrides['taxRate'] ?? TaxRate::TVA_20, - weightGrams: $overrides['weightGrams'] ?? 500, - brand: $overrides['brand'] ?? ProductBrand::none, - incoId: $overrides['incoId'] ?? null, - orderUnit: $overrides['orderUnit'] ?? OrderUnit::PCE, - slug: $overrides['slug'] ?? 'product-slug', - picture: $overrides['picture'] ?? null, - description: $overrides['description'] ?? null, - weightVariable: $overrides['weightVariable'] ?? false, - discountRate: $overrides['discountRate'] ?? DiscountRate::fromRatio(0.1), - priceKgTtc: $overrides['priceKgTtc'] ?? getMoney(240), + id: new ProductId(Uuid::uuid7()), + name: $overrides['name'] ?? 'Product Name', + qty: $overrides['qty'] ?? 1, + unitPriceHt: $overrides['unitPriceHt'] ?? getMoney(100), + unitDiscount: $overrides['unitDiscount'] ?? getMoney(10), + taxRate: $overrides['taxRate'] ?? TaxRate::TVA_20, + weightGrams: $overrides['weightGrams'] ?? 500, + brand: ProductBrand::none, + incoId: null, + orderUnit: OrderUnit::PCE, + slug: $overrides['slug'] ?? 'product-slug', + picture: null, + description: null, + weightVariable: false, + discountRate: DiscountRate::fromRatio(0.1), + priceKgTtc: $overrides['priceKgTtc'] ?? getMoney(240), ); } diff --git a/tests/Unit/Domain/Models/ValueObjects/NutritionalValuesTest.php b/tests/Unit/Domain/Models/ValueObjects/NutritionalValuesTest.php index a78b4ef8..76a3c663 100644 --- a/tests/Unit/Domain/Models/ValueObjects/NutritionalValuesTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/NutritionalValuesTest.php @@ -24,18 +24,7 @@ describe('NutritionalValues', function () { */ function getNewNutritionalValues(array $overrides = []): NutritionalValues { - return new NutritionalValues( - refWeightG: $overrides['refWeightG'] ?? null, - kj: $overrides['kj'] ?? null, - kcal: $overrides['kcal'] ?? null, - fatG: $overrides['fatG'] ?? null, - satFatG: $overrides['satFatG'] ?? null, - carbG: $overrides['carbG'] ?? null, - sugarG: $overrides['sugarG'] ?? null, - proteinG: $overrides['proteinG'] ?? null, - saltG: $overrides['saltG'] ?? null, - dailyEnergy: $overrides['dailyEnergy'] ?? null, - ); + return new NutritionalValues(...$overrides); } it('can instantiate', function () { diff --git a/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php b/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php index a6c58fbe..be8082be 100644 --- a/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php @@ -16,35 +16,20 @@ use Money\Money; use Ramsey\Uuid\Uuid; describe('OrderLine', function (): void { - /** - * @param array{ - * incoId?: IncoId, - * originalId?: ProductId, - * name?: string, - * weight?: ProductWeight, - * brand?: ProductBrand, - * orderUnit?: OrderUnit, - * price?: Money, - * discountedPrice?: Money, - * priceKgTtc?: Money, - * taxRate?: TaxRate, - * picture?: \Uwil\Storage\Lib\ValueObjects\StorageFilePath|null, - * } $overrides - */ - function getNewOrderLineProduct(array $overrides = []): OrderLineProduct + function getNewOrderLineProduct(): OrderLineProduct { return new OrderLineProduct( - incoId: $overrides['incoId'] ?? new IncoId(1), - originalId: $overrides['originalId'] ?? new ProductId(Uuid::uuid7()), - name: $overrides['name'] ?? 'poulet blanc', - weight: $overrides['weight'] ?? new ProductWeight(200, false), - brand: $overrides['brand'] ?? ProductBrand::loue, - orderUnit: $overrides['orderUnit'] ?? OrderUnit::KGM, - price: $overrides['price'] ?? Money::EUR(100), - discountedPrice: $overrides['discountedPrice'] ?? Money::EUR(100), - priceKgTtc: $overrides['priceKgTtc'] ?? Money::EUR(500), - taxRate: $overrides['taxRate'] ?? TaxRate::TVA_20, - picture: $overrides['picture'] ?? null, + incoId: new IncoId(1), + originalId: new ProductId(Uuid::uuid7()), + name: 'poulet blanc', + weight: new ProductWeight(200, false), + brand: ProductBrand::loue, + orderUnit: OrderUnit::KGM, + price: Money::EUR(100), + discountedPrice: Money::EUR(100), + priceKgTtc: Money::EUR(500), + taxRate: TaxRate::TVA_20, + picture: null, ); } From aee7d4b8e75ae2c233299f0def1fc31a06c7920d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 16:37:52 +0100 Subject: [PATCH 151/183] chore(config): force APP_ENV to testing in phpunit.xml Ensures the testing environment is consistently set. --- phpunit.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpunit.xml b/phpunit.xml index c3216a6a..57548422 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -19,7 +19,7 @@ - + From 241ad87a2e209756d4f9c12534b6756143e71881 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 16:47:33 +0100 Subject: [PATCH 152/183] test(coverage): cover remaining CQS Queries and FO product HTML rendering (Lot 7A) --- .../Fo/Pages/ProductsControllerTest.php | 90 +++++ .../Cqs/Queries/Basket/GetBasketQueryTest.php | 173 ++++++++++ .../Orders/GetBoPaginatedOrdersQueryTest.php | 326 ++++++++++++++++++ .../GetFoCustomerPaginatedOrdersQueryTest.php | 172 +++++++++ .../GetFoFilteredProductsQueryTest.php | 206 +++++++++++ .../GetPaginatedProductsQueryTest.php | 211 ++++++++++++ .../GetProductWithPricingQueryTest.php | 118 +++++++ .../GetAvailableTimeslotsQueryTest.php | 134 +++++++ 8 files changed, 1430 insertions(+) create mode 100644 tests/Integration/WithApp/App/Cqs/Queries/Basket/GetBasketQueryTest.php create mode 100644 tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoPaginatedOrdersQueryTest.php create mode 100644 tests/Integration/WithApp/App/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQueryTest.php create mode 100644 tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoFilteredProductsQueryTest.php create mode 100644 tests/Integration/WithApp/App/Cqs/Queries/Products/GetPaginatedProductsQueryTest.php create mode 100644 tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductWithPricingQueryTest.php create mode 100644 tests/Integration/WithApp/App/Cqs/Queries/Timeslots/GetAvailableTimeslotsQueryTest.php diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/ProductsControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/ProductsControllerTest.php index 627c72ee..443281fe 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/ProductsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/ProductsControllerTest.php @@ -4,18 +4,25 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Controllers\Fo\Pages; +use App\Models\Discount; use App\Models\Page; use App\Models\Product; +use App\Models\ProductInco; use App\Models\Range; +use App\Models\User; use Database\Seeders\ContentSeeder; +use Domain\Enums\DiscountType; use Domain\Enums\ProductBrand; use Domain\Enums\SellUnit; use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; +use Domain\Models\ValueObjects\DiscountValue; +use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\View; use Money\Money; +use function Pest\Laravel\actingAs; use function Pest\Laravel\get; use function Pest\Laravel\seed; @@ -92,4 +99,87 @@ describe('ProductsController', function () { expect($associatedNames)->toContain($publishedOther->name) ->and($associatedNames)->not->toContain($draftProduct->name); }); + + it('renders published products and excludes unpublished products on GET /produits', function () use ($createProduct): void { + // GIVEN + seed(ContentSeeder::class); + $pages = Page::getCached()->mapWithKeys(fn (Page $page) => [$page->slug->value() => $page]); + View::share('PageList', $pages); + + $published = $createProduct('Poulet Fermier Publie', true, 1); + $draft = $createProduct('Poulet Brouillon Cache', false, 2); + $draft->range->update(['status' => false]); + + // WHEN + $response = get('/produits'); + + // THEN + $response->assertStatus(200) + ->assertSee('id="products-viewer"', false) + ->assertSee($published->name, false) + ->assertDontSee($draft->name, false); + + /** @var array $resourceList */ + $resourceList = $response->viewData('productListResource'); + $names = array_column($resourceList, 'name'); + + expect($names)->toContain($published->name) + ->and($names)->not->toContain($draft->name); + }); + + it('renders formatted price TTC, discount markup and add-to-basket component on GET /produit/{slug}', function () use ($createProduct): void { + // GIVEN + Date::setTestNow('2026-06-15 10:00:00'); + seed(ContentSeeder::class); + $pages = Page::getCached()->mapWithKeys(fn (Page $page) => [$page->slug->value() => $page]); + View::share('PageList', $pages); + + $user = User::factory()->create(); + actingAs($user); + + $discount = new Discount(); + $discount->type = DiscountType::PERCENT; + $discount->value = DiscountValue::fromPercentage(20); + $discount->is_old_price_displayed = true; + $discount->date_start = Date::now()->subDay(); + $discount->date_end = Date::now()->addDay(); + $discount->save(); + + $product = $createProduct('Poulet Roti Fermier', true, 1); + $product->discount_id = $discount->id; + $product->save(); + + $inco = new ProductInco(); + $inco->no_art = random_int(10000, 99999); + $inco->product()->associate($product); + $inco->saveOrFail(); + + // WHEN + $response = get("/produit/{$product->slug}"); + Date::setTestNow(); + + // THEN + $response->assertStatus(200) + ->assertSee($product->name, false) + ->assertSee('class="basket-buttons"', false) + ->assertSee((string) $product->id, false) + ->assertSee('text-danger', false) + ->assertSee('text-decoration-line-through', false) + ->assertDontSee('-.--', false); + }); + + it('forbids viewing an unpublished product directly by slug on GET /produit/{slug}', function () use ($createProduct): void { + // GIVEN + seed(ContentSeeder::class); + $pages = Page::getCached()->mapWithKeys(fn (Page $page) => [$page->slug->value() => $page]); + View::share('PageList', $pages); + + $draft = $createProduct('Produit Non Publié', false, 1); + + // WHEN + $response = get("/produit/{$draft->slug}"); + + // THEN + $response->assertNotFound(); + }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Basket/GetBasketQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Basket/GetBasketQueryTest.php new file mode 100644 index 00000000..ceb24a0d --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/Basket/GetBasketQueryTest.php @@ -0,0 +1,173 @@ +id : new BasketId(Uuid::uuid7()); + $sessionId = new SessionId($basketId->value); + + $sessionService = Mockery::mock(SessionService::class); + $sessionService->shouldReceive('get')->andReturn($sessionId); + + $basketRepository = Mockery::mock(BasketRepository::class); + $basketRepository->shouldReceive('find')->with(Mockery::type(BasketId::class))->andReturn($basket); + + return new BasketService( + repository: $basketRepository, + productRepository: Mockery::mock(ProductRepository::class), + sessionService: $sessionService, + eventDispatcher: Mockery::mock(DomainEventDispatcher::class), + ); +} + +function makeBasketProductItem(ProductId $id, string $name, int $qty = 1): BasketProduct +{ + return new BasketProduct( + id: $id, + name: $name, + qty: $qty, + unitPriceHt: Money::EUR(1000), + unitDiscount: Money::EUR(0), + taxRate: TaxRate::TVA_5_5, + weightGrams: 1000, + brand: ProductBrand::marie, + incoId: new IncoId(45), + orderUnit: OrderUnit::PCE, + slug: 'poulet-roti', + picture: new StorageFilePath('images/poulet.jpg'), + description: 'Description produit', + weightVariable: false, + discountRate: DiscountRate::fromRatio(0.0), + priceKgTtc: Money::EUR(1055), + ); +} + +describe('GetBasketQuery', function (): void { + it('returns an empty BasketDto when the basket is empty', function (): void { + // GIVEN + $basketService = makeBasketServiceWithBasket(null); + $query = new GetBasketQuery($basketService); + + // WHEN + $result = $query(QueryInputEmpty::create()); + + // THEN + expect($result->items)->toBe([]) + ->and($result->countItems)->toBe(0) + ->and($result->totalWeight)->toBe(0); + }); + + it('maps published and unpublished products with accurate isPublished flag', function (): void { + // GIVEN + $range = new Range(); + $range->name = 'Gamme Test ' . uniqid(); + $range->status = true; + $range->order = random_int(1, 9999); + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + $publishedProduct = new Product([ + 'range_id' => $range->id, + 'name' => 'Poulet Publié', + 'brand' => ProductBrand::marie, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_5_5, + 'description' => 'Description produit', + 'status' => true, + 'picture_alt' => 'alt', + 'picture_title' => 'title', + 'picture_large_alt' => 'alt', + 'picture_large_title' => 'title', + ]); + $publishedProduct->order = random_int(1, 999999); + $publishedProduct->price = Money::EUR(1000); + $publishedProduct->save(); + + $unpublishedProduct = new Product([ + 'range_id' => $range->id, + 'name' => 'Poulet Dépublié', + 'brand' => ProductBrand::marie, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_5_5, + 'description' => 'Description produit', + 'status' => false, + 'picture_alt' => 'alt', + 'picture_title' => 'title', + 'picture_large_alt' => 'alt', + 'picture_large_title' => 'title', + ]); + $unpublishedProduct->order = random_int(1, 999999); + $unpublishedProduct->price = Money::EUR(1000); + $unpublishedProduct->save(); + + $publishedId = new ProductId(Uuid::fromString($publishedProduct->id)); + $unpublishedId = new ProductId(Uuid::fromString($unpublishedProduct->id)); + + $basket = new Basket(new BasketId(Uuid::uuid7()), [ + makeBasketProductItem($publishedId, 'Poulet Publié', 2), + makeBasketProductItem($unpublishedId, 'Poulet Dépublié', 1), + ]); + + $query = new GetBasketQuery(makeBasketServiceWithBasket($basket)); + + // WHEN + $result = $query(QueryInputEmpty::create()); + + // THEN + expect($result->items)->toHaveCount(2) + ->and($result->countItems)->toBe(3) + ->and($result->items[0]->product->id->equals($publishedId))->toBeTrue() + ->and($result->items[0]->isPublished)->toBeTrue() + ->and($result->items[1]->product->id->equals($unpublishedId))->toBeTrue() + ->and($result->items[1]->isPublished)->toBeFalse(); + }); + + it('throws InvalidArgumentException when invalid input is passed', function (): void { + // GIVEN + $query = new GetBasketQuery(makeBasketServiceWithBasket(null)); + $invalidInput = new class () implements QueryInput + { + }; + + // WHEN & THEN + expect( + /** @phpstan-ignore argument.type */ + fn () => $query($invalidInput) + )->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoPaginatedOrdersQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoPaginatedOrdersQueryTest.php new file mode 100644 index 00000000..320756d8 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoPaginatedOrdersQueryTest.php @@ -0,0 +1,326 @@ +name = $name; + $shop->address = '10 rue Principale'; + $shop->postcode = '75001'; + $shop->city = 'Paris'; + $shop->default = true; + $shop->save(); + + return $shop; + }; + + $createOrder = function ( + Shop $shop, + OrderStatus $status, + CarbonImmutable $pickupDay, + ?\DateTimeImmutable $createdAt = null, + ): Order { + $order = new Order(); + if ($createdAt !== null) { + $order->id = (string) Uuid::uuid7($createdAt); + } + $order->reference = new OrderReference(Uuid::uuid7()); + $order->total = Money::EUR(2500); + $order->status = $status; + $order->pickup_day = Carbon::instance($pickupDay); + $order->shop_id = $shop->id; + $order->delivery_address = new DeliveryAddress( + name: $shop->name, + address: $shop->address, + postcode: $shop->postcode, + city: $shop->city, + ); + $order->employee = new OrderEmployee( + matricule: new Matricule('1234567'), + firstname: 'Jean', + lastname: 'Dupont', + facility: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), + ); + $order->save(); + + return $order; + }; + + $makeQuery = function (): GetBoPaginatedOrdersQuery { + return new GetBoPaginatedOrdersQuery( + new DataTableService( + Request::create('/'), + new Store('test', new NullSessionHandler()), + static fn (string $table): array => Schema::getColumnListing($table), + ), + ); + }; + + it('returns GetBoPaginatedOrdersQueryOutput sorted by id DESC and respects pagination', function () use ( + $createShop, + $createOrder, + $makeQuery, + ): void { + // GIVEN + $shop = $createShop('Boutique Centre'); + $pickupDay = CarbonImmutable::parse('2026-04-10'); + + Carbon::setTestNow(CarbonImmutable::parse('2026-04-01 09:00:00')); + $order1 = $createOrder($shop, OrderStatus::WAITING, $pickupDay); + + Carbon::setTestNow(CarbonImmutable::parse('2026-04-01 09:00:01')); + $order2 = $createOrder($shop, OrderStatus::WAITING, $pickupDay); + + Carbon::setTestNow(CarbonImmutable::parse('2026-04-01 09:00:02')); + $order3 = $createOrder($shop, OrderStatus::WAITING, $pickupDay); + + $query = $makeQuery(); + + // WHEN: page 1 with pageSize 2 + $outputPage1 = $query(new GetBoPaginatedOrdersQueryInput( + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(2)), + )); + + // THEN + expect($outputPage1->searchFields)->not->toBeEmpty() + ->and($outputPage1->orderStatusList)->toBe(OrderStatus::cases()) + ->and($outputPage1->orders->total())->toBe(3) + ->and($outputPage1->orders->items())->toHaveCount(2) + ->and($outputPage1->orders->items()[0])->toBeInstanceOf(OrderDto::class) + ->and($outputPage1->orders->items()[0]->id)->toBe($order3->id) + ->and($outputPage1->orders->items()[1]->id)->toBe($order2->id); + + // WHEN: page 2 with pageSize 2 + $outputPage2 = $query(new GetBoPaginatedOrdersQueryInput( + pagination: Pagination::ofPage(new PageNumber(2), new PageSize(2)), + )); + + // THEN + expect($outputPage2->orders->items())->toHaveCount(1) + ->and($outputPage2->orders->items()[0]->id)->toBe($order1->id); + }); + + it('filters orders by search on reference and shop name', function () use ( + $createShop, + $createOrder, + $makeQuery, + ): void { + // GIVEN + $shopAlpha = $createShop('Boutique Alpha'); + $shopBeta = $createShop('Boutique Beta'); + $pickupDay = CarbonImmutable::parse('2026-04-10'); + + Carbon::setTestNow(CarbonImmutable::parse('2026-04-01 10:00:00')); + $orderAlpha = $createOrder($shopAlpha, OrderStatus::WAITING, $pickupDay); + + Carbon::setTestNow(CarbonImmutable::parse('2026-04-01 10:00:01')); + $orderBeta = $createOrder($shopBeta, OrderStatus::WAITING, $pickupDay); + + $query = $makeQuery(); + $pagination = Pagination::ofPage(new PageNumber(1), new PageSize(10)); + + // WHEN: search by reference + $byReference = $query(new GetBoPaginatedOrdersQueryInput( + pagination: $pagination, + search: (string) $orderAlpha->reference, + )); + + // THEN + expect($byReference->orders->total())->toBe(1) + ->and($byReference->orders->items()[0]->id)->toBe($orderAlpha->id); + + // WHEN: search by shop name + $byShopName = $query(new GetBoPaginatedOrdersQueryInput( + pagination: $pagination, + search: 'Beta', + )); + + // THEN + expect($byShopName->orders->total())->toBe(1) + ->and($byShopName->orders->items()[0]->id)->toBe($orderBeta->id); + }); + + it('filters orders by orderDateStart and orderDateEnd (single day and range)', function () use ( + $createShop, + $createOrder, + $makeQuery, + ): void { + // GIVEN + $shop = $createShop('Boutique Dates'); + $pickupDay = CarbonImmutable::parse('2026-04-20'); + + $orderDay1 = $createOrder( + $shop, + OrderStatus::WAITING, + $pickupDay, + new \DateTimeImmutable('2026-04-01 12:00:00'), + ); + + $orderDay5 = $createOrder( + $shop, + OrderStatus::WAITING, + $pickupDay, + new \DateTimeImmutable('2026-04-05 12:00:00'), + ); + + $orderDay10 = $createOrder( + $shop, + OrderStatus::WAITING, + $pickupDay, + new \DateTimeImmutable('2026-04-10 12:00:00'), + ); + + $query = $makeQuery(); + $pagination = Pagination::ofPage(new PageNumber(1), new PageSize(10)); + + // WHEN: single day (only orderDateStart) + $singleDay = $query(new GetBoPaginatedOrdersQueryInput( + pagination: $pagination, + orderDateStart: CarbonImmutable::parse('2026-04-05'), + )); + + // THEN + expect($singleDay->orders->total())->toBe(1) + ->and($singleDay->orders->items()[0]->id)->toBe($orderDay5->id); + + // WHEN: date range + $range = $query(new GetBoPaginatedOrdersQueryInput( + pagination: $pagination, + orderDateStart: CarbonImmutable::parse('2026-04-01'), + orderDateEnd: CarbonImmutable::parse('2026-04-06'), + )); + + // THEN + expect($range->orders->total())->toBe(2) + ->and($range->orders->items()[0]->id)->toBe($orderDay5->id) + ->and($range->orders->items()[1]->id)->toBe($orderDay1->id); + + // WHEN: single day on day 10 + $day10 = $query(new GetBoPaginatedOrdersQueryInput( + pagination: $pagination, + orderDateStart: CarbonImmutable::parse('2026-04-10'), + )); + + // THEN + expect($day10->orders->total())->toBe(1) + ->and($day10->orders->items()[0]->id)->toBe($orderDay10->id); + }); + + it('filters orders by orderPickupStart and orderPickupEnd (single day and range)', function () use ( + $createShop, + $createOrder, + $makeQuery, + ): void { + // GIVEN + $shop = $createShop('Boutique Pickup'); + + Carbon::setTestNow(CarbonImmutable::parse('2026-04-01 10:00:00')); + $orderPickup1 = $createOrder($shop, OrderStatus::WAITING, CarbonImmutable::parse('2026-05-01')); + + Carbon::setTestNow(CarbonImmutable::parse('2026-04-01 10:00:01')); + $orderPickup2 = $createOrder($shop, OrderStatus::WAITING, CarbonImmutable::parse('2026-05-05')); + + Carbon::setTestNow(CarbonImmutable::parse('2026-04-01 10:00:02')); + $orderPickup3 = $createOrder($shop, OrderStatus::WAITING, CarbonImmutable::parse('2026-05-10')); + + $query = $makeQuery(); + $pagination = Pagination::ofPage(new PageNumber(1), new PageSize(10)); + + // WHEN: single pickup day + $singlePickup = $query(new GetBoPaginatedOrdersQueryInput( + pagination: $pagination, + orderPickupStart: CarbonImmutable::parse('2026-05-05'), + )); + + // THEN + expect($singlePickup->orders->total())->toBe(1) + ->and($singlePickup->orders->items()[0]->id)->toBe($orderPickup2->id); + + // WHEN: pickup range + $pickupRange = $query(new GetBoPaginatedOrdersQueryInput( + pagination: $pagination, + orderPickupStart: CarbonImmutable::parse('2026-05-01'), + orderPickupEnd: CarbonImmutable::parse('2026-05-06'), + )); + + // THEN + expect($pickupRange->orders->total())->toBe(2) + ->and($pickupRange->orders->items()[0]->id)->toBe($orderPickup2->id) + ->and($pickupRange->orders->items()[1]->id)->toBe($orderPickup1->id); + + // WHEN: single pickup day 3 + $pickupDay3 = $query(new GetBoPaginatedOrdersQueryInput( + pagination: $pagination, + orderPickupStart: CarbonImmutable::parse('2026-05-10'), + )); + + // THEN + expect($pickupDay3->orders->total())->toBe(1) + ->and($pickupDay3->orders->items()[0]->id)->toBe($orderPickup3->id); + }); + + it('filters orders by status', function () use ( + $createShop, + $createOrder, + $makeQuery, + ): void { + // GIVEN + $shop = $createShop('Boutique Status'); + $pickupDay = CarbonImmutable::parse('2026-05-01'); + + Carbon::setTestNow(CarbonImmutable::parse('2026-04-01 10:00:00')); + $waitingOrder = $createOrder($shop, OrderStatus::WAITING, $pickupDay); + + Carbon::setTestNow(CarbonImmutable::parse('2026-04-01 10:00:01')); + $createOrder($shop, OrderStatus::CANCELED, $pickupDay); + + $query = $makeQuery(); + + // WHEN + $output = $query(new GetBoPaginatedOrdersQueryInput( + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), + status: OrderStatus::WAITING, + )); + + // THEN + expect($output->orders->total())->toBe(1) + ->and($output->orders->items()[0]->id)->toBe($waitingOrder->id) + ->and($output->orders->items()[0]->status)->toBe(OrderStatus::WAITING); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQueryTest.php new file mode 100644 index 00000000..a410bd02 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQueryTest.php @@ -0,0 +1,172 @@ +email = new Email('customer-' . uniqid() . '@example.com'); + $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->save(); + + return $customer; + }; + + $createEmployee = function (Customer $customer, string $matricule, string $code): Employee { + $employee = new Employee(); + $employee->customer_id = $customer->id; + $employee->matricule = new Matricule($matricule); + $employee->nom = 'Dupont'; + $employee->prenom = 'Jean'; + $employee->etablissement = new ShopperEstablishmentCode('FAC01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('101'); + $employee->code = new Code($code); + $employee->save(); + + return $employee; + }; + + $createShop = function (): Shop { + $shop = new Shop(); + $shop->name = 'Boutique ' . uniqid(); + $shop->address = '10 rue Principale'; + $shop->postcode = '75001'; + $shop->city = 'Paris'; + $shop->default = true; + $shop->save(); + + return $shop; + }; + + $createOrder = function (Shop $shop, string $matricule): Order { + $order = new Order(); + $order->reference = new OrderReference(Uuid::uuid7()); + $order->total = Money::EUR(2500); + $order->status = OrderStatus::WAITING; + $order->pickup_day = Carbon::now()->addDays(2); + $order->shop_id = $shop->id; + $order->delivery_address = new DeliveryAddress( + name: $shop->name, + address: $shop->address, + postcode: $shop->postcode, + city: $shop->city, + ); + $order->employee = new OrderEmployee( + matricule: new Matricule($matricule), + firstname: 'Jean', + lastname: 'Dupont', + facility: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), + ); + $order->save(); + + return $order; + }; + + it('returns an empty paginator when customer has no linked employee', function () use ($createCustomer): void { + // GIVEN + $customer = $createCustomer(); + $query = new GetFoCustomerPaginatedOrdersQuery(); + $pagination = Pagination::ofPage(new PageNumber(2), new PageSize(5)); + + // WHEN + $result = $query(new GetFoCustomerPaginatedOrdersQueryInput( + customer: $customer, + pagination: $pagination, + )); + + // THEN + expect($result->total())->toBe(0) + ->and($result->items())->toBe([]) + ->and($result->perPage())->toBe(5) + ->and($result->currentPage())->toBe(2); + }); + + it('returns only the linked employee orders sorted by id DESC, mapped to OrderDto and paginated', function () use ( + $createCustomer, + $createEmployee, + $createShop, + $createOrder, + ): void { + // GIVEN + $customer1 = $createCustomer(); + $customer2 = $createCustomer(); + $createEmployee($customer1, '1234567', 'ABCDEFG'); + $createEmployee($customer2, '7654321', 'HJKMNPR'); + $shop = $createShop(); + + $baseTime = CarbonImmutable::parse('2026-03-10 10:00:00'); + Carbon::setTestNow($baseTime); + $order1 = $createOrder($shop, '1234567'); + + Carbon::setTestNow($baseTime->addSecond()); + $order2 = $createOrder($shop, '1234567'); + + Carbon::setTestNow($baseTime->addSeconds(2)); + $order3 = $createOrder($shop, '1234567'); + + Carbon::setTestNow($baseTime->addSeconds(3)); + $createOrder($shop, '7654321'); + + $query = new GetFoCustomerPaginatedOrdersQuery(); + + // WHEN: page 1 with pageSize 2 + $page1 = $query(new GetFoCustomerPaginatedOrdersQueryInput( + customer: $customer1, + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(2)), + )); + + // THEN + expect($page1->total())->toBe(3) + ->and($page1->perPage())->toBe(2) + ->and($page1->currentPage())->toBe(1) + ->and($page1->items())->toHaveCount(2) + ->and($page1->items()[0]->id)->toBe($order3->id) + ->and($page1->items()[1]->id)->toBe($order2->id); + + // WHEN: page 2 with pageSize 2 + $page2 = $query(new GetFoCustomerPaginatedOrdersQueryInput( + customer: $customer1, + pagination: Pagination::ofPage(new PageNumber(2), new PageSize(2)), + )); + + // THEN + expect($page2->total())->toBe(3) + ->and($page2->currentPage())->toBe(2) + ->and($page2->items())->toHaveCount(1) + ->and($page2->items()[0]->id)->toBe($order1->id); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoFilteredProductsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoFilteredProductsQueryTest.php new file mode 100644 index 00000000..a47bab34 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoFilteredProductsQueryTest.php @@ -0,0 +1,206 @@ +name = 'Gamme ' . uniqid(); + $range->status = true; + $range->order = random_int(1, 9999); + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + return $range; + }; + + $createTag = function (): Tag { + $tag = new Tag(); + $tag->label = 'Tag ' . uniqid(); + $tag->status = true; + $tag->save(); + + return $tag; + }; + + $createProduct = function ( + string $name, + Range $range, + int $order, + ProductBrand $brand = ProductBrand::loue, + bool $status = true, + ?int $discountId = null, + ): Product { + $product = new Product([ + 'range_id' => $range->id, + 'name' => $name, + 'brand' => $brand, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Description test', + 'status' => $status, + 'picture_alt' => 'alt', + 'picture_title' => 'title', + 'picture_large_alt' => 'alt', + 'picture_large_title' => 'title', + ]); + $product->order = $order; + $product->price = Money::EUR(1000); + $product->discount_id = $discountId; + $product->save(); + + return $product; + }; + + $createQuery = function (): GetFoFilteredProductsQuery { + return new GetFoFilteredProductsQuery( + new ProductDtoAssemblerService(new EloquentProductRepository()), + ); + }; + + it('excludes unpublished products, orders by order ascending, and returns ProductWithPricingDto', function () use ( + $createRange, + $createProduct, + $createQuery, + ): void { + // GIVEN + $range = $createRange(); + $second = $createProduct('FO Second ' . uniqid(), $range, order: 20, status: true); + $first = $createProduct('FO First ' . uniqid(), $range, order: 10, status: true); + $hidden = $createProduct('FO Hidden ' . uniqid(), $range, order: 5, status: false); + + $query = $createQuery(); + + // WHEN + $result = $query(new GetFoFilteredProductsQueryInput( + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(50)), + ranges: [$range->id], + )); + + // THEN + $items = $result->items(); + $ids = collect($items)->map(static fn (ProductWithPricingDto $dto): string => $dto->product->id)->all(); + + expect($items)->toHaveCount(2) + ->and($ids)->toBe([$first->id, $second->id]) + ->and($ids)->not->toContain($hidden->id); + }); + + it('filters by search, isDiscounted, ranges, tags, and brands', function () use ( + $createRange, + $createTag, + $createProduct, + $createQuery, + ): void { + // GIVEN + CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-06-15 12:00:00')); + + $discount = new Discount(); + $discount->type = DiscountType::PERCENT; + $discount->value = DiscountValue::fromPercentage(10); + $discount->is_old_price_displayed = true; + $discount->save(); + + $range1 = $createRange(); + $range2 = $createRange(); + $tag1 = $createTag(); + $tag2 = $createTag(); + + $token = uniqid('match_'); + $matched = $createProduct("Poulet {$token}", $range1, order: 1, brand: ProductBrand::loue, discountId: $discount->id); + $matched->tags()->attach($tag1->id); + + $otherSearch = $createProduct('Canard Fermier ' . uniqid(), $range1, order: 2, brand: ProductBrand::loue, discountId: $discount->id); + $otherSearch->tags()->attach($tag1->id); + + $noDiscount = $createProduct("Poulet {$token} Sans Promo", $range1, order: 3, brand: ProductBrand::loue, discountId: null); + $noDiscount->tags()->attach($tag1->id); + + $otherRange = $createProduct("Poulet {$token} Autre Gamme", $range2, order: 4, brand: ProductBrand::loue, discountId: $discount->id); + $otherRange->tags()->attach($tag1->id); + + $otherTag = $createProduct("Poulet {$token} Autre Tag", $range1, order: 5, brand: ProductBrand::loue, discountId: $discount->id); + $otherTag->tags()->attach($tag2->id); + + $otherBrand = $createProduct("Poulet {$token} Autre Marque", $range1, order: 6, brand: ProductBrand::legaulois, discountId: $discount->id); + $otherBrand->tags()->attach($tag1->id); + + $query = $createQuery(); + + // WHEN + $result = $query(new GetFoFilteredProductsQueryInput( + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(20)), + search: $token, + ranges: [$range1->id], + tags: [$tag1->id], + brands: [ProductBrand::loue->value], + isDiscounted: true, + )); + + // THEN + $ids = collect($result->items())->map(static fn (ProductWithPricingDto $dto): string => $dto->product->id)->all(); + expect($ids)->toBe([$matched->id]); + }); + + it('paginates filtered results', function () use ( + $createRange, + $createProduct, + $createQuery, + ): void { + // GIVEN + $range = $createRange(); + $p1 = $createProduct('Paginated 1 ' . uniqid(), $range, order: 1); + $p2 = $createProduct('Paginated 2 ' . uniqid(), $range, order: 2); + $p3 = $createProduct('Paginated 3 ' . uniqid(), $range, order: 3); + + $query = $createQuery(); + + // WHEN + $page1 = $query(new GetFoFilteredProductsQueryInput( + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(2)), + ranges: [$range->id], + )); + $page2 = $query(new GetFoFilteredProductsQueryInput( + pagination: Pagination::ofPage(new PageNumber(2), new PageSize(2)), + ranges: [$range->id], + )); + + // THEN + $ids1 = collect($page1->items())->map(static fn (ProductWithPricingDto $dto): string => $dto->product->id)->all(); + $ids2 = collect($page2->items())->map(static fn (ProductWithPricingDto $dto): string => $dto->product->id)->all(); + expect($ids1)->toBe([$p1->id, $p2->id]) + ->and($ids2)->toBe([$p3->id]) + ->and($page1->total())->toBe(3); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Products/GetPaginatedProductsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetPaginatedProductsQueryTest.php new file mode 100644 index 00000000..c56d77ce --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetPaginatedProductsQueryTest.php @@ -0,0 +1,211 @@ +name = 'Gamme ' . uniqid(); + $range->status = true; + $range->order = random_int(1, 9999); + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + return $range; + }; + + $createProduct = function ( + string $name, + Range $range, + bool $status = true, + bool $star = false, + ?int $discountId = null, + ): Product { + $product = new Product([ + 'range_id' => $range->id, + 'name' => $name . ' ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Description test', + 'status' => $status, + 'star' => $star, + 'picture_alt' => 'alt', + 'picture_title' => 'title', + 'picture_large_alt' => 'alt', + 'picture_large_title' => 'title', + ]); + $product->order = random_int(1, 999999); + $product->price = Money::EUR(1000); + $product->discount_id = $discountId; + $product->save(); + + return $product; + }; + + $createQuery = function (): GetPaginatedProductsQuery { + return new GetPaginatedProductsQuery( + new DataTableService( + Request::create('/'), + new Store('test', new NullSessionHandler()), + static fn (string $table): array => Schema::getColumnListing($table), + ), + new ProductDtoAssemblerService(new EloquentProductRepository()), + ); + }; + + it('filters by publishedOnly and starOnly and returns ProductDto when withPricing is false', function () use ( + $createRange, + $createProduct, + $createQuery, + ): void { + // GIVEN + $range = $createRange(); + $pubStar = $createProduct('Pub Star', $range, status: true, star: true); + $pubNoStar = $createProduct('Pub NoStar', $range, status: true, star: false); + $unpubStar = $createProduct('Unpub Star', $range, status: false, star: true); + $unpubNoStar = $createProduct('Unpub NoStar', $range, status: false, star: false); + + $query = $createQuery(); + $pagination = Pagination::ofPage(new PageNumber(1), new PageSize(50)); + + // WHEN: publishedOnly = true + $publishedResult = $query(new GetPaginatedProductsQueryInput( + pagination: $pagination, + publishedOnly: true, + withPricing: false, + )); + + // THEN + $publishedIds = collect($publishedResult->items())->pluck('id')->all(); + expect($publishedResult->items()[0])->toBeInstanceOf(ProductDto::class) + ->and($publishedIds)->toContain($pubStar->id, $pubNoStar->id) + ->and($publishedIds)->not->toContain($unpubStar->id, $unpubNoStar->id); + + // WHEN: starOnly = true + $starResult = $query(new GetPaginatedProductsQueryInput( + pagination: $pagination, + starOnly: true, + withPricing: false, + )); + + // THEN + $starIds = collect($starResult->items())->pluck('id')->all(); + expect($starIds)->toContain($pubStar->id, $unpubStar->id) + ->and($starIds)->not->toContain($pubNoStar->id, $unpubNoStar->id); + }); + + it('returns ProductWithPricingDto with discount calculation when withPricing is true', function () use ( + $createRange, + $createProduct, + $createQuery, + ): void { + // GIVEN + CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-06-15 12:00:00')); + + $discount = new Discount(); + $discount->type = DiscountType::PERCENT; + $discount->value = DiscountValue::fromPercentage(20); + $discount->is_old_price_displayed = true; + $discount->save(); + + $range = $createRange(); + $product = $createProduct('Discounted', $range, status: true, star: false, discountId: $discount->id); + + $query = $createQuery(); + + // WHEN + $result = $query(new GetPaginatedProductsQueryInput( + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(50)), + publishedOnly: true, + withPricing: true, + )); + + // THEN + /** @var ProductWithPricingDto|null $dto */ + $dto = collect($result->items())->first( + static fn (ProductDto | ProductWithPricingDto $item): bool => $item instanceof ProductWithPricingDto + && $item->product->id === $product->id, + ); + + expect($dto)->toBeInstanceOf(ProductWithPricingDto::class) + ->and($dto?->pricing->hasDiscount)->toBeTrue() + ->and($dto?->pricing->discountedPriceHt->getAmount())->toBe('800'); + }); + + it('paginates results according to PageNumber and PageSize', function () use ( + $createRange, + $createProduct, + $createQuery, + ): void { + // GIVEN + $range = $createRange(); + $createProduct('Page Item 1', $range); + $createProduct('Page Item 2', $range); + $createProduct('Page Item 3', $range); + + $query = $createQuery(); + + // WHEN + $page1 = $query(new GetPaginatedProductsQueryInput( + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(2)), + )); + $page2 = $query(new GetPaginatedProductsQueryInput( + pagination: Pagination::ofPage(new PageNumber(2), new PageSize(2)), + )); + + // THEN + expect($page1->perPage())->toBe(2) + ->and($page1->currentPage())->toBe(1) + ->and(count($page1->items()))->toBe(2) + ->and($page2->currentPage())->toBe(2) + ->and(count($page2->items()))->toBeGreaterThanOrEqual(1); + }); + + it('rejects invalid input type', function () use ($createQuery): void { + // GIVEN + $query = $createQuery(); + + // WHEN / THEN + expect(static fn () => $query(QueryInputEmpty::create())) // @phpstan-ignore argument.type + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductWithPricingQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductWithPricingQueryTest.php new file mode 100644 index 00000000..2ad30406 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductWithPricingQueryTest.php @@ -0,0 +1,118 @@ +name = 'Gamme ' . uniqid(); + $range->status = true; + $range->order = random_int(1, 9999); + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + return $range; + }; + + $createQuery = function (): GetProductWithPricingQuery { + return new GetProductWithPricingQuery( + new ProductDtoAssemblerService(new EloquentProductRepository()), + ); + }; + + it('resolves product by Slug and ProductId with validDiscount pricing', function () use ( + $createRange, + $createQuery, + ): void { + // GIVEN + CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-06-15 12:00:00')); + + $discount = new Discount(); + $discount->type = DiscountType::PERCENT; + $discount->value = DiscountValue::fromPercentage(25); + $discount->is_old_price_displayed = true; + $discount->save(); + + $range = $createRange(); + + $product = new Product([ + 'range_id' => $range->id, + 'name' => 'Produit Test ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Description test', + 'status' => true, + 'picture_alt' => 'alt', + 'picture_title' => 'title', + 'picture_large_alt' => 'alt', + 'picture_large_title' => 'title', + ]); + $product->order = random_int(1, 999999); + $product->price = Money::EUR(2000); + $product->discount_id = $discount->id; + $product->save(); + + $query = $createQuery(); + + // WHEN: by Slug + $bySlug = $query(new GetProductQueryInput(new Slug($product->slug))); + + // THEN + expect($bySlug)->toBeInstanceOf(ProductWithPricingDto::class) + ->and($bySlug?->product->id)->toBe($product->id) + ->and($bySlug?->pricing->hasDiscount)->toBeTrue() + ->and($bySlug?->pricing->discountedPriceHt->getAmount())->toBe('1500'); + + // WHEN: by ProductId + $byId = $query(new GetProductQueryInput(new ProductId(Uuid::fromString($product->id)))); + + // THEN + expect($byId)->toBeInstanceOf(ProductWithPricingDto::class) + ->and($byId?->product->id)->toBe($product->id) + ->and($byId?->pricing->discountedPriceHt->getAmount())->toBe('1500'); + }); + + it('returns null when product is not found by Slug or ProductId', function () use ($createQuery): void { + // GIVEN + $query = $createQuery(); + + // WHEN + $bySlug = $query(new GetProductQueryInput(new Slug('non-existent-slug-' . uniqid()))); + $byId = $query(new GetProductQueryInput(new ProductId(Uuid::uuid7()))); + + // THEN + expect($bySlug)->toBeNull() + ->and($byId)->toBeNull(); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Timeslots/GetAvailableTimeslotsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Timeslots/GetAvailableTimeslotsQueryTest.php new file mode 100644 index 00000000..3e81c75d --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/Timeslots/GetAvailableTimeslotsQueryTest.php @@ -0,0 +1,134 @@ +timeslotList)->toBe([]); + }); + + it('returns available PickupTimeSlot instances up to 28 days for an active shop', function (): void { + // GIVEN + $now = CarbonImmutable::parse('2026-06-15 10:00:00'); + CarbonImmutable::setTestNow($now); + + $shop = new Shop(); + $shop->name = 'Boutique Active'; + $shop->address = '10 rue Principale'; + $shop->postcode = '75001'; + $shop->city = 'Paris'; + $shop->default = true; + $shop->save(); + + $query = new GetAvailableTimeslotsQuery( + new PickupSchedulingService(new EloquentPickupExceptionRepository()), + new EloquentShopRepository(), + ); + $input = new GetAvailableTimeslotsQueryInput(new ShopId(Uuid::fromString($shop->id))); + + // WHEN + $result = $query($input); + + // THEN + $maxDate = $now->addDays(28); + expect($result->timeslotList)->not->toBeEmpty(); + + foreach ($result->timeslotList as $slot) { + expect($slot->getAt()->getTimestamp())->toBeLessThanOrEqual($maxDate->getTimestamp()); + } + }); + + it('respects pickup exceptions attached to the shop', function (): void { + // GIVEN + CarbonImmutable::setTestNow('2026-06-15 10:00:00'); + + $shop = new Shop(); + $shop->name = 'Boutique Exception'; + $shop->address = '10 rue Principale'; + $shop->postcode = '75001'; + $shop->city = 'Paris'; + $shop->default = true; + $shop->save(); + + $exception = new PickupException(); + $exception->date = Carbon::parse('2026-06-19'); + $exception->label = 'Fermeture exceptionnelle'; + $exception->repeatable = false; + $exception->repeat_frequency = RepeatFrequency::YEARLY; + $exception->auto_updated = false; + $exception->save(); + + $shop->pickupExceptions()->attach($exception->id, [ + 'replacement_date' => '2026-06-20', + 'order_deadline_at' => '2026-06-18 12:00:00', + ]); + + $query = new GetAvailableTimeslotsQuery( + new PickupSchedulingService(new EloquentPickupExceptionRepository()), + new EloquentShopRepository(), + ); + $input = new GetAvailableTimeslotsQueryInput(new ShopId(Uuid::fromString($shop->id))); + + // WHEN + $result = $query($input); + + // THEN + $dates = array_map( + static fn (PickupTimeSlot $slot): string => $slot->getAt()->format('Y-m-d'), + $result->timeslotList, + ); + + expect($dates)->not->toContain('2026-06-19') + ->and($dates)->toContain('2026-06-20'); + }); + + it('throws InvalidArgumentException when invalid input is passed', function (): void { + // GIVEN + $query = new GetAvailableTimeslotsQuery( + new PickupSchedulingService(new EloquentPickupExceptionRepository()), + new EloquentShopRepository(), + ); + $invalidInput = new class () implements QueryInput + { + }; + + // WHEN & THEN + expect( + /** @phpstan-ignore argument.type */ + fn () => $query($invalidInput) + )->toThrow(\InvalidArgumentException::class); + }); +}); From 3aaec0a6dbba9efd1846cab31e790aed4a84f02e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 16:53:21 +0100 Subject: [PATCH 153/183] test(coverage): cover post-commit Listeners and AppSessionService (Lot 7B) --- .../CustomerPasswordUpdatedListenerTest.php | 27 +++++ .../Orders/SendAdminOrderConfirmationTest.php | 87 ++++++++++++++++ .../SendCustomerOrderConfirmationTest.php | 98 +++++++++++++++++++ .../Services/AppSessionServiceTest.php | 75 ++++++++++++++ 4 files changed, 287 insertions(+) create mode 100644 tests/Feature/App/Listeners/CustomerPasswordUpdatedListenerTest.php create mode 100644 tests/Feature/App/Listeners/Orders/SendAdminOrderConfirmationTest.php create mode 100644 tests/Feature/App/Listeners/Orders/SendCustomerOrderConfirmationTest.php create mode 100644 tests/Integration/WithApp/Infra/Adapters/Services/AppSessionServiceTest.php diff --git a/tests/Feature/App/Listeners/CustomerPasswordUpdatedListenerTest.php b/tests/Feature/App/Listeners/CustomerPasswordUpdatedListenerTest.php new file mode 100644 index 00000000..bed6ab49 --- /dev/null +++ b/tests/Feature/App/Listeners/CustomerPasswordUpdatedListenerTest.php @@ -0,0 +1,27 @@ +handle($event); + + // THEN + Mail::assertQueued( + CustomerPasswordHasReset::class, + static fn (CustomerPasswordHasReset $mail): bool => $mail->hasTo('reset@example.com'), + ); +}); diff --git a/tests/Feature/App/Listeners/Orders/SendAdminOrderConfirmationTest.php b/tests/Feature/App/Listeners/Orders/SendAdminOrderConfirmationTest.php new file mode 100644 index 00000000..b5ba7690 --- /dev/null +++ b/tests/Feature/App/Listeners/Orders/SendAdminOrderConfirmationTest.php @@ -0,0 +1,87 @@ + new SendAdminOrderConfirmation()) + ->toThrow(\UnexpectedValueException::class); +}); + +it('queues OrderConfirmAdminMail to configured contact email when AnOrderHasBeenPlaced is handled', function (): void { + // GIVEN + Mail::fake(); + Config::set('mail.to.contact', 'contact@example.com'); + $listener = new SendAdminOrderConfirmation(); + $event = makeOrderPlacedEvent(); + + // WHEN + $listener->handle($event); + + // THEN + Mail::assertQueued( + OrderConfirmAdminMail::class, + static fn (OrderConfirmAdminMail $mail): bool => $mail->hasTo('contact@example.com'), + ); +}); diff --git a/tests/Feature/App/Listeners/Orders/SendCustomerOrderConfirmationTest.php b/tests/Feature/App/Listeners/Orders/SendCustomerOrderConfirmationTest.php new file mode 100644 index 00000000..68a51780 --- /dev/null +++ b/tests/Feature/App/Listeners/Orders/SendCustomerOrderConfirmationTest.php @@ -0,0 +1,98 @@ +matricule = new Matricule('1234567'); + $employee->nom = 'Dupont'; + $employee->prenom = 'Jean'; + $employee->etablissement = new ShopperEstablishmentCode('FAC01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('101'); + $employee->code = new Code('ABCD2345'); + $employee->saveOrFail(); + + $listener = new SendCustomerOrderConfirmation(); + $event = makeCustomerOrderPlacedEvent('1234567'); + + // WHEN + $listener->handle($event); + + // THEN + Notification::assertSentTo($employee, OrderConfirmed::class); +}); + +it('sends nothing when no matching Employee exists', function (): void { + // GIVEN + Notification::fake(); + $listener = new SendCustomerOrderConfirmation(); + $event = makeCustomerOrderPlacedEvent('9999999'); + + // WHEN + $listener->handle($event); + + // THEN + Notification::assertNothingSent(); +}); diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/AppSessionServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/AppSessionServiceTest.php new file mode 100644 index 00000000..495d1a8b --- /dev/null +++ b/tests/Integration/WithApp/Infra/Adapters/Services/AppSessionServiceTest.php @@ -0,0 +1,75 @@ +get(); + + // THEN + expect(UuidHelper::isV7($sessionId->value))->toBeTrue() + ->and(Session::has($sessionKey))->toBeTrue() + ->and(Session::get($sessionKey))->toBe($sessionId->value->toString()); + }); + + it('returns the exact same SessionId on subsequent get calls without overwriting the session value', function (): void { + // GIVEN + $sessionKey = 'test_session_id'; + Session::forget($sessionKey); + $service = new AppSessionService($sessionKey); + + // WHEN + $first = $service->get(); + $second = $service->get(); + + // THEN + expect($second->value->toString())->toBe($first->value->toString()) + ->and(Session::get($sessionKey))->toBe($first->value->toString()); + }); + + it('hydrates an existing UUID string already stored in Session under the configured key', function (): void { + // GIVEN + $sessionKey = 'test_session_id'; + $existingUuid = Uuid::uuid7()->toString(); + Session::put($sessionKey, $existingUuid); + $service = new AppSessionService($sessionKey); + + // WHEN + $sessionId = $service->get(); + + // THEN + expect($sessionId->value->toString())->toBe($existingUuid) + ->and(Session::get($sessionKey))->toBe($existingUuid); + }); + + it('keeps separate AppSessionService instances with distinct session keys isolated', function (): void { + // GIVEN + $firstKey = 'first_session_id'; + $secondKey = 'second_session_id'; + Session::forget([$firstKey, $secondKey]); + $firstService = new AppSessionService($firstKey); + $secondService = new AppSessionService($secondKey); + + // WHEN + $firstId = $firstService->get(); + $secondId = $secondService->get(); + + // THEN + expect($firstId->value->toString())->not->toBe($secondId->value->toString()) + ->and(Session::get($firstKey))->toBe($firstId->value->toString()) + ->and(Session::get($secondKey))->toBe($secondId->value->toString()); + }); +}); From cdc04d01041e7d63545ef6c8979a94bd023d5aef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 17:01:12 +0100 Subject: [PATCH 154/183] test(coverage): cover Arcadia jobs and employee service, add describe blocks (Lot 7C) --- .../FetchAndUpsertArcadiaEmployeesTest.php | 90 +++++++ .../FetchAndUpsertArcadiaProductIncosTest.php | 129 +++++++++ .../CustomerPasswordUpdatedListenerTest.php | 26 +- .../Orders/SendAdminOrderConfirmationTest.php | 48 ++-- .../SendCustomerOrderConfirmationTest.php | 64 ++--- .../Services/ArcadiaEmployeeServiceTest.php | 244 ++++++++++++++++++ 6 files changed, 535 insertions(+), 66 deletions(-) create mode 100644 tests/Feature/App/Jobs/FetchAndUpsertArcadiaEmployeesTest.php create mode 100644 tests/Feature/App/Jobs/FetchAndUpsertArcadiaProductIncosTest.php create mode 100644 tests/Integration/WithApp/App/Services/ArcadiaEmployeeServiceTest.php diff --git a/tests/Feature/App/Jobs/FetchAndUpsertArcadiaEmployeesTest.php b/tests/Feature/App/Jobs/FetchAndUpsertArcadiaEmployeesTest.php new file mode 100644 index 00000000..305c3335 --- /dev/null +++ b/tests/Feature/App/Jobs/FetchAndUpsertArcadiaEmployeesTest.php @@ -0,0 +1,90 @@ +toHaveKeys([ShouldQueue::class, ShouldBeUnique::class]) + ->and($job->uniqueFor)->toBe(3600) + ->and($job->uniqueId())->toBe('fetch-and-upsert-arcadia-employees'); + }); + + it('executes SynchronizeEmployeesWithArcadiaApi via Executor in handle', function (): void { + // GIVEN + /** @var Executor&\Mockery\MockInterface $executor */ + $executor = \Mockery::mock(Executor::class); + /** @var EmployeeSyncService&\Mockery\MockInterface $syncService */ + $syncService = \Mockery::mock(EmployeeSyncService::class); + $action = new SynchronizeEmployeesWithArcadiaApi($syncService); + $job = new FetchAndUpsertArcadiaEmployees(); + + $executor->shouldReceive('execute') + ->once() + ->with($action, \Mockery::type(ActionInputEmpty::class)); + + // WHEN + $job->handle($executor, $action); + + // THEN + expect(\Mockery::getContainer()->mockery_getExpectationCount())->toBeGreaterThan(0); + }); + + it('synchronizes employees via dispatchSync using mocked ArcadiaEmployeeService', function (): void { + // GIVEN + $setting = Setting::getSingleton(); + $setting->employee_sites = ['PA']; + $setting->saveOrFail(); + + $arcadiaEmployee = new ArcadiaEmployee( + matricule: new Matricule('9123456'), + lastname: 'Martin', + firstname: 'Alice', + startDate: CarbonImmutable::parse('2026-01-01'), + endDate: null, + etablissement: new ShopperEstablishmentCode('01'), + site: new ShopperSiteCode('PA'), + service: new ShopperServiceCode('01'), + ); + + /** @var ArcadiaEmployeeService&\Mockery\MockInterface $arcadiaService */ + $arcadiaService = \Mockery::mock(ArcadiaEmployeeService::class); + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->once() + ->with(\Mockery::on(static fn (ShopperSiteCode $s): bool => $s->value === 'PA'), \Mockery::any()) + ->andReturn([$arcadiaEmployee]); + + app()->instance(ArcadiaEmployeeService::class, $arcadiaService); + + // WHEN + FetchAndUpsertArcadiaEmployees::dispatchSync(); + + // THEN + $employee = Employee::query()->where('matricule', '9123456')->first(); + expect($employee)->not->toBeNull() + ->and($employee?->nom)->toBe('Martin') + ->and($employee?->prenom)->toBe('Alice'); + }); +}); diff --git a/tests/Feature/App/Jobs/FetchAndUpsertArcadiaProductIncosTest.php b/tests/Feature/App/Jobs/FetchAndUpsertArcadiaProductIncosTest.php new file mode 100644 index 00000000..b0d55d3a --- /dev/null +++ b/tests/Feature/App/Jobs/FetchAndUpsertArcadiaProductIncosTest.php @@ -0,0 +1,129 @@ +toHaveKeys([ShouldQueue::class, ShouldBeUnique::class]) + ->and($job->uniqueFor)->toBe(3600) + ->and($job->uniqueId())->toBe('fetch-and-upsert-arcadia-product-incos'); + }); + + it('executes SynchronizeProductIncosWithArcadiaApi via Executor in handle', function (): void { + // GIVEN + /** @var Executor&\Mockery\MockInterface $executor */ + $executor = \Mockery::mock(Executor::class); + /** @var ArcadiaIncoService&\Mockery\MockInterface $arcadiaService */ + $arcadiaService = \Mockery::mock(ArcadiaIncoService::class); + $action = new SynchronizeProductIncosWithArcadiaApi($arcadiaService, new NullLogger()); + $job = new FetchAndUpsertArcadiaProductIncos(); + + $executor->shouldReceive('execute') + ->once() + ->with($action, \Mockery::type(ActionInputEmpty::class)) + ->andReturn(0); + + // WHEN + $job->handle($executor, $action); + + // THEN + expect(\Mockery::getContainer()->mockery_getExpectationCount())->toBeGreaterThan(0); + }); + + it('synchronizes product incos via dispatchSync using mocked ArcadiaIncoService', function (): void { + // GIVEN + $range = new Range(); + $range->name = 'Gamme ' . uniqid(); + $range->status = true; + $range->order = random_int(1, 9999); + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + $product = new Product([ + 'range_id' => $range->id, + 'name' => 'Produit ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Description test', + 'status' => true, + ]); + $product->order = random_int(1, 999999); + $product->price = Money::EUR(1000); + $product->short_description = 'Court'; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt'; + $product->picture_large_title = 'title'; + $product->save(); + + $inco = new ProductInco(); + $inco->product_id = (string) $product->id; + $inco->no_art = 1001; + $inco->ingredients = 'Anciens ingrédients'; + $inco->save(); + + $data = new ArcadiaIncoDataDto( + noArt: 1001, + name: 'P1', + libelle: 'Produit 1', + brand: 'LDC', + ingredients: '

Nouveaux ingrédients

', + preparation: null, + servings: null, + allergens: 'Gluten', + sellingArgument: null, + nutriscore: Nutriscore::A, + nutriscoreArgs: null, + nutrition: new NutritionalValues(refWeightG: 100.0, kj: 550.0), + ); + + /** @var ArcadiaIncoService&\Mockery\MockInterface $arcadiaService */ + $arcadiaService = \Mockery::mock(ArcadiaIncoService::class); + $arcadiaService->shouldReceive('fetchInco') + ->with(1001) + ->once() + ->andReturn($data); + + app()->instance(ArcadiaIncoService::class, $arcadiaService); + + // WHEN + FetchAndUpsertArcadiaProductIncos::dispatchSync(); + + // THEN + $fresh = ProductInco::query()->find($inco->id); + expect($fresh?->ingredients)->toBe('

Nouveaux ingrédients

') + ->and($fresh?->allergens)->toBe('Gluten') + ->and($fresh?->nutriscore)->toBe(Nutriscore::A); + }); +}); diff --git a/tests/Feature/App/Listeners/CustomerPasswordUpdatedListenerTest.php b/tests/Feature/App/Listeners/CustomerPasswordUpdatedListenerTest.php index bed6ab49..4748f61a 100644 --- a/tests/Feature/App/Listeners/CustomerPasswordUpdatedListenerTest.php +++ b/tests/Feature/App/Listeners/CustomerPasswordUpdatedListenerTest.php @@ -10,18 +10,20 @@ use App\Mail\CustomerPasswordHasReset; use Domain\Models\ValueObjects\Email; use Illuminate\Support\Facades\Mail; -it('queues CustomerPasswordHasReset mail to customer email when CustomerPasswordUpdated is handled', function (): void { - // GIVEN - Mail::fake(); - $listener = new CustomerPasswordUpdatedListener(); - $event = new CustomerPasswordUpdated(new Email('reset@example.com')); +describe('CustomerPasswordUpdatedListener', function (): void { + it('queues CustomerPasswordHasReset mail to customer email when CustomerPasswordUpdated is handled', function (): void { + // GIVEN + Mail::fake(); + $listener = new CustomerPasswordUpdatedListener(); + $event = new CustomerPasswordUpdated(new Email('reset@example.com')); - // WHEN - $listener->handle($event); + // WHEN + $listener->handle($event); - // THEN - Mail::assertQueued( - CustomerPasswordHasReset::class, - static fn (CustomerPasswordHasReset $mail): bool => $mail->hasTo('reset@example.com'), - ); + // THEN + Mail::assertQueued( + CustomerPasswordHasReset::class, + static fn (CustomerPasswordHasReset $mail): bool => $mail->hasTo('reset@example.com'), + ); + }); }); diff --git a/tests/Feature/App/Listeners/Orders/SendAdminOrderConfirmationTest.php b/tests/Feature/App/Listeners/Orders/SendAdminOrderConfirmationTest.php index b5ba7690..851ebcab 100644 --- a/tests/Feature/App/Listeners/Orders/SendAdminOrderConfirmationTest.php +++ b/tests/Feature/App/Listeners/Orders/SendAdminOrderConfirmationTest.php @@ -60,28 +60,30 @@ function makeOrderPlacedEvent(): AnOrderHasBeenPlaced ); } -it('throws UnexpectedValueException when mail.to.contact is missing', function (): void { - // GIVEN - Config::set('mail.to', []); +describe('SendAdminOrderConfirmation', function (): void { + it('throws UnexpectedValueException when mail.to.contact is missing', function (): void { + // GIVEN + Config::set('mail.to', []); - // WHEN / THEN - expect(static fn (): SendAdminOrderConfirmation => new SendAdminOrderConfirmation()) - ->toThrow(\UnexpectedValueException::class); -}); - -it('queues OrderConfirmAdminMail to configured contact email when AnOrderHasBeenPlaced is handled', function (): void { - // GIVEN - Mail::fake(); - Config::set('mail.to.contact', 'contact@example.com'); - $listener = new SendAdminOrderConfirmation(); - $event = makeOrderPlacedEvent(); - - // WHEN - $listener->handle($event); - - // THEN - Mail::assertQueued( - OrderConfirmAdminMail::class, - static fn (OrderConfirmAdminMail $mail): bool => $mail->hasTo('contact@example.com'), - ); + // WHEN / THEN + expect(static fn (): SendAdminOrderConfirmation => new SendAdminOrderConfirmation()) + ->toThrow(\UnexpectedValueException::class); + }); + + it('queues OrderConfirmAdminMail to configured contact email when AnOrderHasBeenPlaced is handled', function (): void { + // GIVEN + Mail::fake(); + Config::set('mail.to.contact', 'contact@example.com'); + $listener = new SendAdminOrderConfirmation(); + $event = makeOrderPlacedEvent(); + + // WHEN + $listener->handle($event); + + // THEN + Mail::assertQueued( + OrderConfirmAdminMail::class, + static fn (OrderConfirmAdminMail $mail): bool => $mail->hasTo('contact@example.com'), + ); + }); }); diff --git a/tests/Feature/App/Listeners/Orders/SendCustomerOrderConfirmationTest.php b/tests/Feature/App/Listeners/Orders/SendCustomerOrderConfirmationTest.php index 68a51780..750f93ea 100644 --- a/tests/Feature/App/Listeners/Orders/SendCustomerOrderConfirmationTest.php +++ b/tests/Feature/App/Listeners/Orders/SendCustomerOrderConfirmationTest.php @@ -61,38 +61,40 @@ function makeCustomerOrderPlacedEvent(string $matricule): AnOrderHasBeenPlaced ); } -it('sends OrderConfirmed notification when matching Employee exists', function (): void { - // GIVEN - Notification::fake(); - $employee = new Employee(); - $employee->matricule = new Matricule('1234567'); - $employee->nom = 'Dupont'; - $employee->prenom = 'Jean'; - $employee->etablissement = new ShopperEstablishmentCode('FAC01'); - $employee->site = new ShopperSiteCode('SITE'); - $employee->service = new ShopperServiceCode('101'); - $employee->code = new Code('ABCD2345'); - $employee->saveOrFail(); +describe('SendCustomerOrderConfirmation', function (): void { + it('sends OrderConfirmed notification when matching Employee exists', function (): void { + // GIVEN + Notification::fake(); + $employee = new Employee(); + $employee->matricule = new Matricule('1234567'); + $employee->nom = 'Dupont'; + $employee->prenom = 'Jean'; + $employee->etablissement = new ShopperEstablishmentCode('FAC01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('101'); + $employee->code = new Code('ABCD2345'); + $employee->saveOrFail(); - $listener = new SendCustomerOrderConfirmation(); - $event = makeCustomerOrderPlacedEvent('1234567'); + $listener = new SendCustomerOrderConfirmation(); + $event = makeCustomerOrderPlacedEvent('1234567'); - // WHEN - $listener->handle($event); + // WHEN + $listener->handle($event); - // THEN - Notification::assertSentTo($employee, OrderConfirmed::class); -}); - -it('sends nothing when no matching Employee exists', function (): void { - // GIVEN - Notification::fake(); - $listener = new SendCustomerOrderConfirmation(); - $event = makeCustomerOrderPlacedEvent('9999999'); - - // WHEN - $listener->handle($event); - - // THEN - Notification::assertNothingSent(); + // THEN + Notification::assertSentTo($employee, OrderConfirmed::class); + }); + + it('sends nothing when no matching Employee exists', function (): void { + // GIVEN + Notification::fake(); + $listener = new SendCustomerOrderConfirmation(); + $event = makeCustomerOrderPlacedEvent('9999999'); + + // WHEN + $listener->handle($event); + + // THEN + Notification::assertNothingSent(); + }); }); diff --git a/tests/Integration/WithApp/App/Services/ArcadiaEmployeeServiceTest.php b/tests/Integration/WithApp/App/Services/ArcadiaEmployeeServiceTest.php new file mode 100644 index 00000000..a416368b --- /dev/null +++ b/tests/Integration/WithApp/App/Services/ArcadiaEmployeeServiceTest.php @@ -0,0 +1,244 @@ +shouldReceive('debug')->twice(); + + $site = new ShopperSiteCode('LDCSER'); + $since = new \DateTimeImmutable('2025-01-01T00:00:00+00:00'); + + $libEmployee1 = makeLibEmployee( + matricule: '12345678', + lastname: 'DUPONT', + firstname: 'Jean', + startDate: '2024-01-15T00:00:00+00:00', + endDate: '2025-12-31T00:00:00+00:00', + establishment: '0100', + site: 'LDCSER', + service: '097', + ); + $libEmployee2 = makeLibEmployee( + matricule: '87654321', + lastname: 'MARTIN', + firstname: 'Claire', + startDate: '2023-06-01T00:00:00+00:00', + endDate: null, + establishment: '0200', + site: 'LDCSER', + service: '105', + ); + + $stream = new StreamOf( + static fn (): PageOf => new PageOf( + new PaginationDto(page: 1, pageSize: 100, totalItems: 2, totalPages: 1), + [$libEmployee1, $libEmployee2], + ), + new LibPageSize(100), + ); + + $employeeService->shouldReceive('streamAllOfSitesSince') + ->once() + ->withArgs( + static fn (LibSiteId $sites, \DateTimeInterface $passedSince, LibPageSize $pageSize): bool => $sites->value === 'LDCSER' + && $pageSize->value === 100 + && $passedSince === $since + ) + ->andReturn($stream); + + $service = new ArcadiaEmployeeService($employeeService, $logger); + + // WHEN + $result = $service->getEmployeesOfSiteSince($site, $since); + + // THEN + expect($result)->toBeArray()->toHaveCount(2); + + /** @var array $result */ + expect($result[0]->matricule)->toEqual(new Matricule('12345678')) + ->and($result[0]->lastname)->toBe('DUPONT') + ->and($result[0]->firstname)->toBe('Jean') + ->and($result[0]->startDate->format(\DATE_ATOM))->toBe('2024-01-15T00:00:00+00:00') + ->and($result[0]->endDate?->format(\DATE_ATOM))->toBe('2025-12-31T00:00:00+00:00') + ->and($result[0]->etablissement)->toEqual(new ShopperEstablishmentCode('0100')) + ->and($result[0]->site)->toEqual(new ShopperSiteCode('LDCSER')) + ->and($result[0]->service)->toEqual(new ShopperServiceCode('097')) + ->and($result[1]->matricule)->toEqual(new Matricule('87654321')) + ->and($result[1]->lastname)->toBe('MARTIN') + ->and($result[1]->firstname)->toBe('Claire') + ->and($result[1]->startDate->format(\DATE_ATOM))->toBe('2023-06-01T00:00:00+00:00') + ->and($result[1]->endDate)->toBeNull() + ->and($result[1]->etablissement)->toEqual(new ShopperEstablishmentCode('0200')) + ->and($result[1]->site)->toEqual(new ShopperSiteCode('LDCSER')) + ->and($result[1]->service)->toEqual(new ShopperServiceCode('105')); + }); + + it('logs error and returns false when stream returns an ApiError', function (): void { + // GIVEN + $employeeService = \Mockery::mock(LibEmployeeService::class); + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldReceive('debug')->twice(); + $logger->shouldReceive('error')->once(); + + $apiError = \Mockery::mock(ApiError::class); + $apiError->shouldReceive('message')->andReturn('Gateway Timeout'); + + $stream = new StreamOf( + static fn (): ApiError => $apiError, + new LibPageSize(100), + ); + + $employeeService->shouldReceive('streamAllOfSitesSince') + ->once() + ->andReturn($stream); + + $service = new ArcadiaEmployeeService($employeeService, $logger); + + // WHEN + $result = $service->getEmployeesOfSiteSince( + new ShopperSiteCode('LDCSER'), + new \DateTimeImmutable('2025-01-01T00:00:00+00:00'), + ); + + // THEN + expect($result)->toBeFalse(); + }); + }); + + describe('employeeExists()', function (): void { + it('returns mapped ArcadiaEmployee when findBy returns LibEmployee', function (): void { + // GIVEN + $employeeService = \Mockery::mock(LibEmployeeService::class); + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldReceive('debug')->once(); + + $libEmployee = makeLibEmployee( + matricule: '12345678', + lastname: 'DUPONT', + firstname: 'Jean', + startDate: '2024-01-15T00:00:00+00:00', + endDate: null, + establishment: '0100', + site: 'LDCSER', + service: '097', + ); + + $employeeService->shouldReceive('findBy') + ->once() + ->withArgs(static fn (LibArcadiaEmployeeId $id): bool => $id->value === '12345678') + ->andReturn($libEmployee); + + $service = new ArcadiaEmployeeService($employeeService, $logger); + + // WHEN + $result = $service->employeeExists(new Matricule('12345678')); + + // THEN + expect($result)->toBeInstanceOf(ArcadiaEmployee::class); + assert($result instanceof ArcadiaEmployee); + + expect($result->matricule)->toEqual(new Matricule('12345678')) + ->and($result->lastname)->toBe('DUPONT') + ->and($result->firstname)->toBe('Jean') + ->and($result->endDate)->toBeNull() + ->and($result->etablissement)->toEqual(new ShopperEstablishmentCode('0100')) + ->and($result->site)->toEqual(new ShopperSiteCode('LDCSER')) + ->and($result->service)->toEqual(new ShopperServiceCode('097')); + }); + + it('returns null when findBy returns null', function (): void { + // GIVEN + $employeeService = \Mockery::mock(LibEmployeeService::class); + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldReceive('debug')->twice(); + + $employeeService->shouldReceive('findBy') + ->once() + ->withArgs(static fn (LibArcadiaEmployeeId $id): bool => $id->value === '12345678') + ->andReturnNull(); + + $service = new ArcadiaEmployeeService($employeeService, $logger); + + // WHEN + $result = $service->employeeExists(new Matricule('12345678')); + + // THEN + expect($result)->toBeNull(); + }); + + it('logs error and returns false when findBy returns an ApiError', function (): void { + // GIVEN + $employeeService = \Mockery::mock(LibEmployeeService::class); + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldReceive('debug')->once(); + $logger->shouldReceive('error')->once(); + + $apiError = \Mockery::mock(ApiError::class); + $apiError->shouldReceive('message')->andReturn('Internal Server Error'); + + $employeeService->shouldReceive('findBy') + ->once() + ->withArgs(static fn (LibArcadiaEmployeeId $id): bool => $id->value === '12345678') + ->andReturn($apiError); + + $service = new ArcadiaEmployeeService($employeeService, $logger); + + // WHEN + $result = $service->employeeExists(new Matricule('12345678')); + + // THEN + expect($result)->toBeFalse(); + }); + }); +}); From 8ffe04c388447d8ec9472f6ba479a0db680584f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 17:08:29 +0100 Subject: [PATCH 155/183] ci: add AWS_DEFAULT_REGION variable for phpstan --- .gitlab-ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index d3a74b38..a8474213 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -79,6 +79,7 @@ phpstan: variables: PHP_MEMORY_LIMIT: "512M" COMPOSER_CACHE_DIR: ".composer-cache" + AWS_DEFAULT_REGION: "us-east-1" script: - php -d memory_limit=512M vendor/bin/phpstan --error-format=junit > phpstan-report.xml artifacts: From 0fb5a25a4a9b9fd81cd53fd53b79beaaf7168e58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 17:12:54 +0100 Subject: [PATCH 156/183] ci: update phpstan configuration to copy .env.example This change ensures that the .env file is created from the example before running phpstan, allowing for proper environment setup. --- .gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index a8474213..006abb7c 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -79,8 +79,8 @@ phpstan: variables: PHP_MEMORY_LIMIT: "512M" COMPOSER_CACHE_DIR: ".composer-cache" - AWS_DEFAULT_REGION: "us-east-1" script: + - cp .env.example .env - php -d memory_limit=512M vendor/bin/phpstan --error-format=junit > phpstan-report.xml artifacts: when: on_failure From 45fc35b1f7b162836a51856007486ab4968e58f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 18:34:07 +0100 Subject: [PATCH 157/183] fix(products): query published associated products in pivot order on FO product page --- .../GetPublishedAssociatedProductsQuery.php | 54 +++++++ ...tPublishedAssociatedProductsQueryInput.php | 16 ++ .../GetPublishedProductWithPricingQuery.php | 2 +- .../Fo/Pages/ProductsController.php | 18 ++- .../Fo/Pages/ProductsControllerTest.php | 50 +++++- ...etPublishedAssociatedProductsQueryTest.php | 150 ++++++++++++++++++ 6 files changed, 275 insertions(+), 15 deletions(-) create mode 100644 app/Cqs/Queries/Products/GetPublishedAssociatedProductsQuery.php create mode 100644 app/Cqs/Queries/Products/GetPublishedAssociatedProductsQueryInput.php create mode 100644 tests/Integration/WithApp/App/Cqs/Queries/Products/GetPublishedAssociatedProductsQueryTest.php diff --git a/app/Cqs/Queries/Products/GetPublishedAssociatedProductsQuery.php b/app/Cqs/Queries/Products/GetPublishedAssociatedProductsQuery.php new file mode 100644 index 00000000..82179eb8 --- /dev/null +++ b/app/Cqs/Queries/Products/GetPublishedAssociatedProductsQuery.php @@ -0,0 +1,54 @@ + + * > + */ +final readonly class GetPublishedAssociatedProductsQuery implements Query +{ + public function __construct( + private ProductDtoAssemblerService $assembler, + ) { + } + + /** + * @param \App\Cqs\Queries\Products\GetPublishedAssociatedProductsQueryInput $input + * @return list<\App\Dto\ProductWithPricingDto> + */ + #[\Override] + public function __invoke(QueryInput $input): array + { + Assert::isAOf($input, GetPublishedAssociatedProductsQueryInput::class); + + $product = Product::query() + ->where('slug', $input->slug->value) + ->published() + ->first(); + + if ($product === null) { + return []; + } + + $associated = $product->products() + ->where('products.status', true) + ->whereKeyNot($product->getKey()) + ->with(['inco', 'validDiscount']) + ->get(); + + return $this->assembler->toDtosWithPricing($associated); + } +} diff --git a/app/Cqs/Queries/Products/GetPublishedAssociatedProductsQueryInput.php b/app/Cqs/Queries/Products/GetPublishedAssociatedProductsQueryInput.php new file mode 100644 index 00000000..9890fbd1 --- /dev/null +++ b/app/Cqs/Queries/Products/GetPublishedAssociatedProductsQueryInput.php @@ -0,0 +1,16 @@ +with(['inco', 'validDiscount', 'range', 'products']) + ->with(['inco', 'validDiscount', 'range']) ->where('slug', $input->slug->value) ->published() ->first(); diff --git a/app/Http/Controllers/Fo/Pages/ProductsController.php b/app/Http/Controllers/Fo/Pages/ProductsController.php index 6573d5c1..64c55dcf 100644 --- a/app/Http/Controllers/Fo/Pages/ProductsController.php +++ b/app/Http/Controllers/Fo/Pages/ProductsController.php @@ -7,11 +7,12 @@ namespace App\Http\Controllers\Fo\Pages; use App\Contracts\Executor; use App\Cqs\Queries\Products\GetFoProductIndexPageQuery; use App\Cqs\Queries\Products\GetFoProductIndexPageQueryInput; -use App\Cqs\Queries\Products\GetPaginatedProductsQuery; -use App\Cqs\Queries\Products\GetPaginatedProductsQueryInput; +use App\Cqs\Queries\Products\GetPublishedAssociatedProductsQuery; +use App\Cqs\Queries\Products\GetPublishedAssociatedProductsQueryInput; use App\Dto\ProductWithPricingDto; use App\Http\Controllers\Controller; use App\Http\Resources\Fo\Ajax\FilteredProductResource; +use Domain\Models\ValueObjects\Slug; use Illuminate\Contracts\View\View; use Illuminate\Http\Request; use Shared\Pagination\PageSize; @@ -48,16 +49,17 @@ class ProductsController extends Controller ]); } - public function view(Request $request, ProductWithPricingDto $productWithPricing, GetPaginatedProductsQuery $query): View - { + public function view( + Request $request, + ProductWithPricingDto $productWithPricing, + GetPublishedAssociatedProductsQuery $query, + ): View { $this->authorize('viewPublished', $productWithPricing); $associated = $this->executor->execute( $query, - new GetPaginatedProductsQueryInput( - pagination: Pagination::firstPage(new PageSize(self::PER_PAGE_PRODUCTS)), - publishedOnly: true, - withPricing: true, + new GetPublishedAssociatedProductsQueryInput( + slug: new Slug($productWithPricing->product->slug), ), ); diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/ProductsControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/ProductsControllerTest.php index 443281fe..41b1488a 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/ProductsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/ProductsControllerTest.php @@ -77,15 +77,26 @@ describe('ProductsController', function () { $response->assertStatus(200); }); - it('excludes unpublished products from associated products on GET /produit/{slug}', function () use ($createProduct): void { + it('shows only published associated products in pivot order on GET /produit/{slug}', function () use ( + $createProduct, + ): void { // GIVEN seed(ContentSeeder::class); $pages = Page::getCached()->mapWithKeys(fn (Page $page) => [$page->slug->value() => $page]); View::share('PageList', $pages); - $viewedProduct = $createProduct('Produit Affiché', true, 1); - $draftProduct = $createProduct('Produit Brouillon Secret', false, 2); - $publishedOther = $createProduct('Produit Associé Publié', true, 3); + $viewedProduct = $createProduct('Produit Affiché', true, 1); + $draftAssociated = $createProduct('Produit Associé Brouillon', false, 2); + $associatedSecond = $createProduct('Produit Associé Deuxième', true, 3); + $associatedFirst = $createProduct('Produit Associé Premier', true, 4); + $publishedUnrelated = $createProduct('Produit Publié Non Associé', true, 5); + + $viewedProduct->products()->attach([ + $associatedSecond->id => ['sort_order' => 2], + $associatedFirst->id => ['sort_order' => 1], + $draftAssociated->id => ['sort_order' => 0], + $viewedProduct->id => ['sort_order' => 3], + ]); // WHEN $response = get("/produit/{$viewedProduct->slug}"); @@ -96,8 +107,35 @@ describe('ProductsController', function () { $associated = $response->viewData('associatedProducts'); $associatedNames = array_column($associated, 'name'); - expect($associatedNames)->toContain($publishedOther->name) - ->and($associatedNames)->not->toContain($draftProduct->name); + expect($associatedNames)->toBe([ + $associatedFirst->name, + $associatedSecond->name, + ]) + ->and($associatedNames)->not->toContain($draftAssociated->name) + ->and($associatedNames)->not->toContain($publishedUnrelated->name) + ->and($associatedNames)->not->toContain($viewedProduct->name); + }); + + it('returns empty associated products when none are attached on GET /produit/{slug}', function () use ($createProduct): void { + // GIVEN + seed(ContentSeeder::class); + $pages = Page::getCached()->mapWithKeys(fn (Page $page) => [$page->slug->value() => $page]); + View::share('PageList', $pages); + + $viewedProduct = $createProduct('Produit Sans Associés', true, 1); + $publishedUnrelated = $createProduct('Autre Produit Publié', true, 2); + + // WHEN + $response = get("/produit/{$viewedProduct->slug}"); + + // THEN + $response->assertStatus(200) + ->assertDontSee($publishedUnrelated->name, false) + ->assertDontSee('class="associated-products"', false); + + /** @var array> $associated */ + $associated = $response->viewData('associatedProducts'); + expect($associated)->toBe([]); }); it('renders published products and excludes unpublished products on GET /produits', function () use ($createProduct): void { diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Products/GetPublishedAssociatedProductsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetPublishedAssociatedProductsQueryTest.php new file mode 100644 index 00000000..3b40cf00 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetPublishedAssociatedProductsQueryTest.php @@ -0,0 +1,150 @@ +name = 'Gamme ' . uniqid(); + $range->status = true; + $range->order = random_int(1, 9999); + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + return $range; + }; + + $createProduct = static function ( + string $name, + Range $range, + int $order, + bool $status = true, + ): Product { + $product = new Product([ + 'range_id' => $range->id, + 'name' => $name, + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Description test', + 'status' => $status, + 'picture_alt' => 'alt', + 'picture_title' => 'title', + 'picture_large_alt' => 'alt', + 'picture_large_title' => 'title', + ]); + $product->order = $order; + $product->price = Money::EUR(1200); + $product->save(); + + return $product; + }; + + $createQuery = static fn (): GetPublishedAssociatedProductsQuery => new GetPublishedAssociatedProductsQuery( + new ProductDtoAssemblerService(new EloquentProductRepository()), + ); + + it('returns published associated products ordered by pivot sort_order excluding drafts, self, and unassociated products', function () use ( + $createRange, + $createProduct, + $createQuery, + ): void { + // GIVEN + $range = $createRange(); + $source = $createProduct('Produit Source', $range, 1, true); + $associatedSecond = $createProduct('Associé Deuxième', $range, 2, true); + $associatedFirst = $createProduct('Associé Premier', $range, 3, true); + $associatedDraft = $createProduct('Associé Brouillon', $range, 4, false); + $unassociated = $createProduct('Produit Non Associé', $range, 5, true); + + $source->products()->attach([ + $associatedSecond->id => ['sort_order' => 2], + $associatedFirst->id => ['sort_order' => 1], + $associatedDraft->id => ['sort_order' => 0], + $source->id => ['sort_order' => 3], + ]); + + // WHEN + $result = $createQuery()(new GetPublishedAssociatedProductsQueryInput( + slug: new Slug((string) $source->slug), + )); + + // THEN + expect($result)->toHaveCount(2) + ->and($result)->each->toBeInstanceOf(ProductWithPricingDto::class); + + $names = array_map(static fn (ProductWithPricingDto $dto): string => $dto->product->name, $result); + + expect($names)->toBe(['Associé Premier', 'Associé Deuxième']) + ->and($names)->not->toContain($associatedDraft->name) + ->and($names)->not->toContain($unassociated->name) + ->and($names)->not->toContain($source->name); + }); + + it('returns all published associated products without arbitrary limit', function () use ( + $createRange, + $createProduct, + $createQuery, + ): void { + // GIVEN + $range = $createRange(); + $source = $createProduct('Produit Source Complet', $range, 1, true); + + $attachments = []; + for ($i = 1; $i <= 8; $i++) { + $associated = $createProduct("Associé {$i}", $range, $i + 1, true); + $attachments[$associated->id] = ['sort_order' => $i]; + } + $source->products()->attach($attachments); + + // WHEN + $result = $createQuery()(new GetPublishedAssociatedProductsQueryInput( + slug: new Slug((string) $source->slug), + )); + + // THEN + expect($result)->toHaveCount(8); + }); + + it('returns an empty list for an unknown or unpublished product slug', function () use ( + $createRange, + $createProduct, + $createQuery, + ): void { + // GIVEN + $range = $createRange(); + $draft = $createProduct('Produit Brouillon', $range, 1, false); + $associated = $createProduct('Associé Publié', $range, 2, true); + $draft->products()->attach($associated->id, ['sort_order' => 1]); + + $query = $createQuery(); + + // WHEN + $forDraft = $query(new GetPublishedAssociatedProductsQueryInput(new Slug((string) $draft->slug))); + $forUnknown = $query(new GetPublishedAssociatedProductsQueryInput(new Slug('slug-inexistant'))); + + // THEN + expect($forDraft)->toBe([]) + ->and($forUnknown)->toBe([]); + }); +}); From 1f3d25d61a0ea195c187370644d9a8606bb36ff7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 18:34:08 +0100 Subject: [PATCH 158/183] fix(ci,tests): resolve PHPStan CI failures with .env.example and Intelephense warnings --- .gitlab-ci.yml | 3 +++ .../App/Http/Controllers/Bo/EmployeesControllerTest.php | 3 ++- .../Controllers/Fo/Auth/ResetPasswordControllerTest.php | 8 ++++---- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 006abb7c..275cf3db 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -79,6 +79,9 @@ phpstan: variables: PHP_MEMORY_LIMIT: "512M" COMPOSER_CACHE_DIR: ".composer-cache" + CRM_ENDPOINT: "http://fake-url.com" + CRM_TOKEN: "fake-token" + CRM_PASSWORD: "fake-password" script: - cp .env.example .env - php -d memory_limit=512M vendor/bin/phpstan --error-format=junit > phpstan-report.xml diff --git a/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php index e4ed6d46..f1e60699 100644 --- a/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php @@ -7,6 +7,7 @@ namespace Tests\Feature\App\Http\Controllers\Bo; use App\Jobs\FetchAndUpsertArcadiaEmployees; use App\Models\User; use Domain\Enums\UserRole; +use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Queue; use function Pest\Laravel\actingAs; @@ -42,7 +43,7 @@ describe('EmployeesController', function (): void { it('redirects unauthenticated users to login', function (): void { // GIVEN - auth()->guard('backend')->logout(); + Auth::guard('backend')->logout(); // WHEN $response = post('/bo/settings/employees/sync'); diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php index 7e667f55..e79ec14c 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php @@ -114,7 +114,7 @@ describe('ResetPasswordController', function () { $crmService->shouldReceive('getCustomerFromEmail')->with('reset-null@example.com')->andReturn($crmCustomer); $crmService->shouldNotReceive('resetPasswordFor'); - $token = Password::broker('customers')->createToken($customer); + $token = Password::createToken($customer); $shopperService = \Mockery::mock(ShopperService::class); $shopperService->shouldReceive('getShopperFor') @@ -173,7 +173,7 @@ describe('ResetPasswordController', function () { $crmService->shouldReceive('getCustomerFromEmail')->with('reset-inactive@example.com')->andReturn($crmCustomer); $crmService->shouldNotReceive('resetPasswordFor'); - $token = Password::broker('customers')->createToken($customer); + $token = Password::createToken($customer); $shopper = new Shopper( id: clone $customer->getId(), @@ -252,7 +252,7 @@ describe('ResetPasswordController', function () { ->once() ->andReturn($crmCustomer); - $token = Password::broker('customers')->createToken($customer); + $token = Password::createToken($customer); $shopper = new Shopper( id: clone $customer->getId(), @@ -332,7 +332,7 @@ describe('ResetPasswordController', function () { ->once() ->andReturn($crmCustomer); - $token = Password::broker('customers')->createToken($customer); + $token = Password::createToken($customer); $shopper = new Shopper( id: clone $customer->getId(), From 392dcdc6c3778e4d722823a414ee7cfc7e0a88a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 18:34:08 +0100 Subject: [PATCH 159/183] fix(auth): validate forgot-password email through Email value object --- .../Fo/Auth/ForgotPasswordController.php | 18 ++++++++++++++++++ .../Fo/Auth/ForgotPasswordControllerTest.php | 17 +++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/app/Http/Controllers/Fo/Auth/ForgotPasswordController.php b/app/Http/Controllers/Fo/Auth/ForgotPasswordController.php index 5e8d0a21..6494a0c3 100644 --- a/app/Http/Controllers/Fo/Auth/ForgotPasswordController.php +++ b/app/Http/Controllers/Fo/Auth/ForgotPasswordController.php @@ -57,6 +57,24 @@ class ForgotPasswordController extends AuthController return $this->traitSendResetLinkEmail($request); } + protected function validateEmail(Request $request): void + { + $request->validate([ + 'email' => [ + 'bail', + 'required', + 'string', + static function (string $attribute, mixed $value, \Closure $fail): void { + try { + new Email(\is_string($value) ? $value : ''); + } catch (\DomainException) { + $fail(__('validation.email', ['attribute' => $attribute])); + } + }, + ], + ]); + } + protected function sendResetLinkResponse(Request $request, string $response): JsonResponse | RedirectResponse { return $this->sendResponse($request->wantsJson()); diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php index e8910776..9772a764 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php @@ -257,4 +257,21 @@ describe('ForgotPasswordController', function () { ->assertSessionHas('status', trans('Please check your email, if we know you you should receive a reset link')); Notification::assertSentTo($customer, ResetPassword::class); }); + + it('returns a validation error instead of 500 when email lacks a valid TLD accepted by RFC rule', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + Notification::fake(); + $this->seed(ContentSeeder::class); + sharePagesForForgotPasswordTest(); + + // WHEN + $response = $this->from('/auth/mot-de-passe-oublie') + ->post('/auth/mot-de-passe-oublie', ['email' => 'user@localhost']); + + // THEN + $response->assertRedirect('/auth/mot-de-passe-oublie') + ->assertSessionHasErrors('email'); + Notification::assertNothingSent(); + }); }); From 85aceedd1fe4c1d4cd2ac69bfca12d247f5e9562 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 18:34:09 +0100 Subject: [PATCH 160/183] fix(http): guard null route when redirecting guests in middleware --- bootstrap/middlewares.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bootstrap/middlewares.php b/bootstrap/middlewares.php index 6f1414b2..a8f4c8ab 100644 --- a/bootstrap/middlewares.php +++ b/bootstrap/middlewares.php @@ -27,7 +27,7 @@ $redirectGuests = function (Request $request) { app(FlashMessageService::class)->warning(__('Please log in to continue.')); - foreach ($request->route()->gatherMiddleware() as $middleware) { + foreach ($request->route()?->gatherMiddleware() ?? [] as $middleware) { if (\is_string($middleware) && str_contains($middleware, 'auth:')) { $route = $logins[str_replace('auth:', '', $middleware)] ?? null; if ($route) { From 757f9aebaa920a0cad5d70279ed3d6fb6ea76680 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 18:34:09 +0100 Subject: [PATCH 161/183] fix(casts): treat empty string as null in FilePathCast --- app/Casts/FilePathCast.php | 4 +- tests/Unit/App/Casts/FilePathCastTest.php | 94 +++++++++++++++++++++++ 2 files changed, 96 insertions(+), 2 deletions(-) create mode 100644 tests/Unit/App/Casts/FilePathCastTest.php diff --git a/app/Casts/FilePathCast.php b/app/Casts/FilePathCast.php index a59274f8..9c090108 100644 --- a/app/Casts/FilePathCast.php +++ b/app/Casts/FilePathCast.php @@ -14,7 +14,7 @@ class FilePathCast implements CastsAttributes /** @param array $attributes */ public function get(Model $model, string $key, mixed $value, array $attributes): ?StorageFilePath { - if ($value === null) { + if ($value === null || $value === '') { return null; } @@ -28,7 +28,7 @@ class FilePathCast implements CastsAttributes /** @param array $attributes */ public function set(Model $model, string $key, mixed $value, array $attributes): ?string { - if ($value === null) { + if ($value === null || $value === '') { return null; } diff --git a/tests/Unit/App/Casts/FilePathCastTest.php b/tests/Unit/App/Casts/FilePathCastTest.php new file mode 100644 index 00000000..5e015bf3 --- /dev/null +++ b/tests/Unit/App/Casts/FilePathCastTest.php @@ -0,0 +1,94 @@ + new class () extends Model + { + }; + + it('returns null on get when value is null or empty string', function (mixed $raw) use ($makeModel): void { + // GIVEN + $cast = new FilePathCast(); + $model = $makeModel(); + + // WHEN + $result = $cast->get($model, 'picture', $raw, []); + + // THEN + expect($result)->toBeNull(); + })->with([ + 'null' => [null], + 'empty string' => [''], + ]); + + it('hydrates a StorageFilePath on get when value is a valid path string', function () use ($makeModel): void { + // GIVEN + $cast = new FilePathCast(); + $model = $makeModel(); + + // WHEN + $result = $cast->get($model, 'picture', 'products/poulet.webp', []); + + // THEN + expect($result)->toBeInstanceOf(StorageFilePath::class) + ->and($result?->value)->toBe('products/poulet.webp'); + }); + + it('throws InvalidArgumentException on get when value is not a string or null', function () use ($makeModel): void { + // GIVEN + $cast = new FilePathCast(); + $model = $makeModel(); + + // WHEN / THEN + expect(fn () => $cast->get($model, 'picture', 123, [])) + ->toThrow(\InvalidArgumentException::class); + }); + + it('returns null on set when value is null or empty string', function (?string $value) use ($makeModel): void { + // GIVEN + $cast = new FilePathCast(); + $model = $makeModel(); + + // WHEN + $result = $cast->set($model, 'picture', $value, []); + + // THEN + expect($result)->toBeNull(); + })->with([ + 'null' => [null], + 'empty string' => [''], + ]); + + it('returns raw string on set for StorageFilePath or valid path string', function () use ($makeModel): void { + // GIVEN + $cast = new FilePathCast(); + $model = $makeModel(); + $vo = new StorageFilePath('products/poulet.webp'); + + // WHEN + $fromVo = $cast->set($model, 'picture', $vo, []); + $fromString = $cast->set($model, 'picture', 'products/poulet.webp', []); + + // THEN + expect($fromVo)->toBe('products/poulet.webp') + ->and($fromString)->toBe('products/poulet.webp'); + }); + + it('throws InvalidArgumentException on set when value is not StorageFilePath, string, or null', function () use ($makeModel): void { + // GIVEN + $cast = new FilePathCast(); + $model = $makeModel(); + + // WHEN / THEN + /** @phpstan-ignore argument.type */ + expect(fn () => $cast->set($model, 'picture', 123, [])) + ->toThrow(\InvalidArgumentException::class); + }); +}); From dc6b00fbc1dea1f5192994c64195c0844139405b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 18:34:09 +0100 Subject: [PATCH 162/183] chore(deps): bound wildcard constraints for league/csv and uwil/storage-laravel --- composer.json | 4 ++-- composer.lock | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index 96aa2a36..f0cd5fa9 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,7 @@ "laravel/tinker": "^3.0", "laravel/ui": "^4.6", "ldc/ldccrmv4client": "^4.0", - "league/csv": "*", + "league/csv": "^9.29", "league/flysystem-aws-s3-v3": "^3.35", "league/flysystem-path-prefixing": "^3.31", "maatwebsite/excel": "4.x-dev", @@ -30,7 +30,7 @@ "uwil/laravel-k8s": "^4.0", "uwil/laravel-redirections": "^3.0", "uwil/sitemap-generator": "^8.1", - "uwil/storage-laravel": "*", + "uwil/storage-laravel": "^1.0", "webmozart/assert": "^2.4" }, "require-dev": { diff --git a/composer.lock b/composer.lock index 54c115a3..7f59fa21 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "dce4eeb75bd161f29c2bd6141296349c", + "content-hash": "fea842f5762664def28aca119e4486ac", "packages": [ { "name": "aws/aws-crt-php", From 24acaf56e989c7dd8c1f7367cc856459821aa8dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 18:34:10 +0100 Subject: [PATCH 163/183] test(tunnel): add end-to-end confirmation HTTP tests without mocking Executor --- .../Controllers/Fo/TunnelControllerTest.php | 319 ++++++++++++++++++ 1 file changed, 319 insertions(+) diff --git a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php index 3bdc7869..feb3317a 100644 --- a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php @@ -24,18 +24,37 @@ use App\Cqs\Queries\Orders\GetPickTimeSlotQueryOutput; use App\Dto\ShopDto; use App\Http\Middleware\CustomerIsEmployed; use App\Http\Middleware\EnsureCustomerEmailIsVerified; +use App\Mail\OrderConfirmAdminMail; +use App\Mail\RegateOrderMail; use App\Models\Customer; +use App\Models\Employee; use App\Models\Order; use App\Models\Page; +use App\Models\Product; +use App\Models\ProductInco; +use App\Models\Range; use App\Models\Shop; +use App\Notifications\OrderConfirmed; +use App\Services\CrmService; +use Carbon\Carbon; +use Carbon\CarbonImmutable; use Database\Seeders\ContentSeeder; +use Domain\Builders\OrderBuilder; use Domain\Builders\OrderBuilderCompleted; use Domain\Builders\OrderBuilderWithBasket; +use Domain\Enums\Country; use Domain\Enums\OrderStatus; use Domain\Enums\OrderTunnelStep; +use Domain\Enums\ProductBrand; +use Domain\Enums\SellUnit; +use Domain\Enums\TaxRate; +use Domain\Enums\Units\InvoicingUnit; +use Domain\Enums\Units\OrderUnit; use Domain\Exceptions\OrderTunnel\RegateExportFailedException; use Domain\Models\Entities\Basket; use Domain\Models\Entities\Shopper; +use Domain\Models\ValueObjects\Code; +use Domain\Models\ValueObjects\CrmCustomer; use Domain\Models\ValueObjects\DeliveryAddress; use Domain\Models\ValueObjects\Email; use Domain\Models\ValueObjects\Entities\BasketId; @@ -48,9 +67,16 @@ use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Ports\Repositories\ShopperRepository; +use Domain\Ports\Services\OrderBuilderSessionManager; +use Domain\Ports\Services\RegateService; +use Domain\Services\BasketService; use Domain\Services\OrderTunnelService; use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\Config; +use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Gate; +use Illuminate\Support\Facades\Mail; +use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\View; use Mockery\MockInterface; use Money\Money; @@ -988,4 +1014,297 @@ describe('TunnelController', function (): void { $response->assertRedirectToRoute('fo.sales.confirmation') ->assertSessionHas('message', __('An error occurred while validating your order. Please try again later.')); }); + + it('finalizes order end-to-end without mocking Executor on POST /commande/confirmation', function (): void { + /** @var \Tests\TestCase $this */ + $now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); + + try { + // GIVEN + Config::set('mail.to.regate', 'regate@test.local'); + Config::set('mail.to.contact', 'contact@test.local'); + Mail::fake(); + Notification::fake(); + + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + $hashcode = new CrmHashcode(Uuid::uuid4()); + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'email' => new Email('e2e-success@example.com'), + 'hashcode' => $hashcode, + ]); + + $crmCustomer = new CrmCustomer( + hashcode: $hashcode->value, + email: 'e2e-success@example.com', + password: 'hashed-password', + firstname: 'Jean', + lastname: 'Dupont', + birthDate: null, + phone: null, + address: null, + address2: null, + city: null, + postcode: null, + country: Country::france, + optIn: false, + status: true, + lastConnection: null, + ); + + $crmService = $this->mock(CrmService::class); + $crmService->shouldReceive('getCustomerFromHashCode')->andReturn($crmCustomer); + + $employee = new Employee(); + $employee->matricule = new Matricule('7654321'); + $employee->code = new Code('ABCDEFG'); + $employee->nom = 'Dupont'; + $employee->prenom = 'Jean'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITEA'); + $employee->service = new ShopperServiceCode('101'); + $employee->start_date = Date::now()->subMonth(); + $employee->end_date = null; + $employee->customer()->associate($customer); + $employee->saveOrFail(); + + $shop = new Shop(); + $shop->name = 'Boutique Sablé E2E'; + $shop->address = '10 rue Test'; + $shop->postcode = '72300'; + $shop->city = 'Sablé'; + $shop->default = true; + $shop->saveOrFail(); + + $range = new Range(); + $range->name = 'Gamme E2E'; + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $product = new Product(); + $product->name = 'Poulet E2E'; + $product->brand = ProductBrand::loue; + $product->description = 'Description E2E'; + $product->short_description = 'Court E2E'; + $product->price = Money::EUR(1500); + $product->invoicing_unit = InvoicingUnit::PCE; + $product->tax_rate = TaxRate::TVA_5_5; + $product->stock = 50; + $product->weight = 1000; + $product->sell_unit = SellUnit::PCE; + $product->order_unit = OrderUnit::PCE; + $product->range_id = $range->id; + $product->status = true; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt large'; + $product->picture_large_title = 'title large'; + $product->saveOrFail(); + + $inco = new ProductInco(); + $inco->product_id = $product->id; + $inco->no_art = 889901; + $inco->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + /** @var BasketService $basketService */ + $basketService = $this->app->make(BasketService::class); + $basketService->empty(); + $basketService->add($product->getId(), 2); + $basket = $basketService->getBasket(); + + $slot = new PickupTimeSlot( + CarbonImmutable::parse('2026-11-20 14:00:00', 'Europe/Paris'), + new \DateInterval('PT2H'), + ); + $builder = OrderBuilder::fromBasket($basket, $customer->getId()) + ->withPickupTimeSlot($shop->getId(), $slot); + $this->app->make(OrderBuilderSessionManager::class)->save($builder); + + // WHEN + $response = $this->post('/commande/confirmation', [ + 'ok_cgv' => '1', + ]); + + // THEN + $order = Order::query()->where('employee_matricule', '7654321')->first(); + expect($order)->not->toBeNull() + ->and($order?->status)->toBe(OrderStatus::VALIDATED) + ->and($basketService->hasItems())->toBeFalse(); + + $response->assertRedirectToRoute('fo.sales.confirmation.show-confirmed', (string) $order?->reference); + Mail::assertSent(RegateOrderMail::class); + Mail::assertQueued(OrderConfirmAdminMail::class); + Notification::assertSentTo($employee, OrderConfirmed::class); + } finally { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); + } + }); + + it('cancels pending order end-to-end without mocking Executor when Regate export fails', function (): void { + /** @var \Tests\TestCase $this */ + $now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); + + try { + // GIVEN + Mail::fake(); + Notification::fake(); + + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + $hashcode = new CrmHashcode(Uuid::uuid4()); + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'email' => new Email('e2e-fail@example.com'), + 'hashcode' => $hashcode, + ]); + + $crmCustomer = new CrmCustomer( + hashcode: $hashcode->value, + email: 'e2e-fail@example.com', + password: 'hashed-password', + firstname: 'Jean', + lastname: 'Dupont', + birthDate: null, + phone: null, + address: null, + address2: null, + city: null, + postcode: null, + country: Country::france, + optIn: false, + status: true, + lastConnection: null, + ); + + $crmService = $this->mock(CrmService::class); + $crmService->shouldReceive('getCustomerFromHashCode')->andReturn($crmCustomer); + + $employee = new Employee(); + $employee->matricule = new Matricule('7654322'); + $employee->code = new Code('ABCDEFH'); + $employee->nom = 'Dupont'; + $employee->prenom = 'Jean'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITEA'); + $employee->service = new ShopperServiceCode('101'); + $employee->start_date = Date::now()->subMonth(); + $employee->end_date = null; + $employee->customer()->associate($customer); + $employee->saveOrFail(); + + $shop = new Shop(); + $shop->name = 'Boutique Sablé E2E Fail'; + $shop->address = '10 rue Test'; + $shop->postcode = '72300'; + $shop->city = 'Sablé'; + $shop->default = true; + $shop->saveOrFail(); + + $range = new Range(); + $range->name = 'Gamme E2E Fail'; + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $product = new Product(); + $product->name = 'Poulet E2E Fail'; + $product->brand = ProductBrand::loue; + $product->description = 'Description E2E Fail'; + $product->short_description = 'Court E2E Fail'; + $product->price = Money::EUR(1500); + $product->invoicing_unit = InvoicingUnit::PCE; + $product->tax_rate = TaxRate::TVA_5_5; + $product->stock = 50; + $product->weight = 1000; + $product->sell_unit = SellUnit::PCE; + $product->order_unit = OrderUnit::PCE; + $product->range_id = $range->id; + $product->status = true; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt large'; + $product->picture_large_title = 'title large'; + $product->saveOrFail(); + + $inco = new ProductInco(); + $inco->product_id = $product->id; + $inco->no_art = 889902; + $inco->saveOrFail(); + + $sentryHub = \Mockery::mock(HubInterface::class); + $sentryHub->shouldReceive('captureException') + ->once() + ->with(\Mockery::type(RegateExportFailedException::class)); + $this->app->instance(HubInterface::class, $sentryHub); + + $regateService = \Mockery::mock(RegateService::class); + $regateService->shouldReceive('processOrder') + ->once() + ->andThrow(new RegateExportFailedException('SMTP transport down')); + $this->app->instance(RegateService::class, $regateService); + + $this->actingAs($customer, 'frontend'); + + /** @var BasketService $basketService */ + $basketService = $this->app->make(BasketService::class); + $basketService->empty(); + $basketService->add($product->getId(), 2); + $basket = $basketService->getBasket(); + + $slot = new PickupTimeSlot( + CarbonImmutable::parse('2026-11-20 14:00:00', 'Europe/Paris'), + new \DateInterval('PT2H'), + ); + $builder = OrderBuilder::fromBasket($basket, $customer->getId()) + ->withPickupTimeSlot($shop->getId(), $slot); + $this->app->make(OrderBuilderSessionManager::class)->save($builder); + + // WHEN + $response = $this->from('/commande/confirmation')->post('/commande/confirmation', [ + 'ok_cgv' => '1', + ]); + + // THEN + $order = Order::query()->where('employee_matricule', '7654322')->first(); + expect($order)->not->toBeNull() + ->and($order?->status)->toBe(OrderStatus::CANCELED) + ->and($basketService->hasItems())->toBeTrue(); + + $response->assertRedirectToRoute('fo.sales.confirmation') + ->assertSessionHas('message', __('An error occurred while validating your order. Please try again later.')); + Notification::assertNothingSent(); + } finally { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); + } + }); }); From 53f49fea9c21e10490eac02aa3f59840edb02c37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 19:57:06 +0100 Subject: [PATCH 164/183] refactor(domain,infra): isolate PENDING/FAILED order states and add lockForUpdate --- domain/Enums/OrderStatus.php | 4 + domain/Models/Entities/Order.php | 23 ++++- domain/Ports/Repositories/OrderRepository.php | 7 ++ domain/Services/OrderService.php | 17 +++- domain/Services/OrderTunnelService.php | 6 +- .../Repositories/EloquentOrderRepository.php | 38 ++++++++ .../EloquentEmployeeStatisticsService.php | 2 +- .../EloquentOrderRepositoryTest.php | 90 +++++++++++++++++++ .../EloquentEmployeeStatisticsServiceTest.php | 16 +++- .../Unit/Domain/Models/Entities/OrderTest.php | 35 +++++++- .../Unit/Domain/Services/OrderServiceTest.php | 81 ++++++++++++++++- .../Services/OrderTunnelServiceTest.php | 37 ++++---- 12 files changed, 325 insertions(+), 31 deletions(-) diff --git a/domain/Enums/OrderStatus.php b/domain/Enums/OrderStatus.php index a19a2c42..ffcf24ae 100644 --- a/domain/Enums/OrderStatus.php +++ b/domain/Enums/OrderStatus.php @@ -13,7 +13,9 @@ enum OrderStatus: int implements HasBaseEnum use BaseEnum; case WAITING = 1; + case PENDING = 2; case VALIDATED = 3; + case FAILED = 4; case CANCELED = 7; /** @@ -23,7 +25,9 @@ enum OrderStatus: int implements HasBaseEnum */ private const LABELS = [ self::WAITING->name => 'En attente', + self::PENDING->name => 'En cours', self::VALIDATED->name => 'Validée', + self::FAILED->name => 'Échouée', self::CANCELED->name => 'Annulée', ]; } diff --git a/domain/Models/Entities/Order.php b/domain/Models/Entities/Order.php index dccf4056..9918e0fc 100644 --- a/domain/Models/Entities/Order.php +++ b/domain/Models/Entities/Order.php @@ -68,13 +68,30 @@ final class Order implements Entity return; } + if ($this->status === OrderStatus::PENDING || $this->status === OrderStatus::FAILED) { + throw new \DomainException('Cannot cancel a technical pending or failed order.'); + } + $this->status = OrderStatus::CANCELED; } + public function fail(): void + { + if ($this->status === OrderStatus::FAILED) { + return; + } + + if ($this->status !== OrderStatus::PENDING) { + throw new \DomainException('Only pending orders can be marked as failed.'); + } + + $this->status = OrderStatus::FAILED; + } + public function validate(): void { - if ($this->status === OrderStatus::CANCELED) { - throw new \DomainException('Cannot validate a canceled order.'); + if ($this->status !== OrderStatus::PENDING) { + throw new \DomainException('Only pending orders can be validated.'); } $this->status = OrderStatus::VALIDATED; @@ -95,7 +112,7 @@ final class Order implements Entity pickupTimeSlot: $pickupTimeSlot, shopper: $shopper, shop: $shop, - status: OrderStatus::WAITING, + status: OrderStatus::PENDING, ); } diff --git a/domain/Ports/Repositories/OrderRepository.php b/domain/Ports/Repositories/OrderRepository.php index 160b1a70..0528a6f9 100644 --- a/domain/Ports/Repositories/OrderRepository.php +++ b/domain/Ports/Repositories/OrderRepository.php @@ -15,6 +15,13 @@ interface OrderRepository extends Repository { public function find(OrderId $id): ?Order; + public function findForUpdate(OrderId $id): ?Order; + + /** + * @return list + */ + public function findStalePendingOrderIds(\DateTimeInterface $olderThan): array; + public function persist(Order $order): void; public function delete(Order $order): void; diff --git a/domain/Services/OrderService.php b/domain/Services/OrderService.php index 66dce286..a1016e05 100644 --- a/domain/Services/OrderService.php +++ b/domain/Services/OrderService.php @@ -65,7 +65,7 @@ class OrderService public function validateOrder(OrderId $id): Order { - $order = $this->orderRepository->find($id); + $order = $this->orderRepository->findForUpdate($id); if (! $order) { throw new \DomainException('Order not found'); @@ -78,9 +78,22 @@ class OrderService return $order; } + public function failOrder(OrderId $id): void + { + $order = $this->orderRepository->findForUpdate($id); + + if (! $order) { + throw new \DomainException('Order not found'); + } + + $order->fail(); + + $this->orderRepository->persist($order); + } + public function cancelOrder(OrderId $id): void { - $order = $this->orderRepository->find($id); + $order = $this->orderRepository->findForUpdate($id); if (! $order) { throw new \DomainException('Order not found'); diff --git a/domain/Services/OrderTunnelService.php b/domain/Services/OrderTunnelService.php index 4cd4d18c..e753a22e 100644 --- a/domain/Services/OrderTunnelService.php +++ b/domain/Services/OrderTunnelService.php @@ -214,11 +214,11 @@ class OrderTunnelService } /** - * Step 2c (on Regate failure): cancels the WAITING order without emptying the basket. + * Step 2c (on Regate failure): marks the PENDING order as FAILED without emptying the basket. */ - public function cancelPendingOrder(OrderId $orderId): void + public function failPendingOrder(OrderId $orderId): void { - $this->orderService->cancelOrder($orderId); + $this->orderService->failOrder($orderId); } /** diff --git a/infra/Adapters/Repositories/EloquentOrderRepository.php b/infra/Adapters/Repositories/EloquentOrderRepository.php index 4bb5a236..d5494464 100644 --- a/infra/Adapters/Repositories/EloquentOrderRepository.php +++ b/infra/Adapters/Repositories/EloquentOrderRepository.php @@ -8,6 +8,7 @@ use App\Models\Order; use App\Models\OrderLine; use Carbon\CarbonImmutable; use Carbon\CarbonInterval; +use Domain\Enums\OrderStatus; use Domain\Models\Entities\Order as DomainOrder; use Domain\Models\ValueObjects\Entities\OrderId; use Domain\Models\ValueObjects\Entities\ShopId; @@ -34,6 +35,43 @@ class EloquentOrderRepository implements OrderRepository return $this->toEntity($eloquentOrder); } + #[\Override] + public function findForUpdate(OrderId $id): ?DomainOrder + { + $eloquentOrder = Order::query() + ->with('lines') + ->where('id', $id->value) + ->lockForUpdate() + ->first(); + + if (! $eloquentOrder) { + return null; + } + + return $this->toEntity($eloquentOrder); + } + + /** + * @return list + */ + #[\Override] + public function findStalePendingOrderIds(\DateTimeInterface $olderThan): array + { + $cutoffUtc = CarbonImmutable::instance($olderThan)->utc(); + + /** @var list $ids */ + $ids = Order::query() + ->where('status', OrderStatus::PENDING->value) + ->where('updated_at', '<', $cutoffUtc) + ->pluck('id') + ->all(); + + return array_map( + static fn (string $id): OrderId => new OrderId(Uuid::fromString($id)), + $ids, + ); + } + #[\Override] public function persist(DomainOrder $order): void { diff --git a/infra/Adapters/Services/EloquentEmployeeStatisticsService.php b/infra/Adapters/Services/EloquentEmployeeStatisticsService.php index 9c699a8f..2eae544f 100644 --- a/infra/Adapters/Services/EloquentEmployeeStatisticsService.php +++ b/infra/Adapters/Services/EloquentEmployeeStatisticsService.php @@ -30,7 +30,7 @@ class EloquentEmployeeStatisticsService implements EmployeeStatisticsService { $weekTotal = Order::query() ->where('employee_matricule', $matricule->value) - ->whereIn('status', [OrderStatus::VALIDATED, OrderStatus::WAITING]) + ->whereIn('status', [OrderStatus::VALIDATED, OrderStatus::PENDING]) ->whereBetween('pickup_day', [$start, $end]) ->sum('total'); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php index 9db8ff66..238fed0f 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Tests\Integration\WithApp\Infra\Adapters\Repositories; +use Carbon\CarbonImmutable; use Domain\Enums\OrderStatus; use Domain\Models\Entities\Order as DomainOrder; use Domain\Models\ValueObjects\Entities\OrderId; @@ -61,3 +62,92 @@ it('updates an existing order in the repository', function () { $updatedOrder = DB::table('orders')->where('id', '018e4567-e89b-72d3-a456-426614174002')->first(); expect($updatedOrder?->status)->toBe(OrderStatus::VALIDATED->value); }); + +it('finds an order for update inside a transaction', function (): void { + // GIVEN + $shopId = Uuid::uuid7()->toString(); + $orderId = Uuid::uuid7()->toString(); + DB::table('shops')->insertOrIgnore(['id' => $shopId, 'name' => 'Shop Lock', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); + DB::table('orders')->insert([ + 'id' => $orderId, + 'shop_id' => $shopId, + 'reference' => Uuid::uuid7()->toString(), + 'employee' => json_encode([ + 'matricule' => '1234567', + 'firstname' => 'Jean', + 'lastname' => 'Dupont', + 'facility' => 'FAC01', + 'site' => 'HQ', + 'service' => '101', + ]), + 'delivery_address' => '{}', + 'pickup_day' => '2026-11-20', + 'status' => OrderStatus::PENDING->value, + 'total' => 1000, + ]); + + $repo = new EloquentOrderRepository(); + + // WHEN + $found = DB::transaction(static fn () => $repo->findForUpdate(new OrderId(Uuid::fromString($orderId)))); + + // THEN + expect($found)->toBeInstanceOf(DomainOrder::class) + ->and($found?->status)->toBe(OrderStatus::PENDING); +}); + +it('returns only stale PENDING order ids older than cutoff', function (): void { + // GIVEN + $shopId = Uuid::uuid7()->toString(); + $staleId = Uuid::uuid7()->toString(); + $freshId = Uuid::uuid7()->toString(); + $staleWaiting = Uuid::uuid7()->toString(); + $now = CarbonImmutable::parse('2026-11-16 12:00:00', 'UTC'); + + DB::table('shops')->insertOrIgnore(['id' => $shopId, 'name' => 'Shop Stale', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); + + $baseRow = [ + 'shop_id' => $shopId, + 'employee' => json_encode([ + 'matricule' => '1234567', + 'firstname' => 'Jean', + 'lastname' => 'Dupont', + 'facility' => 'FAC01', + 'site' => 'HQ', + 'service' => '101', + ]), + 'delivery_address' => '{}', + 'pickup_day' => '2026-11-20', + 'total' => 1000, + ]; + + DB::table('orders')->insert([ + array_merge($baseRow, [ + 'id' => $staleId, + 'reference' => Uuid::uuid7()->toString(), + 'status' => OrderStatus::PENDING->value, + 'updated_at' => $now->subMinutes(15)->toDateTimeString(), + ]), + array_merge($baseRow, [ + 'id' => $freshId, + 'reference' => Uuid::uuid7()->toString(), + 'status' => OrderStatus::PENDING->value, + 'updated_at' => $now->subMinutes(5)->toDateTimeString(), + ]), + array_merge($baseRow, [ + 'id' => $staleWaiting, + 'reference' => Uuid::uuid7()->toString(), + 'status' => OrderStatus::WAITING->value, + 'updated_at' => $now->subMinutes(30)->toDateTimeString(), + ]), + ]); + + $repo = new EloquentOrderRepository(); + + // WHEN + $staleIds = $repo->findStalePendingOrderIds($now->subMinutes(10)); + + // THEN + expect($staleIds)->toHaveCount(1) + ->and($staleIds[0]->value->toString())->toBe($staleId); +}); diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php index 5c739e86..89aac542 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php @@ -46,7 +46,7 @@ it('retrieves the weekly order total for a given employee', function () { ->and($result->getCurrency()->getCode())->toBe('EUR'); }); -it('includes WAITING orders and excludes CANCELED orders in weekly total', function (): void { +it('includes VALIDATED and PENDING orders and excludes WAITING, FAILED, and CANCELED orders in weekly total', function (): void { // GIVEN $shop = Shop::factory()->create(); @@ -74,9 +74,21 @@ it('includes WAITING orders and excludes CANCELED orders in weekly total', funct array_merge($baseRow, [ 'id' => Uuid::uuid7()->toString(), 'reference' => Uuid::uuid7()->toString(), - 'status' => OrderStatus::WAITING->value, + 'status' => OrderStatus::PENDING->value, 'total' => 2500, ]), + array_merge($baseRow, [ + 'id' => Uuid::uuid7()->toString(), + 'reference' => Uuid::uuid7()->toString(), + 'status' => OrderStatus::WAITING->value, + 'total' => 4000, + ]), + array_merge($baseRow, [ + 'id' => Uuid::uuid7()->toString(), + 'reference' => Uuid::uuid7()->toString(), + 'status' => OrderStatus::FAILED->value, + 'total' => 5000, + ]), array_merge($baseRow, [ 'id' => Uuid::uuid7()->toString(), 'reference' => Uuid::uuid7()->toString(), diff --git a/tests/Unit/Domain/Models/Entities/OrderTest.php b/tests/Unit/Domain/Models/Entities/OrderTest.php index c4345814..90906637 100644 --- a/tests/Unit/Domain/Models/Entities/OrderTest.php +++ b/tests/Unit/Domain/Models/Entities/OrderTest.php @@ -328,7 +328,7 @@ describe('Order - fromBasket factory', function (): void { ->and($order->getLines()[0]->quantity)->toBe(2); }); - it('creates an order in WAITING status via pendingFromBasket and validates it to VALIDATED', function (): void { + it('creates an order in PENDING status via pendingFromBasket and validates it to VALIDATED', function (): void { // GIVEN $basket = new Basket(new BasketId(Uuid::uuid7()), [ new BasketProduct( @@ -382,13 +382,42 @@ describe('Order - fromBasket factory', function (): void { ); // THEN - expect($order->status)->toBe(OrderStatus::WAITING); + expect($order->status)->toBe(OrderStatus::PENDING); $order->validate(); expect($order->status)->toBe(OrderStatus::VALIDATED); + expect(fn () => $order->validate())->toThrow(\DomainException::class, 'Only pending orders can be validated.'); + expect(fn () => $order->fail())->toThrow(\DomainException::class, 'Only pending orders can be marked as failed.'); $order->cancel(); - expect(fn () => $order->validate())->toThrow(\DomainException::class, 'Cannot validate a canceled order.'); + expect($order->status)->toBe(OrderStatus::CANCELED); + expect(fn () => $order->validate())->toThrow(\DomainException::class, 'Only pending orders can be validated.'); + }); + + it('marks a PENDING order as FAILED and forbids canceling PENDING or FAILED orders', function (): void { + // GIVEN + $pending = makeOrder(['status' => OrderStatus::PENDING]); + + // WHEN / THEN + expect(fn () => $pending->cancel()) + ->toThrow(\DomainException::class, 'Cannot cancel a technical pending or failed order.'); + + $pending->fail(); + expect($pending->status)->toBe(OrderStatus::FAILED); + + $pending->fail(); // idempotent + expect($pending->status)->toBe(OrderStatus::FAILED); + + expect(fn () => $pending->validate()) + ->toThrow(\DomainException::class, 'Only pending orders can be validated.'); + expect(fn () => $pending->cancel()) + ->toThrow(\DomainException::class, 'Cannot cancel a technical pending or failed order.'); + + $waiting = makeOrder(['status' => OrderStatus::WAITING]); + expect(fn () => $waiting->validate()) + ->toThrow(\DomainException::class, 'Only pending orders can be validated.'); + $waiting->cancel(); + expect($waiting->status)->toBe(OrderStatus::CANCELED); }); }); diff --git a/tests/Unit/Domain/Services/OrderServiceTest.php b/tests/Unit/Domain/Services/OrderServiceTest.php index 09df7d18..a19ada33 100644 --- a/tests/Unit/Domain/Services/OrderServiceTest.php +++ b/tests/Unit/Domain/Services/OrderServiceTest.php @@ -111,7 +111,7 @@ describe('Order Cancellation', function () { /** @var OrderRepository|\Mockery\MockInterface $repository */ $repository = Mockery::mock(OrderRepository::class); - $repository->shouldReceive('find')->with($orderId)->andReturn($order); + $repository->shouldReceive('findForUpdate')->with($orderId)->andReturn($order); $repository->shouldReceive('persist')->with($order)->once(); $service = new OrderService($repository); @@ -129,7 +129,7 @@ describe('Order Cancellation', function () { /** @var OrderRepository|\Mockery\MockInterface $repository */ $repository = Mockery::mock(OrderRepository::class); - $repository->shouldReceive('find')->with($orderId)->andReturn(null); + $repository->shouldReceive('findForUpdate')->with($orderId)->andReturn(null); $service = new OrderService($repository); @@ -139,6 +139,83 @@ describe('Order Cancellation', function () { // THEN expect($action)->toThrow(\DomainException::class, 'Order not found'); }); + + it('validates and fails pending orders using findForUpdate', function () { + // GIVEN + $pendingId = new OrderId(Uuid::uuid7()); + $failedId = new OrderId(Uuid::uuid7()); + + $makeOrderWithStatus = static fn (OrderId $id, OrderStatus $status): Order => new Order( + id: $id, + shopId: new ShopId(Uuid::uuid7()), + reference: new OrderReference(Uuid::uuid7()), + employee: new OrderEmployee( + new Matricule('1234567'), + 'Jean', + 'Dupont', + new ShopperEstablishmentCode('ETAB01'), + new ShopperSiteCode('SITEA'), + new ShopperServiceCode('101') + ), + deliveryAddress: new DeliveryAddress( + 'Cocotte Lyon', + '12 rue de la Paix', + '69001', + 'Lyon', + '0478123456' + ), + pickupTimeSlot: new PickupTimeSlot( + new \DateTimeImmutable('2023-12-01 10:00:00'), + new \DateInterval('PT10M') + ), + status: $status, + total: Money::EUR(1899), + lines: [ + new OrderLine( + product: new OrderLineProduct( + incoId: new IncoId(45), + originalId: new ProductId(Uuid::uuid7()), + name: 'Poulet Rôti', + weight: new ProductWeight(1200, false), + brand: ProductBrand::marie, + orderUnit: OrderUnit::PCE, + price: Money::EUR(1000), + discountedPrice: Money::EUR(900), + priceKgTtc: Money::EUR(1500), + taxRate: TaxRate::TVA_5_5, + ), + quantity: 2, + unitPriceHt: Money::EUR(1000), + unitDiscount: Money::EUR(100), + unitTax: Money::EUR(50), + totalHt: Money::EUR(2000), + totalDiscount: Money::EUR(200), + totalTax: Money::EUR(99), + totalTtc: Money::EUR(1899) + ), + ] + ); + + $orderToValidate = $makeOrderWithStatus($pendingId, OrderStatus::PENDING); + $orderToFail = $makeOrderWithStatus($failedId, OrderStatus::PENDING); + + /** @var OrderRepository|\Mockery\MockInterface $repository */ + $repository = Mockery::mock(OrderRepository::class); + $repository->shouldReceive('findForUpdate')->with($pendingId)->once()->andReturn($orderToValidate); + $repository->shouldReceive('persist')->with($orderToValidate)->once(); + $repository->shouldReceive('findForUpdate')->with($failedId)->once()->andReturn($orderToFail); + $repository->shouldReceive('persist')->with($orderToFail)->once(); + + $service = new OrderService($repository); + + // WHEN + $validated = $service->validateOrder($pendingId); + $service->failOrder($failedId); + + // THEN + expect($validated->status)->toBe(OrderStatus::VALIDATED) + ->and($orderToFail->status)->toBe(OrderStatus::FAILED); + }); }); describe('Order Creation', function () { diff --git a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php index 977609bf..8e0174ab 100644 --- a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php +++ b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php @@ -969,10 +969,10 @@ describe('OrderTunnelService', function (): void { $order = $service->placePendingOrder($builder); // THEN - expect($order->status)->toBe(OrderStatus::WAITING); + expect($order->status)->toBe(OrderStatus::PENDING); }); - it('exports, confirms and cancels a pending order across split steps', function (): void { + it('exports, confirms and fails a pending order across split steps', function (): void { // GIVEN $shopId = new ShopId(Uuid::uuid7()); $shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris'); @@ -988,8 +988,16 @@ describe('OrderTunnelService', function (): void { site: new ShopperSiteCode('SITEA'), service: new ShopperServiceCode('101') ); - $basket = createTestBasket(1); - $order = Order::pendingFromBasket( + $basket = createTestBasket(1); + $orderToOk = Order::pendingFromBasket( + new OrderId(Uuid::uuid7()), + new OrderReference(Uuid::uuid7()), + $basket, + new PickupTimeSlot(CarbonImmutable::now()->next('Friday'), new \DateInterval('PT1H')), + $shopper, + $shop + ); + $orderToKo = Order::pendingFromBasket( new OrderId(Uuid::uuid7()), new OrderReference(Uuid::uuid7()), $basket, @@ -999,8 +1007,11 @@ describe('OrderTunnelService', function (): void { ); $orderRepo = \Mockery::mock(OrderRepository::class); - $orderRepo->shouldReceive('find')->with($order->id())->andReturn($order); - $orderRepo->shouldReceive('persist')->twice(); + $orderRepo->shouldReceive('find')->with($orderToOk->id())->andReturn($orderToOk); + $orderRepo->shouldReceive('findForUpdate')->with($orderToOk->id())->andReturn($orderToOk); + $orderRepo->shouldReceive('persist')->with($orderToOk)->once(); + $orderRepo->shouldReceive('findForUpdate')->with($orderToKo->id())->andReturn($orderToKo); + $orderRepo->shouldReceive('persist')->with($orderToKo)->once(); $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); $eventDispatcher->shouldReceive('dispatch') @@ -1017,16 +1028,12 @@ describe('OrderTunnelService', function (): void { ); // WHEN - $service->exportOrderToRegate($order->id()); - $confirmed = $service->confirmPlacedOrder($order->id()); + $service->exportOrderToRegate($orderToOk->id()); + $confirmed = $service->confirmPlacedOrder($orderToOk->id()); + $service->failPendingOrder($orderToKo->id()); // THEN - expect($confirmed->status)->toBe(OrderStatus::VALIDATED); - - // WHEN cancelPendingOrder is invoked - $service->cancelPendingOrder($order->id()); - - // THEN - expect($order->status)->toBe(OrderStatus::CANCELED); + expect($confirmed->status)->toBe(OrderStatus::VALIDATED) + ->and($orderToKo->status)->toBe(OrderStatus::FAILED); }); }); From c58a2c8b23e651e61583a98cf23e43a461c89cc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 20:05:27 +0100 Subject: [PATCH 165/183] feat(orders): add checkout lock, FAIL/PENDING isolation, and stale pending expiration --- app/Cqs/Actions/Orders/CancelPendingOrder.php | 41 ----- app/Cqs/Actions/Orders/FailPendingOrder.php | 43 +++++ ...derInput.php => FailPendingOrderInput.php} | 2 +- ...rOutput.php => FailPendingOrderOutput.php} | 5 +- .../Actions/Orders/FailStalePendingOrders.php | 53 ++++++ .../Orders/FailStalePendingOrdersInput.php | 17 ++ .../Orders/GetBoPaginatedOrdersQuery.php | 2 + .../Queries/Orders/GetBoTodayOrdersQuery.php | 5 +- .../GetFoCustomerPaginatedOrdersQuery.php | 2 + app/Http/Controllers/Fo/TunnelController.php | 108 +++++++----- app/Jobs/FailStalePendingOrdersJob.php | 23 +++ app/Policies/Backend/OrderPolicy.php | 3 +- app/Policies/Frontend/OrderPolicy.php | 5 + bootstrap/jobs.php | 2 + .../views/fo/tunnel/confirmation.blade.php | 23 ++- .../Fo/Customers/OrderControllerTest.php | 84 +++++++++ .../Controllers/Fo/TunnelControllerTest.php | 161 +++++++++++++++++- .../Orders/FailStalePendingOrdersTest.php | 106 ++++++++++++ .../Actions/Orders/PlacePendingOrderTest.php | 28 +-- .../Orders/GetBoPaginatedOrdersQueryTest.php | 45 +++++ .../Orders/GetBoTodayOrdersQueryTest.php | 86 ++++++++++ .../GetFoCustomerPaginatedOrdersQueryTest.php | 36 ++++ .../GetTunnelOrderConfirmedQueryTest.php | 4 +- tests/TestCase.php | 3 + .../Actions/Orders/PlacePendingOrderTest.php | 18 +- .../App/Policies/Backend/OrderPolicyTest.php | 18 ++ .../App/Policies/Frontend/OrderPolicyTest.php | 38 ++++- 27 files changed, 831 insertions(+), 130 deletions(-) delete mode 100644 app/Cqs/Actions/Orders/CancelPendingOrder.php create mode 100644 app/Cqs/Actions/Orders/FailPendingOrder.php rename app/Cqs/Actions/Orders/{CancelPendingOrderInput.php => FailPendingOrderInput.php} (77%) rename app/Cqs/Actions/Orders/{CancelPendingOrderOutput.php => FailPendingOrderOutput.php} (56%) create mode 100644 app/Cqs/Actions/Orders/FailStalePendingOrders.php create mode 100644 app/Cqs/Actions/Orders/FailStalePendingOrdersInput.php create mode 100644 app/Jobs/FailStalePendingOrdersJob.php create mode 100644 tests/Integration/WithApp/App/Cqs/Actions/Orders/FailStalePendingOrdersTest.php create mode 100644 tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoTodayOrdersQueryTest.php diff --git a/app/Cqs/Actions/Orders/CancelPendingOrder.php b/app/Cqs/Actions/Orders/CancelPendingOrder.php deleted file mode 100644 index e44b8b8f..00000000 --- a/app/Cqs/Actions/Orders/CancelPendingOrder.php +++ /dev/null @@ -1,41 +0,0 @@ - - */ -final class CancelPendingOrder implements Action -{ - public function __construct( - private readonly OrderTunnelService $orderTunnelService, - ) { - } - - /** - * @param \App\Cqs\Actions\Orders\CancelPendingOrderInput $input - */ - #[\Override] - public function __invoke(ActionInput $input): CancelPendingOrderOutput - { - Assert::isInstanceOf($input, CancelPendingOrderInput::class); - - try { - $this->orderTunnelService->cancelPendingOrder($input->orderId); - } catch (\DomainException) { - return CancelPendingOrderOutput::NOT_FOUND; - } - - return CancelPendingOrderOutput::CANCELLED; - } -} diff --git a/app/Cqs/Actions/Orders/FailPendingOrder.php b/app/Cqs/Actions/Orders/FailPendingOrder.php new file mode 100644 index 00000000..515dac49 --- /dev/null +++ b/app/Cqs/Actions/Orders/FailPendingOrder.php @@ -0,0 +1,43 @@ + + */ +final class FailPendingOrder implements Action +{ + public function __construct( + private readonly OrderTunnelService $orderTunnelService, + ) { + } + + /** + * @param \App\Cqs\Actions\Orders\FailPendingOrderInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): FailPendingOrderOutput + { + Assert::isInstanceOf($input, FailPendingOrderInput::class); + + try { + $this->orderTunnelService->failPendingOrder($input->orderId); + } catch (\DomainException $e) { + return $e->getMessage() === 'Order not found' + ? FailPendingOrderOutput::NOT_FOUND + : FailPendingOrderOutput::INVALID_STATUS; + } + + return FailPendingOrderOutput::FAILED; + } +} diff --git a/app/Cqs/Actions/Orders/CancelPendingOrderInput.php b/app/Cqs/Actions/Orders/FailPendingOrderInput.php similarity index 77% rename from app/Cqs/Actions/Orders/CancelPendingOrderInput.php rename to app/Cqs/Actions/Orders/FailPendingOrderInput.php index 2ee4f740..55342ccb 100644 --- a/app/Cqs/Actions/Orders/CancelPendingOrderInput.php +++ b/app/Cqs/Actions/Orders/FailPendingOrderInput.php @@ -7,7 +7,7 @@ namespace App\Cqs\Actions\Orders; use App\Contracts\ActionInput; use Domain\Models\ValueObjects\Entities\OrderId; -final readonly class CancelPendingOrderInput implements ActionInput +final readonly class FailPendingOrderInput implements ActionInput { public function __construct( public OrderId $orderId, diff --git a/app/Cqs/Actions/Orders/CancelPendingOrderOutput.php b/app/Cqs/Actions/Orders/FailPendingOrderOutput.php similarity index 56% rename from app/Cqs/Actions/Orders/CancelPendingOrderOutput.php rename to app/Cqs/Actions/Orders/FailPendingOrderOutput.php index ccd2d944..d095e996 100644 --- a/app/Cqs/Actions/Orders/CancelPendingOrderOutput.php +++ b/app/Cqs/Actions/Orders/FailPendingOrderOutput.php @@ -4,8 +4,9 @@ declare(strict_types=1); namespace App\Cqs\Actions\Orders; -enum CancelPendingOrderOutput +enum FailPendingOrderOutput { - case CANCELLED; + case FAILED; case NOT_FOUND; + case INVALID_STATUS; } diff --git a/app/Cqs/Actions/Orders/FailStalePendingOrders.php b/app/Cqs/Actions/Orders/FailStalePendingOrders.php new file mode 100644 index 00000000..dabaf2dd --- /dev/null +++ b/app/Cqs/Actions/Orders/FailStalePendingOrders.php @@ -0,0 +1,53 @@ + + */ +final class FailStalePendingOrders implements Action +{ + public function __construct( + private readonly OrderRepository $orderRepository, + private readonly OrderService $orderService, + private readonly LoggerInterface $logger, + ) { + } + + /** + * @param \App\Cqs\Actions\Orders\FailStalePendingOrdersInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): int + { + Assert::isInstanceOf($input, FailStalePendingOrdersInput::class); + + $cutoff = Date::now()->subMinutes($input->ttlMinutes); + $staleIds = $this->orderRepository->findStalePendingOrderIds($cutoff); + $count = 0; + + foreach ($staleIds as $orderId) { + try { + $this->orderService->failOrder($orderId); + $count++; + } catch (\DomainException $e) { + $this->logger->info('[FailStalePendingOrders] Skipped concurrent order transition', [ + 'order_id' => $orderId->value->toString(), + 'reason' => $e->getMessage(), + ]); + } + } + + return $count; + } +} diff --git a/app/Cqs/Actions/Orders/FailStalePendingOrdersInput.php b/app/Cqs/Actions/Orders/FailStalePendingOrdersInput.php new file mode 100644 index 00000000..38b91766 --- /dev/null +++ b/app/Cqs/Actions/Orders/FailStalePendingOrdersInput.php @@ -0,0 +1,17 @@ +ttlMinutes, 0); + } +} diff --git a/app/Cqs/Queries/Orders/GetBoPaginatedOrdersQuery.php b/app/Cqs/Queries/Orders/GetBoPaginatedOrdersQuery.php index f02650e4..ddabe1ee 100644 --- a/app/Cqs/Queries/Orders/GetBoPaginatedOrdersQuery.php +++ b/app/Cqs/Queries/Orders/GetBoPaginatedOrdersQuery.php @@ -66,6 +66,8 @@ final readonly class GetBoPaginatedOrdersQuery implements Query if ($input->status !== null) { $query->where('status', $input->status); + } else { + $query->whereNotIn('status', [OrderStatus::PENDING, OrderStatus::FAILED]); } $this->dataTable->sortQuery( diff --git a/app/Cqs/Queries/Orders/GetBoTodayOrdersQuery.php b/app/Cqs/Queries/Orders/GetBoTodayOrdersQuery.php index a12bd5ad..8d697b2f 100644 --- a/app/Cqs/Queries/Orders/GetBoTodayOrdersQuery.php +++ b/app/Cqs/Queries/Orders/GetBoTodayOrdersQuery.php @@ -9,6 +9,7 @@ use App\Contracts\QueryInput; use App\Dto\OrderDto; use App\Models\Order; use App\Services\DataTableService; +use Domain\Enums\OrderStatus; use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Support\Facades\Date; use Webmozart\Assert\Assert; @@ -35,7 +36,9 @@ final readonly class GetBoTodayOrdersQuery implements Query { Assert::isInstanceOf($input, GetBoTodayOrdersQueryInput::class); - $query = Order::query()->with(['shop']); + $query = Order::query() + ->with(['shop']) + ->whereNotIn('status', [OrderStatus::PENDING, OrderStatus::FAILED]); $query->whereCreatedAtBetween(Date::now(), Date::now()); diff --git a/app/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQuery.php b/app/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQuery.php index e811caa8..52e1ac04 100644 --- a/app/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQuery.php +++ b/app/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQuery.php @@ -8,6 +8,7 @@ use App\Contracts\Query; use App\Contracts\QueryInput; use App\Dto\OrderDto; use App\Models\Order; +use Domain\Enums\OrderStatus; use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Pagination\LengthAwarePaginator as ConcreteLengthAwarePaginator; use Webmozart\Assert\Assert; @@ -43,6 +44,7 @@ final readonly class GetFoCustomerPaginatedOrdersQuery implements Query $paginator = Order::query() ->where('employee_matricule', $employeeMatricule->value) + ->whereNotIn('status', [OrderStatus::PENDING, OrderStatus::FAILED]) ->orderBy('id', \SortDirection::Descending) ->paginate( perPage: $input->pagination->pageSize()->value(), diff --git a/app/Http/Controllers/Fo/TunnelController.php b/app/Http/Controllers/Fo/TunnelController.php index 489ffa83..ecea8e80 100644 --- a/app/Http/Controllers/Fo/TunnelController.php +++ b/app/Http/Controllers/Fo/TunnelController.php @@ -6,14 +6,14 @@ namespace App\Http\Controllers\Fo; use App\Contracts\Executor; use App\Cqs\Actions\Orders\ApplyPickTimeSlot; -use App\Cqs\Actions\Orders\CancelPendingOrder; -use App\Cqs\Actions\Orders\CancelPendingOrderInput; use App\Cqs\Actions\Orders\ConfirmPlacedOrder; use App\Cqs\Actions\Orders\ConfirmPlacedOrderInput; use App\Cqs\Actions\Orders\ConfirmPlacedOrderOutput; use App\Cqs\Actions\Orders\ExportOrderToRegate; use App\Cqs\Actions\Orders\ExportOrderToRegateInput; use App\Cqs\Actions\Orders\ExportOrderToRegateOutput; +use App\Cqs\Actions\Orders\FailPendingOrder; +use App\Cqs\Actions\Orders\FailPendingOrderInput; use App\Cqs\Actions\Orders\InitializeOrderTunnel; use App\Cqs\Actions\Orders\PlacePendingOrder; use App\Cqs\Actions\Orders\PlacePendingOrderOutput; @@ -37,12 +37,15 @@ use Domain\Enums\OrderTunnelStep; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; use Infrastructure\Adapters\Services\AppCustomerAuthService; +use Shared\Concurrency\Lock; +use Shared\Concurrency\LockTimeoutException; class TunnelController extends Controller { public function __construct( private readonly AppCustomerAuthService $authService, private readonly Executor $executor, + private readonly Lock $checkoutLock, ) { } @@ -141,56 +144,79 @@ class TunnelController extends Controller PlacePendingOrder $placePendingOrder, ExportOrderToRegate $exportOrderToRegate, ConfirmPlacedOrder $confirmPlacedOrder, - CancelPendingOrder $cancelPendingOrder, + FailPendingOrder $failPendingOrder, ): RedirectResponse { $this->authorize('canFinalizeOrder', OrderTunnelStep::class); - /** @var PlacePendingOrderOutput $placeOutput */ - $placeOutput = $this->executor->execute( - $placePendingOrder, - $request->toPlacePendingOrderInput() - ); + $placeInput = $request->toPlacePendingOrderInput(); + $shopperId = $placeInput->shopperId ?? $this->authService->getCustomerAsMandatory()->getId(); - if ($placeOutput->status !== PlacePendingOrderStatus::PENDING_CREATED) { - return $this->redirectOnPendingFailure($placeOutput); - } + try { + return $this->checkoutLock->synchronize( + key: "order:checkout:shopper:{$shopperId->value}", + callback: function () use ( + $placePendingOrder, + $placeInput, + $exportOrderToRegate, + $confirmPlacedOrder, + $failPendingOrder, + ): RedirectResponse { + /** @var PlacePendingOrderOutput $placeOutput */ + $placeOutput = $this->executor->execute( + $placePendingOrder, + $placeInput + ); - $orderId = $placeOutput->orderId - ?? throw new \LogicException('Order ID is missing on pending created output.'); - $orderReference = $placeOutput->orderReference - ?? throw new \LogicException('Order reference is missing on pending created output.'); + if ($placeOutput->status !== PlacePendingOrderStatus::PENDING_CREATED) { + return $this->redirectOnPendingFailure($placeOutput); + } - /** @var ExportOrderToRegateOutput $exportOutput */ - $exportOutput = $this->executor->execute( - $exportOrderToRegate, - new ExportOrderToRegateInput($orderId) - ); + $orderId = $placeOutput->orderId + ?? throw new \LogicException('Order ID is missing on pending created output.'); + $orderReference = $placeOutput->orderReference + ?? throw new \LogicException('Order reference is missing on pending created output.'); - if ($exportOutput !== ExportOrderToRegateOutput::SENT) { - $this->executor->execute($cancelPendingOrder, new CancelPendingOrderInput($orderId)); + /** @var ExportOrderToRegateOutput $exportOutput */ + $exportOutput = $this->executor->execute( + $exportOrderToRegate, + new ExportOrderToRegateInput($orderId) + ); - return to_route('fo.sales.confirmation')->with( + if ($exportOutput !== ExportOrderToRegateOutput::SENT) { + $this->executor->execute($failPendingOrder, new FailPendingOrderInput($orderId)); + + return to_route('fo.sales.confirmation')->with( + 'message', + __('An error occurred while validating your order. Please try again later.') + ); + } + + /** @var ConfirmPlacedOrderOutput $confirmOutput */ + $confirmOutput = $this->executor->execute( + $confirmPlacedOrder, + new ConfirmPlacedOrderInput($orderId) + ); + + return match ($confirmOutput) { + ConfirmPlacedOrderOutput::CONFIRMED => to_route( + 'fo.sales.confirmation.show-confirmed', + (string) $orderReference + ), + ConfirmPlacedOrderOutput::FAILED => to_route('fo.sales.confirmation')->with( + 'message', + __('An error occurred while validating your order. Please try again later.') + ), + }; + }, + ttlSeconds: 60, + waitSeconds: 0, + ); + } catch (LockTimeoutException) { + return back()->with( 'message', - __('An error occurred while validating your order. Please try again later.') + __('Your order is already being processed. Please wait a moment and try again.') ); } - - /** @var ConfirmPlacedOrderOutput $confirmOutput */ - $confirmOutput = $this->executor->execute( - $confirmPlacedOrder, - new ConfirmPlacedOrderInput($orderId) - ); - - return match ($confirmOutput) { - ConfirmPlacedOrderOutput::CONFIRMED => to_route( - 'fo.sales.confirmation.show-confirmed', - (string) $orderReference - ), - ConfirmPlacedOrderOutput::FAILED => to_route('fo.sales.confirmation')->with( - 'message', - __('An error occurred while validating your order. Please try again later.') - ), - }; } private function redirectOnPendingFailure(PlacePendingOrderOutput $output): RedirectResponse diff --git a/app/Jobs/FailStalePendingOrdersJob.php b/app/Jobs/FailStalePendingOrdersJob.php new file mode 100644 index 00000000..bdb96787 --- /dev/null +++ b/app/Jobs/FailStalePendingOrdersJob.php @@ -0,0 +1,23 @@ +execute($action, new FailStalePendingOrdersInput()); + } +} diff --git a/app/Policies/Backend/OrderPolicy.php b/app/Policies/Backend/OrderPolicy.php index 4f5687cc..fc20609c 100644 --- a/app/Policies/Backend/OrderPolicy.php +++ b/app/Policies/Backend/OrderPolicy.php @@ -50,6 +50,7 @@ class OrderPolicy return false; } - return $user->role->isAtLeastEqualsTo(UserRole::Admin) && ! $order->status->equals(OrderStatus::CANCELED); + return $user->role->isAtLeastEqualsTo(UserRole::Admin) + && ! \in_array($order->status, [OrderStatus::CANCELED, OrderStatus::PENDING, OrderStatus::FAILED], true); } } diff --git a/app/Policies/Frontend/OrderPolicy.php b/app/Policies/Frontend/OrderPolicy.php index 27266eac..628bf56e 100644 --- a/app/Policies/Frontend/OrderPolicy.php +++ b/app/Policies/Frontend/OrderPolicy.php @@ -9,6 +9,7 @@ use App\Models\Customer; use App\Models\Order; use App\Models\User; use App\Services\OrderOwnershipService; +use Domain\Enums\OrderStatus; class OrderPolicy { @@ -32,6 +33,10 @@ class OrderPolicy return false; } + if (\in_array($order->status, [OrderStatus::PENDING, OrderStatus::FAILED], true)) { + return false; + } + return $this->orderOwnershipService->isOrderOwnedBy( $order, $user, diff --git a/bootstrap/jobs.php b/bootstrap/jobs.php index 4ea12613..065f1c06 100644 --- a/bootstrap/jobs.php +++ b/bootstrap/jobs.php @@ -4,6 +4,7 @@ declare(strict_types=1); use App\Jobs\DeleteOldResetTokens; use App\Jobs\EnsurePublicHolidaysSyncedJob; +use App\Jobs\FailStalePendingOrdersJob; use App\Jobs\SendMissingOrderReminderJob; use App\Jobs\SendReminderMail; use App\Jobs\UpdateSlidesStatus; @@ -14,6 +15,7 @@ use Illuminate\Support\Facades\Date; return function (Schedule $schedule): void { $schedule->job(DeleteOldResetTokens::class)->everyMinute(); $schedule->job(UpdateSlidesStatus::class)->everyMinute(); + $schedule->job(FailStalePendingOrdersJob::class)->onOneServer()->everyFiveMinutes(); // FIXME: The Arcadia jobs are currently disabled and need to be enabled when api will be available. // $schedule->job(FetchAndUpsertArcadiaEmployees::class)->onOneServer()->dailyAt('00:00'); diff --git a/resources/views/fo/tunnel/confirmation.blade.php b/resources/views/fo/tunnel/confirmation.blade.php index 3c16ac6c..6ea5957f 100644 --- a/resources/views/fo/tunnel/confirmation.blade.php +++ b/resources/views/fo/tunnel/confirmation.blade.php @@ -48,7 +48,7 @@

-
+ @csrf
@@ -74,3 +74,22 @@
@endsection + +@push('scripts') + +@endpush diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php index 0bbd1288..8ad770de 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php @@ -283,4 +283,88 @@ describe('OrderController', function () { $response->assertViewHas('order', fn ($orderData) => $orderData instanceof OrderDto && (string) $orderData->reference === $ref); $response->assertViewHas('mapUrl'); }); + + it('forbids viewing technical PENDING or FAILED orders on GET /compte/commandes/{reference}', function (OrderStatus $status) { + /** @var \Tests\TestCase $this */ + // GIVEN + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + $hashcode = new CrmHashcode(Uuid::uuid4()); + $customer = Customer::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'hashcode' => $hashcode->value, + 'email' => new Email('tech-order-' . $status->value . '@example.com'), + ]); + + Employee::query()->forceCreate([ + 'customer_id' => $customer->id, + 'matricule' => new Matricule('8888003'), + 'nom' => 'Martin', + 'prenom' => 'Paul', + 'code' => new Code('ABCDEF35'), + 'etablissement' => 'ETAB', + 'site' => 'SITE', + 'service' => '101', + 'created_at' => CarbonImmutable::now(), + 'updated_at' => CarbonImmutable::now(), + ]); + + $shop = Shop::factory()->create(); + $reference = new OrderReference(Uuid::uuid7()); + Order::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'shop_id' => $shop->id, + 'reference' => $reference, + 'status' => $status->value, + 'total' => new Money(5000, new Currency('EUR')), + 'employee' => new OrderEmployee( + new Matricule('8888003'), + 'Paul', + 'Martin', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), + 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), + 'pickup_day' => Date::now()->toDateString(), + ]); + + $crmCustomer = new CrmCustomer( + hashcode: $hashcode->value, + email: 'tech-order-' . $status->value . '@example.com', + password: 'pwd', + firstname: 'Paul', + lastname: 'Martin', + birthDate: null, + phone: '0123456789', + address: '10 rue test', + address2: null, + city: 'Paris', + postcode: '75000', + country: Country::france, + optIn: true, + status: true, + lastConnection: null, + ); + + $crmMock = \Mockery::mock(CrmService::class)->makePartial(); + $crmMock->shouldReceive('getCustomerFromHashCode')->andReturn($crmCustomer); + App::instance(CrmService::class, $crmMock); + + $this->actingAs($customer, 'frontend'); + + // WHEN + $response = $this->get('/compte/commandes/' . (string) $reference); + + // THEN + expect($response->status())->toBe(403); + })->with([ + 'pending' => [OrderStatus::PENDING], + 'failed' => [OrderStatus::FAILED], + ]); }); diff --git a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php index feb3317a..a71a7c7e 100644 --- a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php @@ -6,15 +6,15 @@ namespace Tests\Feature\App\Http\Controllers\Fo; use App\Contracts\Executor; use App\Cqs\Actions\Orders\ApplyPickTimeSlotOutput; -use App\Cqs\Actions\Orders\CancelPendingOrder; -use App\Cqs\Actions\Orders\CancelPendingOrderInput; -use App\Cqs\Actions\Orders\CancelPendingOrderOutput; use App\Cqs\Actions\Orders\ConfirmPlacedOrder; use App\Cqs\Actions\Orders\ConfirmPlacedOrderInput; use App\Cqs\Actions\Orders\ConfirmPlacedOrderOutput; use App\Cqs\Actions\Orders\ExportOrderToRegate; use App\Cqs\Actions\Orders\ExportOrderToRegateInput; use App\Cqs\Actions\Orders\ExportOrderToRegateOutput; +use App\Cqs\Actions\Orders\FailPendingOrder; +use App\Cqs\Actions\Orders\FailPendingOrderInput; +use App\Cqs\Actions\Orders\FailPendingOrderOutput; use App\Cqs\Actions\Orders\PlacePendingOrder; use App\Cqs\Actions\Orders\PlacePendingOrderInput; use App\Cqs\Actions\Orders\PlacePendingOrderOutput; @@ -71,6 +71,8 @@ use Domain\Ports\Services\OrderBuilderSessionManager; use Domain\Ports\Services\RegateService; use Domain\Services\BasketService; use Domain\Services\OrderTunnelService; +use Illuminate\Contracts\Cache\LockProvider; +use Illuminate\Contracts\Cache\Repository as CacheRepository; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Date; @@ -602,8 +604,8 @@ describe('TunnelController', function (): void { ->andReturn(ExportOrderToRegateOutput::FAILED); $mock->shouldReceive('execute') ->once() - ->with(\Mockery::type(CancelPendingOrder::class), \Mockery::type(CancelPendingOrderInput::class)) - ->andReturn(CancelPendingOrderOutput::CANCELLED); + ->with(\Mockery::type(FailPendingOrder::class), \Mockery::type(FailPendingOrderInput::class)) + ->andReturn(FailPendingOrderOutput::FAILED); }); // WHEN @@ -940,7 +942,7 @@ describe('TunnelController', function (): void { $order = new Order(); $order->reference = $orderReference; $order->total = Money::EUR(3000); - $order->status = OrderStatus::WAITING; + $order->status = OrderStatus::VALIDATED; $order->pickup_day = now()->addDays(2); $order->shop_id = $shop->id; $order->employee = new OrderEmployee( @@ -1157,7 +1159,7 @@ describe('TunnelController', function (): void { } }); - it('cancels pending order end-to-end without mocking Executor when Regate export fails', function (): void { + it('marks pending order as FAILED end-to-end without mocking Executor when Regate export fails', function (): void { /** @var \Tests\TestCase $this */ $now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris'); Date::setTestNow($now); @@ -1295,7 +1297,7 @@ describe('TunnelController', function (): void { // THEN $order = Order::query()->where('employee_matricule', '7654322')->first(); expect($order)->not->toBeNull() - ->and($order?->status)->toBe(OrderStatus::CANCELED) + ->and($order?->status)->toBe(OrderStatus::FAILED) ->and($basketService->hasItems())->toBeTrue(); $response->assertRedirectToRoute('fo.sales.confirmation') @@ -1307,4 +1309,147 @@ describe('TunnelController', function (): void { Carbon::setTestNow(); } }); + + it('rejects concurrent confirmation immediately when shopper checkout lock is already held', function (): void { + /** @var \Tests\TestCase $this */ + $now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); + + $heldLock = null; + + try { + // GIVEN + Mail::fake(); + Notification::fake(); + + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + $hashcode = new CrmHashcode(Uuid::uuid4()); + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'email' => new Email('e2e-lock@example.com'), + 'hashcode' => $hashcode, + ]); + + $crmCustomer = new CrmCustomer( + hashcode: $hashcode->value, + email: 'e2e-lock@example.com', + password: 'hashed-password', + firstname: 'Jean', + lastname: 'Dupont', + birthDate: null, + phone: null, + address: null, + address2: null, + city: null, + postcode: null, + country: Country::france, + optIn: false, + status: true, + lastConnection: null, + ); + + $crmService = $this->mock(CrmService::class); + $crmService->shouldReceive('getCustomerFromHashCode')->andReturn($crmCustomer); + + $employee = new Employee(); + $employee->matricule = new Matricule('7654323'); + $employee->code = new Code('ABCDEFJ'); + $employee->nom = 'Dupont'; + $employee->prenom = 'Jean'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITEA'); + $employee->service = new ShopperServiceCode('101'); + $employee->start_date = Date::now()->subMonth(); + $employee->end_date = null; + $employee->customer()->associate($customer); + $employee->saveOrFail(); + + $shop = new Shop(); + $shop->name = 'Boutique Sablé Lock'; + $shop->address = '10 rue Test'; + $shop->postcode = '72300'; + $shop->city = 'Sablé'; + $shop->default = true; + $shop->saveOrFail(); + + $range = new Range(); + $range->name = 'Gamme Lock'; + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $product = new Product(); + $product->name = 'Poulet Lock'; + $product->brand = ProductBrand::loue; + $product->description = 'Description Lock'; + $product->short_description = 'Court Lock'; + $product->price = Money::EUR(1500); + $product->invoicing_unit = InvoicingUnit::PCE; + $product->tax_rate = TaxRate::TVA_5_5; + $product->stock = 50; + $product->weight = 1000; + $product->sell_unit = SellUnit::PCE; + $product->order_unit = OrderUnit::PCE; + $product->range_id = $range->id; + $product->status = true; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt large'; + $product->picture_large_title = 'title large'; + $product->saveOrFail(); + + $inco = new ProductInco(); + $inco->product_id = $product->id; + $inco->no_art = 889903; + $inco->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + /** @var BasketService $basketService */ + $basketService = $this->app->make(BasketService::class); + $basketService->empty(); + $basketService->add($product->getId(), 2); + $basket = $basketService->getBasket(); + + $slot = new PickupTimeSlot( + CarbonImmutable::parse('2026-11-20 14:00:00', 'Europe/Paris'), + new \DateInterval('PT2H'), + ); + $builder = OrderBuilder::fromBasket($basket, $customer->getId()) + ->withPickupTimeSlot($shop->getId(), $slot); + $this->app->make(OrderBuilderSessionManager::class)->save($builder); + + $store = $this->app->make(CacheRepository::class)->getStore(); + assert($store instanceof LockProvider); + $heldLock = $store->lock("order:checkout:shopper:{$customer->id}", 60); + expect($heldLock->get())->toBeTrue(); + + // WHEN + $response = $this->from('/commande/confirmation')->post('/commande/confirmation', [ + 'ok_cgv' => '1', + ]); + + // THEN + $response->assertRedirect('/commande/confirmation') + ->assertSessionHas('message', __('Your order is already being processed. Please wait a moment and try again.')); + expect(Order::query()->count())->toBe(0); + Mail::assertNothingSent(); + } finally { + $heldLock?->release(); + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); + } + }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/FailStalePendingOrdersTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/FailStalePendingOrdersTest.php new file mode 100644 index 00000000..97e762b3 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/FailStalePendingOrdersTest.php @@ -0,0 +1,106 @@ +create(); + + $stalePendingId = Uuid::uuid7()->toString(); + $freshPendingId = Uuid::uuid7()->toString(); + $staleWaitingId = Uuid::uuid7()->toString(); + $staleValidatedId = Uuid::uuid7()->toString(); + + $baseRow = [ + 'shop_id' => $shop->id, + 'employee' => json_encode([ + 'matricule' => '1234567', + 'firstname' => 'Jean', + 'lastname' => 'Dupont', + 'facility' => 'FAC01', + 'site' => 'SITEA', + 'service' => '101', + ]), + 'delivery_address' => json_encode(new DeliveryAddress('Boutique', '1 rue Test', '72300', 'Sablé')), + 'pickup_day' => '2026-11-20', + 'total' => 1500, + ]; + + DB::table('orders')->insert([ + array_merge($baseRow, [ + 'id' => $stalePendingId, + 'reference' => (string) new OrderReference(Uuid::uuid7()), + 'status' => OrderStatus::PENDING->value, + 'updated_at' => $now->subMinutes(15)->toDateTimeString(), + ]), + array_merge($baseRow, [ + 'id' => $freshPendingId, + 'reference' => (string) new OrderReference(Uuid::uuid7()), + 'status' => OrderStatus::PENDING->value, + 'updated_at' => $now->subMinutes(4)->toDateTimeString(), + ]), + array_merge($baseRow, [ + 'id' => $staleWaitingId, + 'reference' => (string) new OrderReference(Uuid::uuid7()), + 'status' => OrderStatus::WAITING->value, + 'updated_at' => $now->subHours(2)->toDateTimeString(), + ]), + array_merge($baseRow, [ + 'id' => $staleValidatedId, + 'reference' => (string) new OrderReference(Uuid::uuid7()), + 'status' => OrderStatus::VALIDATED->value, + 'updated_at' => $now->subHours(2)->toDateTimeString(), + ]), + ]); + + $orderRepo = new EloquentOrderRepository(); + $action = new FailStalePendingOrders($orderRepo, new OrderService($orderRepo), new NullLogger()); + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN + $failedCount = $executor->execute($action, new FailStalePendingOrdersInput(ttlMinutes: 10)); + + // THEN + expect($failedCount)->toBe(1) + ->and(Order::query()->find($stalePendingId)?->status)->toBe(OrderStatus::FAILED) + ->and(Order::query()->find($freshPendingId)?->status)->toBe(OrderStatus::PENDING) + ->and(Order::query()->find($staleWaitingId)?->status)->toBe(OrderStatus::WAITING) + ->and(Order::query()->find($staleValidatedId)?->status)->toBe(OrderStatus::VALIDATED); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php index 3ad7603b..eab56504 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -4,15 +4,15 @@ declare(strict_types=1); namespace Tests\Integration\WithApp\App\Cqs\Actions\Orders; -use App\Cqs\Actions\Orders\CancelPendingOrder; -use App\Cqs\Actions\Orders\CancelPendingOrderInput; -use App\Cqs\Actions\Orders\CancelPendingOrderOutput; use App\Cqs\Actions\Orders\ConfirmPlacedOrder; use App\Cqs\Actions\Orders\ConfirmPlacedOrderInput; use App\Cqs\Actions\Orders\ConfirmPlacedOrderOutput; use App\Cqs\Actions\Orders\ExportOrderToRegate; use App\Cqs\Actions\Orders\ExportOrderToRegateInput; use App\Cqs\Actions\Orders\ExportOrderToRegateOutput; +use App\Cqs\Actions\Orders\FailPendingOrder; +use App\Cqs\Actions\Orders\FailPendingOrderInput; +use App\Cqs\Actions\Orders\FailPendingOrderOutput; use App\Cqs\Actions\Orders\PlacePendingOrder; use App\Cqs\Actions\Orders\PlacePendingOrderInput; use App\Enums\PlacePendingOrderStatus; @@ -283,15 +283,15 @@ describe('Order placement two-step CQS actions', function (): void { $exportAction = new ExportOrderToRegate($ctx['tunnelService']); $confirmAction = new ConfirmPlacedOrder($ctx['tunnelService']); - // WHEN: Step 1 - create pending WAITING order + // WHEN: Step 1 - create pending PENDING order $placeOutput = $ctx['executor']->execute($placeAction, new PlacePendingOrderInput($ctx['customer']->getId())); - // THEN: Order is WAITING and no notifications or emails were sent yet + // THEN: Order is PENDING and no notifications or emails were sent yet expect($placeOutput->status)->toBe(PlacePendingOrderStatus::PENDING_CREATED) ->and($placeOutput->orderId)->toBeInstanceOf(OrderId::class); $pendingOrder = Order::query()->find($placeOutput->orderId?->value->toString()); - expect($pendingOrder?->status)->toBe(OrderStatus::WAITING); + expect($pendingOrder?->status)->toBe(OrderStatus::PENDING); Notification::assertNothingSent(); // WHEN: Step 2 - export to Regate outside any extra SQL transaction @@ -316,7 +316,7 @@ describe('Order placement two-step CQS actions', function (): void { expect($ctx['basketRepository']->find($ctx['basketId']))->toBeNull(); }); - it('cancels WAITING order cleanly and keeps basket intact when Regate export fails', function (): void { + it('marks PENDING order as FAILED cleanly, frees weekly limit and keeps basket intact when Regate export fails', function (): void { // GIVEN /** @var \Domain\Ports\Services\RegateService&\Mockery\MockInterface $failingRegate */ $failingRegate = \Mockery::mock(RegateService::class); @@ -327,21 +327,21 @@ describe('Order placement two-step CQS actions', function (): void { $ctx = buildOrderPlacementScenario(regateService: $failingRegate); $placeAction = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']); $exportAction = new ExportOrderToRegate($ctx['tunnelService']); - $cancelAction = new CancelPendingOrder($ctx['tunnelService']); + $failAction = new FailPendingOrder($ctx['tunnelService']); // WHEN - $placeOutput = $ctx['executor']->execute($placeAction, new PlacePendingOrderInput($ctx['customer']->getId())); + $placeOutput = $ctx['executor']->execute($placeAction, new PlacePendingOrderInput($ctx['customer']->getId())); /** @var OrderId $orderId */ $orderId = $placeOutput->orderId; $exportOutput = $ctx['executor']->execute($exportAction, new ExportOrderToRegateInput($orderId)); - $cancelOutput = $ctx['executor']->execute($cancelAction, new CancelPendingOrderInput($orderId)); + $failOutput = $ctx['executor']->execute($failAction, new FailPendingOrderInput($orderId)); // THEN expect($exportOutput)->toBe(ExportOrderToRegateOutput::FAILED) - ->and($cancelOutput)->toBe(CancelPendingOrderOutput::CANCELLED); + ->and($failOutput)->toBe(FailPendingOrderOutput::FAILED); $persistedOrder = Order::query()->find($orderId->value->toString()); - expect($persistedOrder?->status)->toBe(OrderStatus::CANCELED) + expect($persistedOrder?->status)->toBe(OrderStatus::FAILED) ->and($ctx['basketRepository']->find($ctx['basketId']))->not->toBeNull(); Mail::assertNothingQueued(); Notification::assertNothingSent(); @@ -382,7 +382,7 @@ describe('Order placement two-step CQS actions', function (): void { Mail::assertNothingSent(); }); - it('counts existing WAITING orders toward weekly limit to prevent concurrent overspending', function (): void { + it('counts existing PENDING orders toward weekly limit to prevent concurrent overspending', function (): void { // GIVEN $ctx = buildOrderPlacementScenario(priceCents: 6000, qty: 1); @@ -390,7 +390,7 @@ describe('Order placement two-step CQS actions', function (): void { 'id' => Uuid::uuid7()->toString(), 'shop_id' => $ctx['shop']->id, 'reference' => new OrderReference(Uuid::uuid7()), - 'status' => OrderStatus::WAITING->value, + 'status' => OrderStatus::PENDING->value, 'total' => Money::EUR(16000), 'employee' => new OrderEmployee( $ctx['employee']->matricule, diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoPaginatedOrdersQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoPaginatedOrdersQueryTest.php index 320756d8..bc1063fd 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoPaginatedOrdersQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoPaginatedOrdersQueryTest.php @@ -323,4 +323,49 @@ describe('GetBoPaginatedOrdersQuery', function (): void { ->and($output->orders->items()[0]->id)->toBe($waitingOrder->id) ->and($output->orders->items()[0]->status)->toBe(OrderStatus::WAITING); }); + + it('excludes PENDING and FAILED orders by default and shows them when explicitly filtered', function () use ( + $createShop, + $createOrder, + $makeQuery, + ): void { + // GIVEN + $shop = $createShop('Boutique Technique'); + $pickupDay = CarbonImmutable::parse('2026-05-01'); + + Carbon::setTestNow(CarbonImmutable::parse('2026-04-01 10:00:00')); + $validated = $createOrder($shop, OrderStatus::VALIDATED, $pickupDay); + + Carbon::setTestNow(CarbonImmutable::parse('2026-04-01 10:00:01')); + $pending = $createOrder($shop, OrderStatus::PENDING, $pickupDay); + + Carbon::setTestNow(CarbonImmutable::parse('2026-04-01 10:00:02')); + $failed = $createOrder($shop, OrderStatus::FAILED, $pickupDay); + + $query = $makeQuery(); + $pagination = Pagination::ofPage(new PageNumber(1), new PageSize(10)); + + // WHEN: no status filter (default BO list) + $defaultOutput = $query(new GetBoPaginatedOrdersQueryInput(pagination: $pagination)); + + // THEN + expect($defaultOutput->orders->total())->toBe(1) + ->and($defaultOutput->orders->items()[0]->id)->toBe($validated->id); + + // WHEN: explicitly filtering on PENDING or FAILED + $pendingOutput = $query(new GetBoPaginatedOrdersQueryInput( + pagination: $pagination, + status: OrderStatus::PENDING, + )); + $failedOutput = $query(new GetBoPaginatedOrdersQueryInput( + pagination: $pagination, + status: OrderStatus::FAILED, + )); + + // THEN + expect($pendingOutput->orders->total())->toBe(1) + ->and($pendingOutput->orders->items()[0]->id)->toBe($pending->id) + ->and($failedOutput->orders->total())->toBe(1) + ->and($failedOutput->orders->items()[0]->id)->toBe($failed->id); + }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoTodayOrdersQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoTodayOrdersQueryTest.php new file mode 100644 index 00000000..abfb405e --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoTodayOrdersQueryTest.php @@ -0,0 +1,86 @@ +create(); + + $createOrder = static function (OrderStatus $status) use ($shop): Order { + $order = new Order(); + $order->reference = new OrderReference(Uuid::uuid7()); + $order->total = Money::EUR(2000); + $order->status = $status; + $order->pickup_day = Date::now()->addDays(4); + $order->shop_id = $shop->id; + $order->delivery_address = new DeliveryAddress('Shop', '1 rue Test', '72300', 'Sablé'); + $order->employee = new OrderEmployee( + matricule: new Matricule('1234567'), + firstname: 'Jean', + lastname: 'Dupont', + facility: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), + ); + $order->save(); + + return $order; + }; + + $validated = $createOrder(OrderStatus::VALIDATED); + $waiting = $createOrder(OrderStatus::WAITING); + $canceled = $createOrder(OrderStatus::CANCELED); + $createOrder(OrderStatus::PENDING); + $createOrder(OrderStatus::FAILED); + + $request = new Request(); + $session = app('session.store'); + $query = new GetBoTodayOrdersQuery( + new DataTableService($request, $session, static fn (): array => ['id', 'reference', 'status']), + ); + + // WHEN + $result = $query(new GetBoTodayOrdersQueryInput( + Pagination::ofPage(new PageNumber(1), new PageSize(20)), + )); + + // THEN + $ids = array_map(static fn ($dto): string => $dto->id, $result->items()); + expect($result->total())->toBe(3) + ->and($ids)->toContain($validated->id, $waiting->id, $canceled->id); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQueryTest.php index a410bd02..dd0c0b99 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQueryTest.php @@ -169,4 +169,40 @@ describe('GetFoCustomerPaginatedOrdersQuery', function (): void { ->and($page2->items())->toHaveCount(1) ->and($page2->items()[0]->id)->toBe($order1->id); }); + + it('excludes PENDING and FAILED technical orders from customer order history', function () use ( + $createCustomer, + $createEmployee, + $createShop, + $createOrder, + ): void { + // GIVEN + $customer = $createCustomer(); + $createEmployee($customer, '1234568', 'HJKMNPS'); + $shop = $createShop(); + + $validated = $createOrder($shop, '1234568'); + $validated->status = OrderStatus::VALIDATED; + $validated->save(); + + $pending = $createOrder($shop, '1234568'); + $pending->status = OrderStatus::PENDING; + $pending->save(); + + $failed = $createOrder($shop, '1234568'); + $failed->status = OrderStatus::FAILED; + $failed->save(); + + $query = new GetFoCustomerPaginatedOrdersQuery(); + + // WHEN + $result = $query(new GetFoCustomerPaginatedOrdersQueryInput( + customer: $customer, + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), + )); + + // THEN + expect($result->total())->toBe(1) + ->and($result->items()[0]->id)->toBe($validated->id); + }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php index 1ecba95f..972932ae 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php @@ -37,7 +37,7 @@ describe('GetTunnelOrderConfirmedQuery', function (): void { $order = new Order(); $order->reference = $reference; $order->total = Money::EUR(2500); - $order->status = OrderStatus::WAITING; + $order->status = OrderStatus::VALIDATED; $order->pickup_day = now()->addDays(2); $order->shop_id = $shop->id; $order->delivery_address = new DeliveryAddress( @@ -75,7 +75,7 @@ describe('GetTunnelOrderConfirmedQuery', function (): void { $order = new Order(); $order->reference = $reference; $order->total = Money::EUR(2500); - $order->status = OrderStatus::WAITING; + $order->status = OrderStatus::VALIDATED; $order->pickup_day = now()->addDays(2); $order->shop_id = null; $order->employee = new OrderEmployee( diff --git a/tests/TestCase.php b/tests/TestCase.php index 7be6956d..fd665209 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -7,6 +7,7 @@ namespace Tests; use App\Services\CrmService; use GuzzleHttp\Psr7\Response as GuzzleResponse; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; +use Illuminate\Support\Facades\Config; use LDC\LDCCRM\CrmApiV4; use LDC\LDCCRM\Enums\ApiStatus; use LDC\LDCCRM\Models\ClientModel; @@ -23,6 +24,8 @@ abstract class TestCase extends BaseTestCase { parent::setUp(); + Config::set('purifier.cachePath', sys_get_temp_dir() . '/purifier-testing-' . get_current_user()); + $this->mockCrmTransport(); } diff --git a/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php index 6e85b58b..dc13eebd 100644 --- a/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php +++ b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -6,15 +6,15 @@ namespace Tests\Unit\App\Cqs\Actions\Orders; use App\Contracts\HandlesFailure; use App\Contracts\HandlesSuccess; -use App\Cqs\Actions\Orders\CancelPendingOrder; -use App\Cqs\Actions\Orders\CancelPendingOrderInput; -use App\Cqs\Actions\Orders\CancelPendingOrderOutput; use App\Cqs\Actions\Orders\ConfirmPlacedOrder; use App\Cqs\Actions\Orders\ConfirmPlacedOrderInput; use App\Cqs\Actions\Orders\ConfirmPlacedOrderOutput; use App\Cqs\Actions\Orders\ExportOrderToRegate; use App\Cqs\Actions\Orders\ExportOrderToRegateInput; use App\Cqs\Actions\Orders\ExportOrderToRegateOutput; +use App\Cqs\Actions\Orders\FailPendingOrder; +use App\Cqs\Actions\Orders\FailPendingOrderInput; +use App\Cqs\Actions\Orders\FailPendingOrderOutput; use App\Cqs\Actions\Orders\PlacePendingOrder; use App\Cqs\Actions\Orders\PlacePendingOrderInput; use App\Cqs\Actions\Orders\PlacePendingOrderOutput; @@ -210,7 +210,7 @@ describe('PlacePendingOrder', function (): void { }); }); -describe('ExportOrderToRegate, ConfirmPlacedOrder and CancelPendingOrder', function (): void { +describe('ExportOrderToRegate, ConfirmPlacedOrder and FailPendingOrder', function (): void { it('exports order via OrderTunnelService and handles lock timeout', function (): void { // GIVEN $orderId = new OrderId(Uuid::uuid7()); @@ -231,7 +231,7 @@ describe('ExportOrderToRegate, ConfirmPlacedOrder and CancelPendingOrder', funct ->and($action->onLockTimeout($input))->toBe(ExportOrderToRegateOutput::LOCK_TIMEOUT); }); - it('confirms a placed order and cancels a pending order', function (): void { + it('confirms a placed order and fails a pending order', function (): void { // GIVEN $orderId = new OrderId(Uuid::uuid7()); $order = new Order( @@ -264,19 +264,19 @@ describe('ExportOrderToRegate, ConfirmPlacedOrder and CancelPendingOrder', funct ->once() ->with($orderId) ->andReturn($order); - $orderTunnelService->shouldReceive('cancelPendingOrder') + $orderTunnelService->shouldReceive('failPendingOrder') ->once() ->with($orderId); $confirmAction = new ConfirmPlacedOrder($orderTunnelService); - $cancelAction = new CancelPendingOrder($orderTunnelService); + $failAction = new FailPendingOrder($orderTunnelService); // WHEN $confirmResult = $confirmAction(new ConfirmPlacedOrderInput($orderId)); - $cancelResult = $cancelAction(new CancelPendingOrderInput($orderId)); + $failResult = $failAction(new FailPendingOrderInput($orderId)); // THEN expect($confirmResult)->toBe(ConfirmPlacedOrderOutput::CONFIRMED) - ->and($cancelResult)->toBe(CancelPendingOrderOutput::CANCELLED); + ->and($failResult)->toBe(FailPendingOrderOutput::FAILED); }); }); diff --git a/tests/Unit/App/Policies/Backend/OrderPolicyTest.php b/tests/Unit/App/Policies/Backend/OrderPolicyTest.php index 178cb410..8f273f23 100644 --- a/tests/Unit/App/Policies/Backend/OrderPolicyTest.php +++ b/tests/Unit/App/Policies/Backend/OrderPolicyTest.php @@ -132,6 +132,24 @@ describe('OrderPolicy', function () { expect($result)->toBeFalse(); }); + test('cancel returns false for admin user when order is PENDING or FAILED', function (OrderStatus $status) { + // GIVEN + $user = new User(); + $user->role = UserRole::Admin; + $order = new Order(); + $order->status = $status; + $policy = new OrderPolicy(); + + // WHEN + $result = $policy->cancel($user, $order); + + // THEN + expect($result)->toBeFalse(); + })->with([ + 'pending' => [OrderStatus::PENDING], + 'failed' => [OrderStatus::FAILED], + ]); + test('cancel returns true for admin user even when order pickup day is in the past', function () { // GIVEN $user = new User(); diff --git a/tests/Unit/App/Policies/Frontend/OrderPolicyTest.php b/tests/Unit/App/Policies/Frontend/OrderPolicyTest.php index 122d68f0..f9a74743 100644 --- a/tests/Unit/App/Policies/Frontend/OrderPolicyTest.php +++ b/tests/Unit/App/Policies/Frontend/OrderPolicyTest.php @@ -9,6 +9,7 @@ use App\Models\Order; use App\Models\User; use App\Policies\Frontend\OrderPolicy; use App\Services\OrderOwnershipService; +use Domain\Enums\OrderStatus; covers(OrderPolicy::class); @@ -83,10 +84,11 @@ describe('OrderPolicy', function () { it('returns true when user is a Customer and owns the order', function () { // GIVEN - $orderService = \Mockery::mock(OrderOwnershipService::class); - $policy = new OrderPolicy($orderService); - $customer = \Mockery::mock(Customer::class); - $order = \Mockery::mock(Order::class); + $orderService = \Mockery::mock(OrderOwnershipService::class); + $policy = new OrderPolicy($orderService); + $customer = \Mockery::mock(Customer::class); + $order = new Order(); + $order->status = OrderStatus::VALIDATED; $orderService->shouldReceive('isOrderOwnedBy') ->once() @@ -102,10 +104,11 @@ describe('OrderPolicy', function () { it('returns false when user is a Customer and does not own the order', function () { // GIVEN - $orderService = \Mockery::mock(OrderOwnershipService::class); - $policy = new OrderPolicy($orderService); - $customer = \Mockery::mock(Customer::class); - $order = \Mockery::mock(Order::class); + $orderService = \Mockery::mock(OrderOwnershipService::class); + $policy = new OrderPolicy($orderService); + $customer = \Mockery::mock(Customer::class); + $order = new Order(); + $order->status = OrderStatus::VALIDATED; $orderService->shouldReceive('isOrderOwnedBy') ->once() @@ -118,5 +121,24 @@ describe('OrderPolicy', function () { // THEN expect($result)->toBeFalse(); }); + + it('returns false when order status is PENDING or FAILED even if owned by customer', function (OrderStatus $status) { + // GIVEN + $orderService = \Mockery::mock(OrderOwnershipService::class); + $orderService->shouldNotReceive('isOrderOwnedBy'); + $policy = new OrderPolicy($orderService); + $customer = \Mockery::mock(Customer::class); + $order = new Order(); + $order->status = $status; + + // WHEN + $result = $policy->viewOwn($customer, $order); + + // THEN + expect($result)->toBeFalse(); + })->with([ + 'pending' => [OrderStatus::PENDING], + 'failed' => [OrderStatus::FAILED], + ]); }); }); From 3b24436263136699c09953bd6949fa0d3adac9cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 20:19:31 +0100 Subject: [PATCH 166/183] feat(stats,orders): track tunnel attempts in DB to preserve waiting stats --- REGLES METIERS.md | 16 +- .../ResetTunnelAttemptOnBasketRemoved.php | 22 ++ app/Models/OrderTunnelAttempt.php | 65 ++++ app/Providers/ShoppingServiceProvider.php | 12 + app/Services/StatsService.php | 12 +- ...000_create_order_tunnel_attempts_table.php | 27 ++ .../Services/TunnelAttemptTrackerService.php | 17 ++ domain/Services/OrderTunnelService.php | 4 + .../DatabaseTunnelAttemptTrackerService.php | 73 +++++ .../Controllers/Fo/TunnelControllerTest.php | 281 ++++++++++++++++++ .../Actions/Orders/ApplyPickTimeSlotTest.php | 2 + .../Orders/InitializeOrderTunnelTest.php | 13 +- .../Actions/Orders/PlacePendingOrderTest.php | 2 + .../WithApp/App/Services/StatsServiceTest.php | 64 ++++ ...atabaseTunnelAttemptTrackerServiceTest.php | 147 +++++++++ .../Services/OrderTunnelServiceTest.php | 88 ++++++ 16 files changed, 840 insertions(+), 5 deletions(-) create mode 100644 app/Listeners/Orders/ResetTunnelAttemptOnBasketRemoved.php create mode 100644 app/Models/OrderTunnelAttempt.php create mode 100644 database/migrations/2026_11_16_190000_create_order_tunnel_attempts_table.php create mode 100644 domain/Ports/Services/TunnelAttemptTrackerService.php create mode 100644 infra/Adapters/Services/DatabaseTunnelAttemptTrackerService.php create mode 100644 tests/Integration/WithApp/Infra/Adapters/Services/DatabaseTunnelAttemptTrackerServiceTest.php diff --git a/REGLES METIERS.md b/REGLES METIERS.md index 14d0d2bf..757d3f92 100644 --- a/REGLES METIERS.md +++ b/REGLES METIERS.md @@ -56,11 +56,23 @@ Elle est vérifiée côté Domaine par `Shopper::isActive()` et côté Eloquent - Le salarié est actif uniquement si `end_date` est `null` ou strictement supérieure au jour courant en `Europe/Paris` (`end_date > aujourd'hui Europe/Paris`). - **Comportement assumé** : le salarié devient donc inactif dès `00:00:00 Europe/Paris` de son dernier jour renseigné (`end_date`). -## 5. Annulation de Commande (Back-Office) +## 5. Cycle de Vie, Tunnel de Commande & Annulation (Back-Office) +### Statuts des commandes (`Domain\Enums\OrderStatus`) +- **`WAITING` (`1`)** : reliquat historique des commandes créées avant la refonte (paniers non transformés). Conservé en lecture dans les statistiques historiques. +- **`PENDING` (`2`)** : commande technique créée lors de `PlacePendingOrder` avant l'export Régate. Elle est comptabilisée dans le plafond hebdomadaire de 200 € (`EloquentEmployeeStatisticsService`), masquée en Front-Office (`GetFoCustomerPaginatedOrdersQuery`, `Frontend\OrderPolicy::viewOwn`) et masquée par défaut en Back-Office (affichable à la demande via le filtre statut). +- **`VALIDATED` (`3`)** : commande confirmée après succès de l'export Régate (`ConfirmPlacedOrder`). +- **`FAILED` (`4`)** : statut technique en cas d'échec de l'export Régate (`FailPendingOrder`) ou d'expiration d'une commande `PENDING` bloquée au-delà de 10 minutes (`FailStalePendingOrders` / `FailStalePendingOrdersJob`, planifié toutes les 5 minutes). Masqué en Front-Office, affichable à la demande en Back-Office, exclu du plafond hebdomadaire et des statistiques. +- **`CANCELED` (`7`)** : annulation métier (Back-Office ou Régate). + +### Concurrence du tunnel & suivi des paniers non transformés +- Lors de la soumission finale (`TunnelController::confirmationSubmit()`), un verrou distribué non bloquant (`order:checkout:shopper:{id}`, `waitSeconds: 0`, TTL `60s`) protège la séquence synchrone `PlacePendingOrder` (elle-même protégée par `#[Locked]` sur `order:finalize:shopper:{id}`) → `ExportOrderToRegate` → `ConfirmPlacedOrder` / `FailPendingOrder`. +- Les entrées dans le tunnel (étape 1, `OrderTunnelService::initializeFromBasket`) créent ou réutilisent une tentative en session dans `order_tunnel_attempts` (`TunnelAttemptTrackerService::recordEntry`), marquée convertie lors de la validation (`markConverted`) ou réinitialisée en session si le panier est vidé (`BasketRemoved` → `ResetTunnelAttemptOnBasketRemoved`). `StatsService::getNbWaitingCmd()` (et `getCanceledRate()`) additionnent les commandes historiques `WAITING` et les tentatives `order_tunnel_attempts` non converties (`converted_at IS NULL`). + +### Annulation de Commande (Back-Office) Elle est autorisée côté HTTP par `App\Policies\Backend\OrderPolicy::cancel()` et exécutée côté Domaine par `Domain\Services\OrderService::cancelOrder()`. -- **Statuts & date de retrait (`pickup_day`)** : toutes les commandes finalisées sont créées directement au statut `OrderStatus::VALIDATED` (aucun statut `COMPLETED` n'existe). `Backend\OrderPolicy::cancel()` autorise intentionnellement un administrateur à annuler toute commande non encore annulée, y compris lorsque `pickup_day` est déjà dépassé (rattrapage/correction administrative). +- **Statuts autorisés & date de retrait (`pickup_day`)** : `Backend\OrderPolicy::cancel()` interdit d'annuler une commande déjà `CANCELED`, `PENDING` ou `FAILED`, mais autorise intentionnellement un administrateur à annuler toute commande métier (`WAITING` ou `VALIDATED`), y compris lorsque `pickup_day` est déjà dépassé (rattrapage/correction administrative). - **Comportement assumé** : l'annulation d'une commande depuis le Back-Office met uniquement à jour son statut en base de données (`cancel()` puis `persist()`) sans émettre d'événement de domaine ni envoyer d'e-mail ou de notification à Régate ou au client. ## 6. Code d'Accès Salarié & Inscription diff --git a/app/Listeners/Orders/ResetTunnelAttemptOnBasketRemoved.php b/app/Listeners/Orders/ResetTunnelAttemptOnBasketRemoved.php new file mode 100644 index 00000000..4205d64e --- /dev/null +++ b/app/Listeners/Orders/ResetTunnelAttemptOnBasketRemoved.php @@ -0,0 +1,22 @@ +tunnelAttemptTracker->clearActiveSession(); + } +} diff --git a/app/Models/OrderTunnelAttempt.php b/app/Models/OrderTunnelAttempt.php new file mode 100644 index 00000000..ee92e7f2 --- /dev/null +++ b/app/Models/OrderTunnelAttempt.php @@ -0,0 +1,65 @@ +toString(); + } + + /** + * @return BelongsTo + */ + public function customer(): BelongsTo + { + return $this->belongsTo(Customer::class); + } + + /** + * @return BelongsTo + */ + public function order(): BelongsTo + { + return $this->belongsTo(Order::class); + } + + #[\Override] + protected function casts(): array + { + return [ + 'converted_at' => UtcDatetimeCast::class, + 'created_at' => UtcDatetimeCast::class, + 'updated_at' => UtcDatetimeCast::class, + ]; + } +} diff --git a/app/Providers/ShoppingServiceProvider.php b/app/Providers/ShoppingServiceProvider.php index 1d10a9f1..42feda91 100644 --- a/app/Providers/ShoppingServiceProvider.php +++ b/app/Providers/ShoppingServiceProvider.php @@ -8,6 +8,7 @@ use Domain\Ports\Repositories\BasketRepository; use Domain\Ports\Repositories\ProductRepository; use Domain\Ports\Services\OrderBuilderSessionManager; use Domain\Ports\Services\SessionService; +use Domain\Ports\Services\TunnelAttemptTrackerService; use Domain\Services\BasketService; use Illuminate\Contracts\Session\Session; use Illuminate\Foundation\Application; @@ -16,6 +17,7 @@ use Illuminate\Support\ServiceProvider; use Infrastructure\Adapters\Repositories\SessionBasketRepository; use Infrastructure\Adapters\Serializers\BasketSerializer; use Infrastructure\Adapters\Services\AppSessionService; +use Infrastructure\Adapters\Services\DatabaseTunnelAttemptTrackerService; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; use Shared\DDD\DomainEventDispatcher; @@ -25,6 +27,8 @@ class ShoppingServiceProvider extends ServiceProvider private const string ORDER_BUILDER_SESSION_KEY = 'order_tunnel_builder_session'; + private const string ORDER_TUNNEL_ATTEMPT_SESSION_KEY = 'order_tunnel_attempt_id'; + /** * Bootstrap the application services. * @@ -54,6 +58,14 @@ class ShoppingServiceProvider extends ServiceProvider ) ); + App::scoped( + TunnelAttemptTrackerService::class, + fn (Application $app) => new DatabaseTunnelAttemptTrackerService( + $app->make(Session::class), + self::ORDER_TUNNEL_ATTEMPT_SESSION_KEY + ) + ); + App::scoped(BasketService::class, fn (Application $app) => new BasketService( $app->make(BasketRepository::class), $app->make(ProductRepository::class), diff --git a/app/Services/StatsService.php b/app/Services/StatsService.php index ec3fa7b2..03ea91ac 100644 --- a/app/Services/StatsService.php +++ b/app/Services/StatsService.php @@ -8,6 +8,7 @@ use App\Models\Customer; use App\Models\Employee; use App\Models\Order; use App\Models\OrderLine; +use App\Models\OrderTunnelAttempt; use Carbon\CarbonInterface; use Carbon\CarbonPeriod; use Domain\Enums\OrderStatus; @@ -199,7 +200,16 @@ class StatsService */ private function getNbWaitingCmd(CarbonInterface $start, CarbonInterface $end): int { - return $this->countOrdersByStatus(OrderStatus::WAITING, $start, $end); + $legacyWaiting = $this->countOrdersByStatus(OrderStatus::WAITING, $start, $end); + $unconvertedAttempts = OrderTunnelAttempt::query() + ->whereNull('converted_at') + ->whereBetween('created_at', [ + $start->copy()->startOfDay()->utc(), + $end->copy()->endOfDay()->utc(), + ]) + ->count(); + + return $legacyWaiting + $unconvertedAttempts; } /** diff --git a/database/migrations/2026_11_16_190000_create_order_tunnel_attempts_table.php b/database/migrations/2026_11_16_190000_create_order_tunnel_attempts_table.php new file mode 100644 index 00000000..744d5613 --- /dev/null +++ b/database/migrations/2026_11_16_190000_create_order_tunnel_attempts_table.php @@ -0,0 +1,27 @@ +uuid('id')->primary(); + $table->foreignUuid('customer_id')->nullable()->constrained('customers')->nullOnDelete(); + $table->foreignUuid('order_id')->nullable()->constrained('orders')->nullOnDelete(); + $table->timestamp('converted_at')->nullable()->index(); + $table->timestamps(); + $table->index('created_at'); + }); + } + + public function down(): void + { + Schema::dropIfExists('order_tunnel_attempts'); + } +}; diff --git a/domain/Ports/Services/TunnelAttemptTrackerService.php b/domain/Ports/Services/TunnelAttemptTrackerService.php new file mode 100644 index 00000000..8b2ff737 --- /dev/null +++ b/domain/Ports/Services/TunnelAttemptTrackerService.php @@ -0,0 +1,17 @@ +orderBuilderSessionManager->save($builder); + $this->tunnelAttemptTracker->recordEntry($customerId); } /** @@ -208,6 +211,7 @@ class OrderTunnelService { $order = $this->orderService->validateOrder($orderId); + $this->tunnelAttemptTracker->markConverted($order->id()); $this->eventDispatcher->dispatch($order->toPlacedEvent()); return $order; diff --git a/infra/Adapters/Services/DatabaseTunnelAttemptTrackerService.php b/infra/Adapters/Services/DatabaseTunnelAttemptTrackerService.php new file mode 100644 index 00000000..8e492ed2 --- /dev/null +++ b/infra/Adapters/Services/DatabaseTunnelAttemptTrackerService.php @@ -0,0 +1,73 @@ +session->get($this->sessionKey); + + if (is_string($attemptId) && $attemptId !== '') { + $exists = OrderTunnelAttempt::query() + ->whereKey($attemptId) + ->whereNull('converted_at') + ->where('customer_id', $customerId->value->toString()) + ->exists(); + + if ($exists) { + return; + } + } + + $attempt = new OrderTunnelAttempt(); + $attempt->customer_id = $customerId->value->toString(); + $attempt->saveOrFail(); + + $this->session->put($this->sessionKey, $attempt->id); + } + + #[\Override] + public function markConverted(OrderId $orderId): void + { + $attemptId = $this->session->get($this->sessionKey); + + if (! is_string($attemptId) || $attemptId === '') { + return; + } + + $attempt = OrderTunnelAttempt::query()->find($attemptId); + + if ($attempt !== null && $attempt->converted_at === null) { + $attempt->order_id = $orderId->value->toString(); + $attempt->converted_at = Date::now(); + $attempt->saveOrFail(); + } + + $this->session->forget($this->sessionKey); + } + + #[\Override] + public function clearActiveSession(): void + { + $this->session->forget($this->sessionKey); + } +} diff --git a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php index a71a7c7e..a5ed75fb 100644 --- a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php @@ -29,6 +29,7 @@ use App\Mail\RegateOrderMail; use App\Models\Customer; use App\Models\Employee; use App\Models\Order; +use App\Models\OrderTunnelAttempt; use App\Models\Page; use App\Models\Product; use App\Models\ProductInco; @@ -1452,4 +1453,284 @@ describe('TunnelController', function (): void { Carbon::setTestNow(); } }); + + it('tracks unconverted tunnel attempts from step 1 and marks them converted upon step 3 confirmation', function (): void { + /** @var \Tests\TestCase $this */ + $now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); + + try { + // GIVEN + Mail::fake(); + Notification::fake(); + + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + $hashcode = new CrmHashcode(Uuid::uuid4()); + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'email' => new Email('e2e-attempt@example.com'), + 'hashcode' => $hashcode, + ]); + + $crmCustomer = new CrmCustomer( + hashcode: $hashcode->value, + email: 'e2e-attempt@example.com', + password: 'hashed-password', + firstname: 'Jean', + lastname: 'Dupont', + birthDate: null, + phone: null, + address: null, + address2: null, + city: null, + postcode: null, + country: Country::france, + optIn: false, + status: true, + lastConnection: null, + ); + + $crmService = $this->mock(CrmService::class); + $crmService->shouldReceive('getCustomerFromHashCode')->andReturn($crmCustomer); + + $employee = new Employee(); + $employee->matricule = new Matricule('7654324'); + $employee->code = new Code('ABCDEFK'); + $employee->nom = 'Dupont'; + $employee->prenom = 'Jean'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITEA'); + $employee->service = new ShopperServiceCode('101'); + $employee->start_date = Date::now()->subMonth(); + $employee->end_date = null; + $employee->customer()->associate($customer); + $employee->saveOrFail(); + + $shop = new Shop(); + $shop->name = 'Boutique Sablé Attempt'; + $shop->address = '10 rue Test'; + $shop->postcode = '72300'; + $shop->city = 'Sablé'; + $shop->default = true; + $shop->saveOrFail(); + + $range = new Range(); + $range->name = 'Gamme Attempt'; + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $product = new Product(); + $product->name = 'Poulet Attempt'; + $product->brand = ProductBrand::loue; + $product->description = 'Description Attempt'; + $product->short_description = 'Court Attempt'; + $product->price = Money::EUR(1500); + $product->invoicing_unit = InvoicingUnit::PCE; + $product->tax_rate = TaxRate::TVA_5_5; + $product->stock = 50; + $product->weight = 1000; + $product->sell_unit = SellUnit::PCE; + $product->order_unit = OrderUnit::PCE; + $product->range_id = $range->id; + $product->status = true; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt large'; + $product->picture_large_title = 'title large'; + $product->saveOrFail(); + + $inco = new ProductInco(); + $inco->product_id = $product->id; + $inco->no_art = 889904; + $inco->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + /** @var BasketService $basketService */ + $basketService = $this->app->make(BasketService::class); + $basketService->empty(); + $basketService->add($product->getId(), 2); + + // WHEN: Step 1 submitted twice before completing checkout + $step1First = $this->post('/commande/panier', []); + $step1Second = $this->post('/commande/panier', []); + + // THEN: single unconverted attempt recorded + $step1First->assertRedirectToRoute('fo.sales.pick-time-slot'); + $step1Second->assertRedirectToRoute('fo.sales.pick-time-slot'); + expect(OrderTunnelAttempt::query()->whereNull('converted_at')->count())->toBe(1); + + // WHEN: Step 2 & Step 3 submitted + $this->post('/commande/creneaux', [ + 'timeslot' => '2026-11-20', + ])->assertRedirectToRoute('fo.sales.confirmation'); + + $step3Response = $this->post('/commande/confirmation', [ + 'ok_cgv' => '1', + ]); + + // THEN: same attempt is now marked converted and linked to the validated order + $order = Order::query()->where('employee_matricule', '7654324')->firstOrFail(); + $step3Response->assertRedirectToRoute('fo.sales.confirmation.show-confirmed', [ + 'order' => (string) $order->reference, + ]); + $attempt = OrderTunnelAttempt::query()->firstOrFail(); + expect(OrderTunnelAttempt::query()->count())->toBe(1) + ->and($attempt->order_id)->toBe($order->id) + ->and($attempt->converted_at)->not->toBeNull(); + } finally { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); + } + }); + + it('keeps tunnel attempt unconverted when regate export fails on step 3', function (): void { + /** @var \Tests\TestCase $this */ + $now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); + + try { + // GIVEN + Mail::fake(); + Notification::fake(); + + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + $hashcode = new CrmHashcode(Uuid::uuid4()); + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'email' => new Email('e2e-attempt-ko@example.com'), + 'hashcode' => $hashcode, + ]); + + $crmCustomer = new CrmCustomer( + hashcode: $hashcode->value, + email: 'e2e-attempt-ko@example.com', + password: 'hashed-password', + firstname: 'Jean', + lastname: 'Dupont', + birthDate: null, + phone: null, + address: null, + address2: null, + city: null, + postcode: null, + country: Country::france, + optIn: false, + status: true, + lastConnection: null, + ); + + $crmService = $this->mock(CrmService::class); + $crmService->shouldReceive('getCustomerFromHashCode')->andReturn($crmCustomer); + + $regateService = $this->mock(RegateService::class); + $regateService->shouldReceive('processOrder') + ->once() + ->andThrow(new RegateExportFailedException('SMTP unreachable')); + + $employee = new Employee(); + $employee->matricule = new Matricule('7654325'); + $employee->code = new Code('ABCDEFM'); + $employee->nom = 'Dupont'; + $employee->prenom = 'Jean'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITEA'); + $employee->service = new ShopperServiceCode('101'); + $employee->start_date = Date::now()->subMonth(); + $employee->end_date = null; + $employee->customer()->associate($customer); + $employee->saveOrFail(); + + $shop = new Shop(); + $shop->name = 'Boutique Sablé Attempt KO'; + $shop->address = '10 rue Test'; + $shop->postcode = '72300'; + $shop->city = 'Sablé'; + $shop->default = true; + $shop->saveOrFail(); + + $range = new Range(); + $range->name = 'Gamme Attempt KO'; + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $product = new Product(); + $product->name = 'Poulet Attempt KO'; + $product->brand = ProductBrand::loue; + $product->description = 'Description Attempt KO'; + $product->short_description = 'Court Attempt KO'; + $product->price = Money::EUR(1500); + $product->invoicing_unit = InvoicingUnit::PCE; + $product->tax_rate = TaxRate::TVA_5_5; + $product->stock = 50; + $product->weight = 1000; + $product->sell_unit = SellUnit::PCE; + $product->order_unit = OrderUnit::PCE; + $product->range_id = $range->id; + $product->status = true; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt large'; + $product->picture_large_title = 'title large'; + $product->saveOrFail(); + + $inco = new ProductInco(); + $inco->product_id = $product->id; + $inco->no_art = 889905; + $inco->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + /** @var BasketService $basketService */ + $basketService = $this->app->make(BasketService::class); + $basketService->empty(); + $basketService->add($product->getId(), 2); + + // WHEN: Step 1 -> Step 2 -> failing Step 3 + $this->post('/commande/panier', []) + ->assertRedirectToRoute('fo.sales.pick-time-slot'); + $this->post('/commande/creneaux', [ + 'timeslot' => '2026-11-20', + ])->assertRedirectToRoute('fo.sales.confirmation'); + $this->post('/commande/confirmation', ['ok_cgv' => '1']) + ->assertRedirectToRoute('fo.sales.confirmation'); + + // THEN: order is FAILED, basket remains intact, and attempt stays unconverted + $order = Order::query()->where('employee_matricule', '7654325')->firstOrFail(); + $attempt = OrderTunnelAttempt::query()->firstOrFail(); + expect($order->status)->toBe(OrderStatus::FAILED) + ->and($attempt->order_id)->toBeNull() + ->and($attempt->converted_at)->toBeNull() + ->and($basketService->hasItems())->toBeTrue(); + } finally { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); + } + }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php index 13370599..18e743e4 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php @@ -44,6 +44,7 @@ use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; use Infrastructure\Adapters\Repositories\EloquentProductRepository; use Infrastructure\Adapters\Repositories\EloquentShopperRepository; use Infrastructure\Adapters\Repositories\EloquentShopRepository; +use Infrastructure\Adapters\Services\DatabaseTunnelAttemptTrackerService; use Infrastructure\Adapters\Services\EloquentEmployeeStatisticsService; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; use Money\Currency; @@ -135,6 +136,7 @@ describe('ApplyPickTimeSlot action', function (): void { new OrderService($orderRepo), new EloquentEmployeeStatisticsService(), $regateService, + new DatabaseTunnelAttemptTrackerService($session, 'order_tunnel_attempt_id'), ); return [$customer, $shop, $builderManager, $tunnelService]; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php index 90a716bf..c474fbb8 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php @@ -6,6 +6,7 @@ namespace Tests\Integration\WithApp\App\Cqs\Actions\Orders; use App\Cqs\Actions\Orders\InitializeOrderTunnel; use App\Cqs\Actions\Orders\InitializeOrderTunnelInput; +use App\Models\Customer; use Domain\Builders\OrderBuilderWithBasket; use Domain\Enums\ProductBrand; use Domain\Enums\TaxRate; @@ -13,9 +14,9 @@ use Domain\Enums\Units\OrderUnit; use Domain\Models\Entities\Basket; use Domain\Models\ValueObjects\BasketProduct; use Domain\Models\ValueObjects\DiscountRate; +use Domain\Models\ValueObjects\Email; use Domain\Models\ValueObjects\Entities\BasketId; use Domain\Models\ValueObjects\Entities\ProductId; -use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Models\ValueObjects\IncoId; use Domain\Policies\CustomerOrderLimitPolicy; use Domain\Ports\Services\RegateService; @@ -30,6 +31,7 @@ use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; use Infrastructure\Adapters\Repositories\EloquentProductRepository; use Infrastructure\Adapters\Repositories\EloquentShopperRepository; use Infrastructure\Adapters\Repositories\EloquentShopRepository; +use Infrastructure\Adapters\Services\DatabaseTunnelAttemptTrackerService; use Infrastructure\Adapters\Services\EloquentEmployeeStatisticsService; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; use Money\Currency; @@ -62,6 +64,7 @@ describe('InitializeOrderTunnel action', function (): void { new OrderService($orderRepo), new EloquentEmployeeStatisticsService(), $regateService, + new DatabaseTunnelAttemptTrackerService($session, 'order_tunnel_attempt_id'), ); $productId = new ProductId(Uuid::uuid7()); @@ -86,7 +89,13 @@ describe('InitializeOrderTunnel action', function (): void { options: [], ), ]); - $shopperId = new ShopperId(Uuid::uuid7()); + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'email' => new Email('init-tunnel@example.com'), + 'hashcode' => Uuid::uuid4()->toString(), + ]); + $shopperId = $customer->getId(); $action = new InitializeOrderTunnel($tunnelService); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php index eab56504..d1107e01 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -76,6 +76,7 @@ use Infrastructure\Adapters\Repositories\SessionBasketRepository; use Infrastructure\Adapters\Serializers\BasketSerializer; use Infrastructure\Adapters\Services\AppSessionService; use Infrastructure\Adapters\Services\CsvGeneratorImpl; +use Infrastructure\Adapters\Services\DatabaseTunnelAttemptTrackerService; use Infrastructure\Adapters\Services\EloquentEmployeeStatisticsService; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; use Money\Currency; @@ -236,6 +237,7 @@ describe('Order placement two-step CQS actions', function (): void { new OrderService($orderRepo), new EloquentEmployeeStatisticsService(), $regateService ?? new MailRegateService(new CsvGeneratorImpl(), $mailer), + new DatabaseTunnelAttemptTrackerService($session, 'order_tunnel_attempt_id'), ); $executor = new ActionExecutorService( diff --git a/tests/Integration/WithApp/App/Services/StatsServiceTest.php b/tests/Integration/WithApp/App/Services/StatsServiceTest.php index d7b23aa7..08bf3ab5 100644 --- a/tests/Integration/WithApp/App/Services/StatsServiceTest.php +++ b/tests/Integration/WithApp/App/Services/StatsServiceTest.php @@ -8,6 +8,7 @@ use App\Models\Customer; use App\Models\Employee; use App\Models\Order; use App\Models\OrderLine; +use App\Models\OrderTunnelAttempt; use App\Services\StatsService; use Carbon\Carbon; use Carbon\CarbonImmutable; @@ -218,4 +219,67 @@ describe('StatsService', function (): void { ->and($shopStats[StatsShopType::averageBasketHt->value]['current'])->toBe(20.0) ->and($shopStats[StatsShopType::averageProductCountPerOrder->value]['current'])->toBe(2.0); }); + + it('combines legacy WAITING orders and unconverted tunnel attempts in waiting stats', function () use ($createOrder): void { + // GIVEN + $service = new StatsService(new Currency('EUR')); + $now = CarbonImmutable::now(); + $customer = Customer::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'hashcode' => Uuid::uuid4()->toString(), + 'email' => new Email('attempts-stats@example.com'), + ]); + + // 1 legacy WAITING order + $createOrder(OrderStatus::WAITING, '1000401', $now->subDays(2)); + // 1 VALIDATED + 1 CANCELED business orders + $validatedOrder = $createOrder(OrderStatus::VALIDATED, '1000401', $now->subDays(2)); + $createOrder(OrderStatus::CANCELED, '1000401', $now->subDays(2)); + // Technical PENDING and FAILED orders must never pollute nbWaitingCmd or canceledRate + $createOrder(OrderStatus::PENDING, '1000401', $now->subDays(2)); + $createOrder(OrderStatus::FAILED, '1000401', $now->subDays(2)); + + // 2 unconverted attempts in period + OrderTunnelAttempt::query()->forceCreate([ + 'customer_id' => $customer->id, + 'order_id' => null, + 'converted_at' => null, + 'created_at' => $now->subDay()->utc(), + 'updated_at' => $now->subDay()->utc(), + ]); + OrderTunnelAttempt::query()->forceCreate([ + 'customer_id' => $customer->id, + 'order_id' => null, + 'converted_at' => null, + 'created_at' => $now->subHours(2)->utc(), + 'updated_at' => $now->subHours(2)->utc(), + ]); + + // 1 converted attempt (must not be counted as waiting) + OrderTunnelAttempt::query()->forceCreate([ + 'customer_id' => $customer->id, + 'order_id' => $validatedOrder->id, + 'converted_at' => $now->subDays(2)->utc(), + 'created_at' => $now->subDays(2)->utc(), + 'updated_at' => $now->subDays(2)->utc(), + ]); + + // 1 unconverted attempt outside the queried period (must not be counted) + OrderTunnelAttempt::query()->forceCreate([ + 'customer_id' => $customer->id, + 'order_id' => null, + 'converted_at' => null, + 'created_at' => $now->subDays(12)->utc(), + 'updated_at' => $now->subDays(12)->utc(), + ]); + + // WHEN + $shopStats = $service->getStats(StatsShopType::cases(), $now->subDays(5), $now); + + // THEN: waiting = 1 legacy + 2 unconverted = 3 ; canceled = 1 ; validated = 1 => canceledRate = (4 / 5) * 100 = 80.0 + expect($shopStats[StatsShopType::nbWaitingCmd->value]['current'])->toBe(3) + ->and($shopStats[StatsShopType::nbValidateCmd->value]['current'])->toBe(1) + ->and($shopStats[StatsShopType::nbCanceledCmd->value]['current'])->toBe(1) + ->and($shopStats[StatsShopType::canceledRate->value]['current'])->toBe(80.0); + }); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/DatabaseTunnelAttemptTrackerServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/DatabaseTunnelAttemptTrackerServiceTest.php new file mode 100644 index 00000000..0d857e0f --- /dev/null +++ b/tests/Integration/WithApp/Infra/Adapters/Services/DatabaseTunnelAttemptTrackerServiceTest.php @@ -0,0 +1,147 @@ +forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'hashcode' => Uuid::uuid4()->toString(), + 'email' => new Email('attempt-reuse@example.com'), + ]); + $shopperId = new ShopperId(Uuid::fromString($customer->id)); + + // WHEN + $tracker->recordEntry($shopperId); + $firstAttemptId = $session->get('order_tunnel_attempt_id'); + $tracker->recordEntry($shopperId); + $secondAttemptId = $session->get('order_tunnel_attempt_id'); + + // THEN + expect($firstAttemptId)->toBeString() + ->and($secondAttemptId)->toBe($firstAttemptId) + ->and(OrderTunnelAttempt::query()->count())->toBe(1); + + $attempt = OrderTunnelAttempt::query()->firstOrFail(); + expect($attempt->customer_id)->toBe($customer->id) + ->and($attempt->order_id)->toBeNull() + ->and($attempt->converted_at)->toBeNull(); + }); + + it('marks attempt converted on order confirmation and clears the session key', function (): void { + // GIVEN + $now = CarbonImmutable::parse('2026-11-16 14:30:00', 'UTC'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); + + /** @var \Illuminate\Contracts\Session\Session $session */ + $session = Session::driver(); + $tracker = new DatabaseTunnelAttemptTrackerService($session, 'order_tunnel_attempt_id'); + + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'hashcode' => Uuid::uuid4()->toString(), + 'email' => new Email('attempt-convert@example.com'), + ]); + $shopperId = new ShopperId(Uuid::fromString($customer->id)); + + $orderId = Uuid::uuid7()->toString(); + Order::query()->forceCreate([ + 'id' => $orderId, + 'reference' => new OrderReference(Uuid::uuid7()), + 'status' => OrderStatus::VALIDATED->value, + 'total' => Money::EUR(1500), + 'employee' => new OrderEmployee( + new Matricule('1000401'), + 'Jean', + 'Dupont', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), + 'delivery_address' => new DeliveryAddress('Boutique', '1 rue Test', '72300', 'Sablé'), + ]); + + $tracker->recordEntry($shopperId); + + // WHEN + $tracker->markConverted(new OrderId(Uuid::fromString($orderId))); + + // THEN + expect($session->has('order_tunnel_attempt_id'))->toBeFalse(); + + $attempt = OrderTunnelAttempt::query()->firstOrFail(); + expect($attempt->order_id)->toBe($orderId) + ->and($attempt->converted_at)->not->toBeNull(); + + // Recording a new entry in the same session now creates a distinct attempt + $tracker->recordEntry($shopperId); + expect(OrderTunnelAttempt::query()->count())->toBe(2); + }); + + it('clears only the session key when BasketRemoved listener fires', function (): void { + // GIVEN + /** @var \Illuminate\Contracts\Session\Session $session */ + $session = Session::driver(); + $tracker = new DatabaseTunnelAttemptTrackerService($session, 'order_tunnel_attempt_id'); + $listener = new ResetTunnelAttemptOnBasketRemoved($tracker); + + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'hashcode' => Uuid::uuid4()->toString(), + 'email' => new Email('attempt-clear@example.com'), + ]); + $tracker->recordEntry(new ShopperId(Uuid::fromString($customer->id))); + + // WHEN + $listener->handle(new BasketRemoved(new BasketId(Uuid::uuid7()))); + + // THEN + expect($session->has('order_tunnel_attempt_id'))->toBeFalse() + ->and(OrderTunnelAttempt::query()->whereNull('converted_at')->count())->toBe(1); + }); +}); diff --git a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php index 8e0174ab..360c6b3d 100644 --- a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php +++ b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php @@ -48,6 +48,7 @@ use Domain\Ports\Repositories\ShopRepository; use Domain\Ports\Services\EmployeeStatisticsService; use Domain\Ports\Services\OrderBuilderSessionManager; use Domain\Ports\Services\RegateService; +use Domain\Ports\Services\TunnelAttemptTrackerService; use Domain\Services\OrderService; use Domain\Services\OrderTunnelService; use Domain\Services\PickupSchedulingService; @@ -118,6 +119,7 @@ function createOrderTunnelService( ?OrderRepository $orderRepository = null, ?DomainEventDispatcher $eventDispatcher = null, ?RegateService $regateService = null, + ?TunnelAttemptTrackerService $tunnelAttemptTracker = null, ): OrderTunnelService { if ($productRepository === null) { $productRepository = \Mockery::mock(ProductRepository::class); @@ -165,6 +167,13 @@ function createOrderTunnelService( $regateService->shouldReceive('processOrder')->byDefault(); } + if ($tunnelAttemptTracker === null) { + $tunnelAttemptTracker = \Mockery::mock(TunnelAttemptTrackerService::class); + $tunnelAttemptTracker->shouldReceive('recordEntry')->byDefault(); + $tunnelAttemptTracker->shouldReceive('markConverted')->byDefault(); + $tunnelAttemptTracker->shouldReceive('clearActiveSession')->byDefault(); + } + $orderLimitPolicy = new CustomerOrderLimitPolicy(500000, 500000, new Currency('EUR')); return new OrderTunnelService( @@ -180,6 +189,7 @@ function createOrderTunnelService( $orderService, $employeeStatisticsService, $regateService, + $tunnelAttemptTracker, ); } @@ -1036,4 +1046,82 @@ describe('OrderTunnelService', function (): void { expect($confirmed->status)->toBe(OrderStatus::VALIDATED) ->and($orderToKo->status)->toBe(OrderStatus::FAILED); }); + + it('records a tunnel attempt when initializing from basket', function (): void { + // GIVEN + $basket = createTestBasket(1); + $customerId = new ShopperId(Uuid::uuid7()); + $recorded = false; + + $orderBuilderSessionManager = \Mockery::mock(OrderBuilderSessionManager::class); + $orderBuilderSessionManager->shouldReceive('save')->once(); + + $tracker = \Mockery::mock(TunnelAttemptTrackerService::class); + $tracker->shouldReceive('recordEntry') + ->once() + ->with($customerId) + ->andReturnUsing(function () use (&$recorded): void { + $recorded = true; + }); + + $service = createOrderTunnelService( + orderBuilderSessionManager: $orderBuilderSessionManager, + tunnelAttemptTracker: $tracker, + ); + + // WHEN + $service->initializeFromBasket($basket, $customerId); + + // THEN + expect($recorded)->toBeTrue(); + }); + + it('marks the tunnel attempt converted when confirming a placed order', function (): void { + // GIVEN + $shopId = new ShopId(Uuid::uuid7()); + $shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris'); + $shopper = new Shopper( + id: new ShopperId(Uuid::uuid7()), + email: new Email('convert@test.com'), + matricule: new Matricule('1234567'), + nom: 'Doe', + prenom: 'John', + startDate: CarbonImmutable::now()->subYear(), + endDate: null, + etablissement: new ShopperEstablishmentCode('ETAB01'), + site: new ShopperSiteCode('SITEA'), + service: new ShopperServiceCode('101') + ); + $basket = createTestBasket(1); + $order = Order::pendingFromBasket( + new OrderId(Uuid::uuid7()), + new OrderReference(Uuid::uuid7()), + $basket, + new PickupTimeSlot(CarbonImmutable::now()->next('Friday'), new \DateInterval('PT1H')), + $shopper, + $shop + ); + + $orderRepo = \Mockery::mock(OrderRepository::class); + $orderRepo->shouldReceive('findForUpdate')->with($order->id())->andReturn($order); + $orderRepo->shouldReceive('persist')->with($order)->once(); + + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); + $eventDispatcher->shouldReceive('dispatch')->once()->with(\Mockery::type(AnOrderHasBeenPlaced::class)); + + $tracker = \Mockery::mock(TunnelAttemptTrackerService::class); + $tracker->shouldReceive('markConverted')->once()->with($order->id()); + + $service = createOrderTunnelService( + orderRepository: $orderRepo, + eventDispatcher: $eventDispatcher, + tunnelAttemptTracker: $tracker, + ); + + // WHEN + $confirmed = $service->confirmPlacedOrder($order->id()); + + // THEN + expect($confirmed->status)->toBe(OrderStatus::VALIDATED); + }); }); From 758605be099b960659ef1144acf2e666c7ee6884 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 20:31:25 +0100 Subject: [PATCH 167/183] refactor(domain,orders): convert OrderStatus enum to lowercase string --- REGLES METIERS.md | 10 +-- .../Requests/Bo/Orders/IndexOrdersRequest.php | 6 -- ...200000_convert_orders_status_to_string.php | 63 ++++++++++++++++ domain/Enums/OrderStatus.php | 24 +++--- .../Controllers/Bo/OrdersControllerTest.php | 58 +++++++++++++++ .../Bo/Orders/IndexOrdersRequestTest.php | 19 ++++- tests/Unit/Domain/Enums/OrderStatusTest.php | 74 +++++++++++++++++++ 7 files changed, 230 insertions(+), 24 deletions(-) create mode 100644 database/migrations/2026_11_16_200000_convert_orders_status_to_string.php create mode 100644 tests/Unit/Domain/Enums/OrderStatusTest.php diff --git a/REGLES METIERS.md b/REGLES METIERS.md index 757d3f92..e268058c 100644 --- a/REGLES METIERS.md +++ b/REGLES METIERS.md @@ -59,11 +59,11 @@ Elle est vérifiée côté Domaine par `Shopper::isActive()` et côté Eloquent ## 5. Cycle de Vie, Tunnel de Commande & Annulation (Back-Office) ### Statuts des commandes (`Domain\Enums\OrderStatus`) -- **`WAITING` (`1`)** : reliquat historique des commandes créées avant la refonte (paniers non transformés). Conservé en lecture dans les statistiques historiques. -- **`PENDING` (`2`)** : commande technique créée lors de `PlacePendingOrder` avant l'export Régate. Elle est comptabilisée dans le plafond hebdomadaire de 200 € (`EloquentEmployeeStatisticsService`), masquée en Front-Office (`GetFoCustomerPaginatedOrdersQuery`, `Frontend\OrderPolicy::viewOwn`) et masquée par défaut en Back-Office (affichable à la demande via le filtre statut). -- **`VALIDATED` (`3`)** : commande confirmée après succès de l'export Régate (`ConfirmPlacedOrder`). -- **`FAILED` (`4`)** : statut technique en cas d'échec de l'export Régate (`FailPendingOrder`) ou d'expiration d'une commande `PENDING` bloquée au-delà de 10 minutes (`FailStalePendingOrders` / `FailStalePendingOrdersJob`, planifié toutes les 5 minutes). Masqué en Front-Office, affichable à la demande en Back-Office, exclu du plafond hebdomadaire et des statistiques. -- **`CANCELED` (`7`)** : annulation métier (Back-Office ou Régate). +- **`WAITING` (`'waiting'`)** : reliquat historique des commandes créées avant la refonte (paniers non transformés). Conservé en lecture dans les statistiques historiques. +- **`PENDING` (`'pending'`)** : commande technique créée lors de `PlacePendingOrder` avant l'export Régate. Elle est comptabilisée dans le plafond hebdomadaire de 200 € (`EloquentEmployeeStatisticsService`), masquée en Front-Office (`GetFoCustomerPaginatedOrdersQuery`, `Frontend\OrderPolicy::viewOwn`) et masquée par défaut en Back-Office (affichable à la demande via le filtre statut). +- **`VALIDATED` (`'validated'`)** : commande confirmée après succès de l'export Régate (`ConfirmPlacedOrder`). +- **`FAILED` (`'failed'`)** : statut technique en cas d'échec de l'export Régate (`FailPendingOrder`) ou d'expiration d'une commande `PENDING` bloquée au-delà de 10 minutes (`FailStalePendingOrders` / `FailStalePendingOrdersJob`, planifié toutes les 5 minutes). Masqué en Front-Office, affichable à la demande en Back-Office, exclu du plafond hebdomadaire et des statistiques. +- **`CANCELED` (`'canceled'`)** : annulation métier (Back-Office ou Régate). ### Concurrence du tunnel & suivi des paniers non transformés - Lors de la soumission finale (`TunnelController::confirmationSubmit()`), un verrou distribué non bloquant (`order:checkout:shopper:{id}`, `waitSeconds: 0`, TTL `60s`) protège la séquence synchrone `PlacePendingOrder` (elle-même protégée par `#[Locked]` sur `order:finalize:shopper:{id}`) → `ExportOrderToRegate` → `ConfirmPlacedOrder` / `FailPendingOrder`. diff --git a/app/Http/Requests/Bo/Orders/IndexOrdersRequest.php b/app/Http/Requests/Bo/Orders/IndexOrdersRequest.php index 36ced615..07d956e1 100644 --- a/app/Http/Requests/Bo/Orders/IndexOrdersRequest.php +++ b/app/Http/Requests/Bo/Orders/IndexOrdersRequest.php @@ -80,12 +80,6 @@ class IndexOrdersRequest extends FormRequest return null; } - $value = $this->input('status'); - - if (is_numeric($value)) { - return OrderStatus::tryFrom((int) $value); - } - return $this->enum('status', OrderStatus::class); } diff --git a/database/migrations/2026_11_16_200000_convert_orders_status_to_string.php b/database/migrations/2026_11_16_200000_convert_orders_status_to_string.php new file mode 100644 index 00000000..7410c0a2 --- /dev/null +++ b/database/migrations/2026_11_16_200000_convert_orders_status_to_string.php @@ -0,0 +1,63 @@ +string('status', 32)->change(); + }); + + foreach (self::UP_STATUS_MAP as [$legacyStatus, $stringStatus]) { + DB::table('orders') + ->where('status', $legacyStatus) + ->update(['status' => $stringStatus]); + } + + Schema::table('orders', function (Blueprint $table): void { + $table->dropIndex('orders_status_id_foreign'); + $table->index('status'); + }); + } + + public function down(): void + { + Schema::table('orders', function (Blueprint $table): void { + $table->dropIndex('orders_status_index'); + $table->index('status', 'orders_status_id_foreign'); + }); + + foreach (self::DOWN_STATUS_MAP as [$stringStatus, $legacyStatus]) { + DB::table('orders') + ->where('status', $stringStatus) + ->update(['status' => $legacyStatus]); + } + + Schema::table('orders', function (Blueprint $table): void { + $table->unsignedBigInteger('status')->change(); + }); + } +}; diff --git a/domain/Enums/OrderStatus.php b/domain/Enums/OrderStatus.php index ffcf24ae..1801d2f9 100644 --- a/domain/Enums/OrderStatus.php +++ b/domain/Enums/OrderStatus.php @@ -7,16 +7,16 @@ namespace Domain\Enums; use Shared\Enums\BaseEnum; use Shared\Enums\HasBaseEnum; -enum OrderStatus: int implements HasBaseEnum +enum OrderStatus: string implements HasBaseEnum { - /** @use \Shared\Enums\BaseEnum */ + /** @use \Shared\Enums\BaseEnum */ use BaseEnum; - case WAITING = 1; - case PENDING = 2; - case VALIDATED = 3; - case FAILED = 4; - case CANCELED = 7; + case WAITING = 'waiting'; + case PENDING = 'pending'; + case VALIDATED = 'validated'; + case FAILED = 'failed'; + case CANCELED = 'canceled'; /** * Optional labels definition @@ -24,10 +24,10 @@ enum OrderStatus: int implements HasBaseEnum * @phpstan-ignore-next-line classConstant.unused (Base enum usage) */ private const LABELS = [ - self::WAITING->name => 'En attente', - self::PENDING->name => 'En cours', - self::VALIDATED->name => 'Validée', - self::FAILED->name => 'Échouée', - self::CANCELED->name => 'Annulée', + self::WAITING->name => 'En attente', + self::PENDING->name => 'En cours', + self::VALIDATED->name => 'Validée', + self::FAILED->name => 'Échouée', + self::CANCELED->name => 'Annulée', ]; } diff --git a/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php index efba6867..8195317e 100644 --- a/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php @@ -385,4 +385,62 @@ describe('Bo\OrdersController', function (): void { // THEN $response->assertStatus(403); }); + + it('filters orders by string status query parameter and marks selected option in view', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $shop = Shop::factory()->create(); + $validated = Order::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(Uuid::uuid7()), + 'status' => OrderStatus::VALIDATED->value, + 'total' => new Money(2500, new Currency('EUR')), + 'employee' => new OrderEmployee( + new Matricule('1000106'), + 'Alice', + 'Martin', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), + 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), + 'pickup_day' => Date::now()->toDateString(), + ]); + Order::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(Uuid::uuid7()), + 'status' => OrderStatus::FAILED->value, + 'total' => new Money(1500, new Currency('EUR')), + 'employee' => new OrderEmployee( + new Matricule('1000107'), + 'Bob', + 'Durand', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), + 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), + 'pickup_day' => Date::now()->toDateString(), + ]); + + // WHEN + $response = $this->get('/bo/orders?status=validated'); + $legacyResponse = $this->get('/bo/orders?status=1'); + + // THEN + $response->assertOk() + ->assertSessionHas('orders.filter.status', OrderStatus::VALIDATED) + ->assertSee('value="validated"', false) + ->assertSee('value="failed"', false) + ->assertSee('value="pending"', false); + + /** @var \Illuminate\Pagination\LengthAwarePaginator $orders */ + $orders = $response->viewData('orders'); + expect($orders->total())->toBe(1) + ->and($orders->first()?->id)->toBe($validated->id); + + $legacyResponse->assertSessionHasErrors('status'); + }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php index 804d1d20..f3137956 100644 --- a/tests/Feature/App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php @@ -64,6 +64,9 @@ describe('IndexOrdersRequest', function (): void { 'order_date_start' => '2026-06-15', 'order_date_end' => '2026-06-10', ], $rules); + $legacyNumeric = Validator::make([ + 'status' => '1', + ], $rules); $valid = Validator::make([ 'status' => OrderStatus::WAITING->value, 'order_date_start' => '2026-06-10', @@ -73,9 +76,23 @@ describe('IndexOrdersRequest', function (): void { // THEN expect($invalid->errors()->has('status'))->toBeTrue() ->and($invalid->errors()->has('order_date_end'))->toBeTrue() + ->and($legacyNumeric->errors()->has('status'))->toBeTrue() ->and($valid->passes())->toBeTrue(); }); + it('returns null from getStatus for legacy numeric status values', function (): void { + // GIVEN + $authService = \Mockery::mock(AppAdminAuthService::class); + $request = new IndexOrdersRequest($authService); + $request->initialize(query: ['status' => '1']); + + // WHEN + $status = $request->getStatus(); + + // THEN + expect($status)->toBeNull(); + }); + it('resolves status and filter dates', function (): void { // GIVEN $authService = \Mockery::mock(AppAdminAuthService::class); @@ -114,7 +131,7 @@ describe('IndexOrdersRequest', function (): void { $request->initialize(query: [ 'page' => 3, 'search' => 'TEST-REF', - 'status' => (string) OrderStatus::VALIDATED->value, + 'status' => OrderStatus::VALIDATED->value, ]); // WHEN diff --git a/tests/Unit/Domain/Enums/OrderStatusTest.php b/tests/Unit/Domain/Enums/OrderStatusTest.php new file mode 100644 index 00000000..31af37a1 --- /dev/null +++ b/tests/Unit/Domain/Enums/OrderStatusTest.php @@ -0,0 +1,74 @@ +value, + $pending->value, + $validated->value, + $failed->value, + $canceled->value, + ]; + + // THEN + expect($values)->toBe([ + 'waiting', + 'pending', + 'validated', + 'failed', + 'canceled', + ]); + }); + + it('returns French labels via label() and toLabels()', function (): void { + // GIVEN + $expectedLabels = [ + 'WAITING' => 'En attente', + 'PENDING' => 'En cours', + 'VALIDATED' => 'Validée', + 'FAILED' => 'Échouée', + 'CANCELED' => 'Annulée', + ]; + + // WHEN + $allLabels = OrderStatus::toLabels(); + $validatedLabel = OrderStatus::VALIDATED->label(); + $failedLabel = OrderStatus::FAILED->label(); + + // THEN + expect($allLabels)->toBe($expectedLabels) + ->and($validatedLabel)->toBe('Validée') + ->and($failedLabel)->toBe('Échouée'); + }); + + it('resolves valid string values via tryFrom and rejects legacy numeric strings', function (): void { + // GIVEN + $resolve = static fn (string $value): ?OrderStatus => OrderStatus::tryFrom($value); + + // WHEN + $resolvedValid = $resolve('validated'); + $resolvedLegacy1 = $resolve('1'); + $resolvedLegacy3 = $resolve('3'); + $resolvedUnknown = $resolve('VALIDATED'); + + // THEN + expect($resolvedValid)->toBe(OrderStatus::VALIDATED) + ->and($resolvedLegacy1)->toBeNull() + ->and($resolvedLegacy3)->toBeNull() + ->and($resolvedUnknown)->toBeNull(); + }); +}); From 7a701328f9b0e3f9e61c681237e0901d4535b3af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 20:39:50 +0100 Subject: [PATCH 168/183] test(orders): verify selected HTML option, failed status filter, and all OrderStatus cases --- .../Controllers/Bo/OrdersControllerTest.php | 31 ++++++++++++++---- tests/Unit/Domain/Enums/OrderStatusTest.php | 32 ++++++++++++++----- 2 files changed, 48 insertions(+), 15 deletions(-) diff --git a/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php index 8195317e..ae7a39b8 100644 --- a/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php @@ -31,6 +31,8 @@ use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; +use function Pest\Laravel\get; + describe('Bo\OrdersController', function (): void { beforeEach(function (): void { /** @var \Tests\TestCase $this */ @@ -387,7 +389,6 @@ describe('Bo\OrdersController', function (): void { }); it('filters orders by string status query parameter and marks selected option in view', function (): void { - /** @var \Tests\TestCase $this */ // GIVEN $shop = Shop::factory()->create(); $validated = Order::query()->forceCreate([ @@ -407,7 +408,7 @@ describe('Bo\OrdersController', function (): void { 'delivery_address' => new DeliveryAddress('Shop Name', 'Address', '75000', 'Paris'), 'pickup_day' => Date::now()->toDateString(), ]); - Order::query()->forceCreate([ + $failed = Order::query()->forceCreate([ 'id' => Uuid::uuid7()->toString(), 'shop_id' => $shop->id, 'reference' => new OrderReference(Uuid::uuid7()), @@ -426,21 +427,37 @@ describe('Bo\OrdersController', function (): void { ]); // WHEN - $response = $this->get('/bo/orders?status=validated'); - $legacyResponse = $this->get('/bo/orders?status=1'); + $response = get('/bo/orders?status=validated'); // THEN $response->assertOk() ->assertSessionHas('orders.filter.status', OrderStatus::VALIDATED) - ->assertSee('value="validated"', false) - ->assertSee('value="failed"', false) - ->assertSee('value="pending"', false); + ->assertSee('', false) + ->assertSee('', false) + ->assertSee('', false); /** @var \Illuminate\Pagination\LengthAwarePaginator $orders */ $orders = $response->viewData('orders'); expect($orders->total())->toBe(1) ->and($orders->first()?->id)->toBe($validated->id); + // WHEN + $failedResponse = get('/bo/orders?status=failed'); + + // THEN + $failedResponse->assertOk() + ->assertSessionHas('orders.filter.status', OrderStatus::FAILED) + ->assertSee('', false); + + /** @var \Illuminate\Pagination\LengthAwarePaginator $failedOrders */ + $failedOrders = $failedResponse->viewData('orders'); + expect($failedOrders->total())->toBe(1) + ->and($failedOrders->first()?->id)->toBe($failed->id); + + // WHEN + $legacyResponse = get('/bo/orders?status=1'); + + // THEN $legacyResponse->assertSessionHasErrors('status'); }); }); diff --git a/tests/Unit/Domain/Enums/OrderStatusTest.php b/tests/Unit/Domain/Enums/OrderStatusTest.php index 31af37a1..5f2a9561 100644 --- a/tests/Unit/Domain/Enums/OrderStatusTest.php +++ b/tests/Unit/Domain/Enums/OrderStatusTest.php @@ -60,15 +60,31 @@ describe('OrderStatus', function (): void { $resolve = static fn (string $value): ?OrderStatus => OrderStatus::tryFrom($value); // WHEN - $resolvedValid = $resolve('validated'); - $resolvedLegacy1 = $resolve('1'); - $resolvedLegacy3 = $resolve('3'); - $resolvedUnknown = $resolve('VALIDATED'); + $resolvedValid = [ + $resolve('waiting'), + $resolve('pending'), + $resolve('validated'), + $resolve('failed'), + $resolve('canceled'), + ]; + $resolvedLegacy = [ + $resolve('1'), + $resolve('2'), + $resolve('3'), + $resolve('4'), + $resolve('7'), + ]; + $resolvedUppercase = $resolve('VALIDATED'); // THEN - expect($resolvedValid)->toBe(OrderStatus::VALIDATED) - ->and($resolvedLegacy1)->toBeNull() - ->and($resolvedLegacy3)->toBeNull() - ->and($resolvedUnknown)->toBeNull(); + expect($resolvedValid)->toBe([ + OrderStatus::WAITING, + OrderStatus::PENDING, + OrderStatus::VALIDATED, + OrderStatus::FAILED, + OrderStatus::CANCELED, + ]) + ->and($resolvedLegacy)->toBe([null, null, null, null, null]) + ->and($resolvedUppercase)->toBeNull(); }); }); From 470c2d1b9d71e53b0c3b9f42faf3e8ec43a4b27e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 21:19:17 +0100 Subject: [PATCH 169/183] ci(gitlab): install mysql-client in tests_laravel for RefreshDatabase schema import --- .gitlab-ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 275cf3db..6daa45e1 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -257,6 +257,7 @@ tests_laravel: - name: mysql:8.0 alias: mysql before_script: + - apk add --no-cache mysql-client - composer config gitlab-token.lab.s-web.fr $CI_DEPLOY_USER $CI_DEPLOY_PASSWORD - composer install --no-scripts --no-interaction --no-ansi --no-progress --prefer-dist script: From c734ee41e429bfe5633589ff0b08944466acd069 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 21:31:35 +0100 Subject: [PATCH 170/183] ci(gitlab): install mariadb-client and disable TLS verification for CI mysql:8.0 --- .gitlab-ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 6daa45e1..fee8bba0 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -257,7 +257,8 @@ tests_laravel: - name: mysql:8.0 alias: mysql before_script: - - apk add --no-cache mysql-client + - apk add --no-cache mariadb-client + - printf "[client]\nssl=0\n" > ~/.my.cnf - composer config gitlab-token.lab.s-web.fr $CI_DEPLOY_USER $CI_DEPLOY_PASSWORD - composer install --no-scripts --no-interaction --no-ansi --no-progress --prefer-dist script: From 17cca9c43d176d58f2148c5b3292beb5cb9bb7b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 22:02:10 +0100 Subject: [PATCH 171/183] ci(tests_laravel): add mariadb-connector-c and update DB user setup Enhance the CI pipeline for Laravel tests by adding mariadb-connector-c and improving the database user setup process for better reliability. --- .gitlab-ci.yml | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index fee8bba0..56de5ab9 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -257,14 +257,29 @@ tests_laravel: - name: mysql:8.0 alias: mysql before_script: - - apk add --no-cache mariadb-client + - apk add --no-cache mariadb-client mariadb-connector-c - printf "[client]\nssl=0\n" > ~/.my.cnf - composer config gitlab-token.lab.s-web.fr $CI_DEPLOY_USER $CI_DEPLOY_PASSWORD - composer install --no-scripts --no-interaction --no-ansi --no-progress --prefer-dist script: - cp .env.example .env - php artisan key:generate - - php -r "while(true){try{new PDO('mysql:host=mysql;dbname=testing_db','root','password');break;}catch(Exception){sleep(1);}}" + - | + php -r ' + while (true) { + try { + $pdo = new PDO("mysql:host=mysql;dbname=testing_db", "root", "password"); + $account = (string) $pdo->query("SELECT CURRENT_USER()")->fetchColumn(); + [$user, $host] = explode("@", $account, 2); + $pdo->exec("ALTER USER " . $pdo->quote($user) . "@" . $pdo->quote($host) . " IDENTIFIED WITH mysql_native_password BY " . $pdo->quote("password")); + $pdo->exec("FLUSH PRIVILEGES"); + break; + } catch (Exception) { + sleep(1); + } + } + ' + - mysql --user=root --password=password --host=mysql --port=3306 --database=testing_db -e "SELECT 1" - php artisan config:clear - php artisan test --coverage --colors=never --log-junit=coverage/junit.xml --coverage-cobertura=coverage/cobertura.xml --coverage-html=coverage/html after_script: From ec7aaa5cfe41f2ba439a32d58c02d0e3ffbff40e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 22:09:41 +0100 Subject: [PATCH 172/183] ci(gitlab): install icu-data-full in tests_laravel for French locale currency formatting --- .gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 56de5ab9..fac09cdb 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -257,7 +257,7 @@ tests_laravel: - name: mysql:8.0 alias: mysql before_script: - - apk add --no-cache mariadb-client mariadb-connector-c + - apk add --no-cache mariadb-client mariadb-connector-c icu-data-full - printf "[client]\nssl=0\n" > ~/.my.cnf - composer config gitlab-token.lab.s-web.fr $CI_DEPLOY_USER $CI_DEPLOY_PASSWORD - composer install --no-scripts --no-interaction --no-ansi --no-progress --prefer-dist From 1085a2d4db81ee1e8c083f9d12d515c5fe6ef77e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Tue, 17 Nov 2026 09:37:58 +0100 Subject: [PATCH 173/183] test(enums): add enum fixtures for testing BaseEnum functionality - Introduced IntStatusFixture, StringStatusFixture, and MissingLabelFixture for comprehensive testing of enum behavior. --- tests/Unit/Shared/Enums/BaseEnumTest.php | 41 ------------------- tests/Unit/Shared/Enums/IntStatusFixture.php | 24 +++++++++++ .../Unit/Shared/Enums/MissingLabelFixture.php | 21 ++++++++++ .../Unit/Shared/Enums/StringStatusFixture.php | 17 ++++++++ 4 files changed, 62 insertions(+), 41 deletions(-) create mode 100644 tests/Unit/Shared/Enums/IntStatusFixture.php create mode 100644 tests/Unit/Shared/Enums/MissingLabelFixture.php create mode 100644 tests/Unit/Shared/Enums/StringStatusFixture.php diff --git a/tests/Unit/Shared/Enums/BaseEnumTest.php b/tests/Unit/Shared/Enums/BaseEnumTest.php index d05b638a..349a2c04 100644 --- a/tests/Unit/Shared/Enums/BaseEnumTest.php +++ b/tests/Unit/Shared/Enums/BaseEnumTest.php @@ -2,53 +2,12 @@ declare(strict_types=1); -// phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses - namespace Tests\Unit\Shared\Enums; use Shared\Enums\BaseEnum; -use Shared\Enums\HasBaseEnum; covers(BaseEnum::class); -enum IntStatusFixture: int implements HasBaseEnum -{ - /** @use BaseEnum */ - use BaseEnum; - - case PENDING = 1; - case IN_PROGRESS = 2; - case DONE = 3; - - public const array LABELS = [ - 'PENDING' => 'En attente', - 'IN_PROGRESS' => 'In Progress', - 'DONE' => 'Terminé', - ]; -} - -enum StringStatusFixture: string implements HasBaseEnum -{ - /** @use BaseEnum */ - use BaseEnum; - - case DRAFT = 'draft'; - case PUBLISHED = 'published'; -} - -enum MissingLabelFixture: string implements HasBaseEnum -{ - /** @use BaseEnum */ - use BaseEnum; - - case FIRST = 'first'; - case SECOND = 'second'; - - public const array LABELS = [ - 'FIRST' => 'First', - ]; -} - it('exposes value, name, and configured label for int-backed enum', function (): void { // GIVEN $enum = IntStatusFixture::IN_PROGRESS; diff --git a/tests/Unit/Shared/Enums/IntStatusFixture.php b/tests/Unit/Shared/Enums/IntStatusFixture.php new file mode 100644 index 00000000..c535847c --- /dev/null +++ b/tests/Unit/Shared/Enums/IntStatusFixture.php @@ -0,0 +1,24 @@ + */ + use BaseEnum; + + case PENDING = 1; + case IN_PROGRESS = 2; + case DONE = 3; + + public const array LABELS = [ + 'PENDING' => 'En attente', + 'IN_PROGRESS' => 'In Progress', + 'DONE' => 'Terminé', + ]; +} diff --git a/tests/Unit/Shared/Enums/MissingLabelFixture.php b/tests/Unit/Shared/Enums/MissingLabelFixture.php new file mode 100644 index 00000000..bdcea3b2 --- /dev/null +++ b/tests/Unit/Shared/Enums/MissingLabelFixture.php @@ -0,0 +1,21 @@ + */ + use BaseEnum; + + case FIRST = 'first'; + case SECOND = 'second'; + + public const array LABELS = [ + 'FIRST' => 'First', + ]; +} diff --git a/tests/Unit/Shared/Enums/StringStatusFixture.php b/tests/Unit/Shared/Enums/StringStatusFixture.php new file mode 100644 index 00000000..c047267b --- /dev/null +++ b/tests/Unit/Shared/Enums/StringStatusFixture.php @@ -0,0 +1,17 @@ + */ + use BaseEnum; + + case DRAFT = 'draft'; + case PUBLISHED = 'published'; +} From 101d0ff018ba8a30cf56c707f95684240c3c6ac7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Tue, 17 Nov 2026 09:46:05 +0100 Subject: [PATCH 174/183] feat(EmployeeCsvReaderService): refactor CSV reader creation Updated the importEmployeesFromCsv method to use a dedicated createCsvReader method for better encoding handling and improved readability. --- app/Services/EmployeeCsvReaderService.php | 30 ++++- .../Services/EmployeeCsvReaderServiceTest.php | 109 ++++++++++++++++++ 2 files changed, 138 insertions(+), 1 deletion(-) diff --git a/app/Services/EmployeeCsvReaderService.php b/app/Services/EmployeeCsvReaderService.php index 6c5f5df3..47673c2d 100644 --- a/app/Services/EmployeeCsvReaderService.php +++ b/app/Services/EmployeeCsvReaderService.php @@ -35,8 +35,8 @@ class EmployeeCsvReaderService try { $sourceEncoding = $this->detectEncoding($fromStream); + $csv = $this->createCsvReader($fromStream); - $csv = Reader::from($fromStream); $csv->setHeaderOffset(0); $csv->setEscape(self::CSV_ESCAPE); $csv->setDelimiter(self::CSV_DELIMITER); @@ -87,6 +87,34 @@ class EmployeeCsvReaderService } } + /** + * League\Csv stream filters (used by CharsetConverter) require a PHP stream resource + * rather than an SplFileObject instance. + * + * @return \League\Csv\Reader> + */ + private function createCsvReader(\SplFileObject $fromStream): Reader + { + $realPath = $fromStream->getRealPath(); + if ($realPath !== false && is_file($realPath)) { + return Reader::fromPath($realPath); + } + + $fromStream->rewind(); + $content = ''; + while (! $fromStream->eof()) { + $chunk = $fromStream->fread(8192); + if ($chunk === false) { + throw new \UnexpectedValueException('Failed to read from input stream.'); + } + $content .= $chunk; + } + + $fromStream->rewind(); + + return Reader::fromString($content); + } + private function detectEncoding(\SplFileObject $fromStream): ?string { $fromStream->rewind(); diff --git a/tests/Unit/App/Services/EmployeeCsvReaderServiceTest.php b/tests/Unit/App/Services/EmployeeCsvReaderServiceTest.php index 288a81c0..501a4f50 100644 --- a/tests/Unit/App/Services/EmployeeCsvReaderServiceTest.php +++ b/tests/Unit/App/Services/EmployeeCsvReaderServiceTest.php @@ -98,4 +98,113 @@ describe('EmployeeCsvReaderService', function (): void { expect(fn () => $service->importEmployeesFromCsv($unreadable)) ->toThrow(\InvalidArgumentException::class, 'Input stream must be readable.'); }); + + it('imports employees from a Windows-1252 encoded CSV file', function (): void { + // GIVEN + /** @var \Psr\Log\LoggerInterface&\Mockery\MockInterface $logger */ + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldReceive('debug')->once(); + $logger->shouldReceive('info')->once(); + $logger->shouldReceive('error')->never(); + + $service = new EmployeeCsvReaderService($logger); + + $filePath = tempnam(sys_get_temp_dir(), 'employees-csv-win1252-'); + expect($filePath)->not->toBeFalse(); + + $utf8Csv = implode("\n", [ + 'Matricule;Nom;Prénom;Date début;Date fin;Date fin prévue;Etablissement;Site;Service', + '1234567;François;Éric;01/10/2026;;;ETAB01;PA;LDCCAV030', + ]); + $win1252Csv = mb_convert_encoding($utf8Csv, 'Windows-1252', 'UTF-8'); + file_put_contents($filePath, $win1252Csv); + + $fileObject = new \SplFileObject($filePath, 'r'); + + // WHEN + $items = $service->importEmployeesFromCsv($fileObject); + + // THEN + $firstItem = $items[0]; + assert($firstItem instanceof EmployeeCsvImportLineService); + + expect($items)->toHaveCount(1) + ->and($firstItem->matricule)->toBe('1234567') + ->and($firstItem->lastName)->toBe('François') + ->and($firstItem->firstName)->toBe('Éric') + ->and($firstItem->service)->toBe('030'); + + unlink($filePath); + }); + + it('imports employees from a UTF-8 BOM CSV file', function (): void { + // GIVEN + /** @var \Psr\Log\LoggerInterface&\Mockery\MockInterface $logger */ + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldReceive('debug')->once(); + $logger->shouldReceive('error')->never(); + + $service = new EmployeeCsvReaderService($logger); + + $filePath = tempnam(sys_get_temp_dir(), 'employees-csv-bom-'); + expect($filePath)->not->toBeFalse(); + + $csvWithBom = "\xEF\xBB\xBF" . implode("\n", [ + 'Matricule;Nom;Prénom;Date début;Date fin;Date fin prévue;Etablissement;Site;Service', + '1234567;Dupont;Hélène;01/10/2026;;;ETAB01;PA;LDCCAV030', + ]); + file_put_contents($filePath, $csvWithBom); + + $fileObject = new \SplFileObject($filePath, 'r'); + + // WHEN + $items = $service->importEmployeesFromCsv($fileObject); + + // THEN + $firstItem = $items[0]; + assert($firstItem instanceof EmployeeCsvImportLineService); + + expect($items)->toHaveCount(1) + ->and($firstItem->firstName)->toBe('Hélène'); + + unlink($filePath); + }); + + it('imports employees from a Windows-1252 encoded SplTempFileObject', function (): void { + // GIVEN + /** @var \Psr\Log\LoggerInterface&\Mockery\MockInterface $logger */ + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldReceive('debug')->once(); + $logger->shouldReceive('info')->once(); + $logger->shouldReceive('error')->never(); + + $service = new EmployeeCsvReaderService($logger); + + $utf8Csv = implode("\n", [ + 'Matricule;Nom;Prénom;Date début;Date fin;Date fin prévue;Etablissement;Site;Service', + '1234567;Noël;Céline;01/10/2026;;;ETAB01;PA;LDCCAV030', + ]); + $win1252Csv = mb_convert_encoding($utf8Csv, 'Windows-1252', 'UTF-8'); + + $tempFile = new class () extends \SplTempFileObject + { + public function isReadable(): bool + { + return true; + } + }; + $tempFile->fwrite($win1252Csv); + $tempFile->rewind(); + + // WHEN + $items = $service->importEmployeesFromCsv($tempFile); + + // THEN + $firstItem = $items[0]; + assert($firstItem instanceof EmployeeCsvImportLineService); + + expect($items)->toHaveCount(1) + ->and($firstItem->lastName)->toBe('Noël') + ->and($firstItem->firstName)->toBe('Céline'); + }); }); From 617d1f70e9b24379b7b406fe8ac18b4acb8415ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Tue, 17 Nov 2026 12:13:55 +0100 Subject: [PATCH 175/183] feat(manifest): add LOG_LEVEL configuration Added LOG_LEVEL with a default value of "warning" to the manifest for better logging control. --- manifest.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/manifest.yaml b/manifest.yaml index d851ec04..18267856 100644 --- a/manifest.yaml +++ b/manifest.yaml @@ -35,6 +35,7 @@ data: FILESYSTEM_DISK: "${APP_FILESYSTEM_DISK}" LDC_HEADQUARTERS_PHONE_RECEPTION: "${APP_LDC_HEADQUARTERS_PHONE_RECEPTION}" LOG_CHANNEL: "k8s" + LOG_LEVEL: "warning" MAIL_ENCRYPTION: "${APP_MAIL_ENCRYPTION}" MAIL_FROM_ADDRESS: "${APP_MAIL_FROM_ADDRESS}" MAIL_FROM_NAME: "${APP_APP_NAME}" From ad2c8f631b4b4256a009dd6a50c2f35c6df46b69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Tue, 17 Nov 2026 12:15:28 +0100 Subject: [PATCH 176/183] feat(shared): encapsulate UUID generation and parsing in UuidHelper --- shared/Helpers/UuidHelper.php | 31 +++ shared/ValueObjects/CrmHashcode.php | 3 +- tests/Unit/Shared/Helpers/UuidHelperTest.php | 236 +++++++++++------- .../Shared/ValueObjects/CrmHashcodeTest.php | 66 ++--- 4 files changed, 210 insertions(+), 126 deletions(-) diff --git a/shared/Helpers/UuidHelper.php b/shared/Helpers/UuidHelper.php index 1af7a150..2d80f320 100644 --- a/shared/Helpers/UuidHelper.php +++ b/shared/Helpers/UuidHelper.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Shared\Helpers; +use Carbon\CarbonImmutable; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; @@ -17,6 +18,36 @@ final readonly class UuidHelper // Static class } + public static function fromString(string $uuid): UuidInterface + { + if (! Uuid::isValid($uuid)) { + throw InvalidUuidException::forValue($uuid); + } + + return Uuid::fromString($uuid); + } + + public static function v4(): UuidInterface + { + return Uuid::uuid4(); + } + + public static function v7(?\DateTimeInterface $dateTime = null): UuidInterface + { + return Uuid::uuid7($dateTime ?? CarbonImmutable::now()); + } + + public static function parse(string $value): UuidInterface + { + $trimmed = trim($value); + + if (self::isValid($trimmed)) { + return self::fromString($trimmed); + } + + return self::fromBase58($trimmed); + } + public static function isValid(string $uuid): bool { return Uuid::isValid($uuid); diff --git a/shared/ValueObjects/CrmHashcode.php b/shared/ValueObjects/CrmHashcode.php index 49e4a9d4..04850c0e 100644 --- a/shared/ValueObjects/CrmHashcode.php +++ b/shared/ValueObjects/CrmHashcode.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace Shared\ValueObjects; -use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; use Shared\Helpers\UuidHelper; @@ -30,6 +29,6 @@ final readonly class CrmHashcode implements \Stringable public static function fromString(string $value): self { - return new self(Uuid::fromString($value)); + return new self(UuidHelper::fromString($value)); } } diff --git a/tests/Unit/Shared/Helpers/UuidHelperTest.php b/tests/Unit/Shared/Helpers/UuidHelperTest.php index 53a80543..a72c6122 100644 --- a/tests/Unit/Shared/Helpers/UuidHelperTest.php +++ b/tests/Unit/Shared/Helpers/UuidHelperTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Tests\Unit\Shared\Helpers; +use Carbon\CarbonImmutable; use Ramsey\Uuid\Lazy\LazyUuidFromString; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; @@ -12,97 +13,148 @@ use Shared\Helpers\UuidHelper; covers(UuidHelper::class); -it('validates uuid strings with isValid', function (): void { - // GIVEN - $v4 = Uuid::uuid4()->toString(); - $v7 = Uuid::uuid7()->toString(); - $invalid = 'not-a-uuid'; +describe('UuidHelper', function (): void { + it('validates uuid strings with isValid', function (): void { + // GIVEN + $v4 = Uuid::uuid4()->toString(); + $v7 = Uuid::uuid7()->toString(); + $invalid = 'not-a-uuid'; - // WHEN & THEN - expect(UuidHelper::isValid($v4))->toBeTrue() - ->and(UuidHelper::isValid($v7))->toBeTrue() - ->and(UuidHelper::isValid($invalid))->toBeFalse(); -}); - -it('roundtrips v4 and v7 uuids through base58 including surrounding whitespace', function (): void { - // GIVEN - $v4 = Uuid::uuid4(); - $v7 = Uuid::uuid7(); - - // WHEN - $v4Base58 = UuidHelper::toBase58($v4); - $v7Base58 = UuidHelper::toBase58($v7); - - $decodedV4 = UuidHelper::fromBase58(" {$v4Base58} \n"); - $decodedV7 = UuidHelper::fromBase58("\t{$v7Base58} "); - - // THEN - expect($decodedV4->toString())->toBe($v4->toString()) - ->and($decodedV7->toString())->toBe($v7->toString()); -}); - -it('rejects invalid base58 inputs', function (string $input): void { - // GIVEN / WHEN / THEN - expect(static fn (): UuidInterface => UuidHelper::fromBase58($input)) - ->toThrow(InvalidUuidException::class); -})->with([ - 'empty string' => [''], - 'too short' => ['12345678901234567890'], - 'too long' => ['12345678901234567890123'], - 'ambiguous chars 0OIl' => ['0OIl123456789012345678'], - 'invalid payload' => ['zzzzzzzzzzzzzzzzzzzzzz'], -]); - -it('detects uuid versions for v4, v7, and v1', function (): void { - // GIVEN - $v4 = Uuid::uuid4(); - $v7 = Uuid::uuid7(); - $v1 = Uuid::uuid1(); - - // WHEN & THEN - expect(UuidHelper::version($v4))->toBe(4) - ->and(UuidHelper::isV4($v4))->toBeTrue() - ->and(UuidHelper::isV7($v4))->toBeFalse() - ->and(UuidHelper::version($v7))->toBe(7) - ->and(UuidHelper::isV4($v7))->toBeFalse() - ->and(UuidHelper::isV7($v7))->toBeTrue() - ->and(UuidHelper::version($v1))->toBe(1) - ->and(UuidHelper::isV4($v1))->toBeFalse() - ->and(UuidHelper::isV7($v1))->toBeFalse(); -}); - -it('passes validateUuid for valid uuid and throws for invalid UuidInterface', function (): void { - // GIVEN - $valid = Uuid::uuid4(); - $invalid = new LazyUuidFromString('invalid'); - - // WHEN - UuidHelper::validateUuid($valid); - - // THEN - expect(static function () use ($invalid): void { - UuidHelper::validateUuid($invalid); - })->toThrow(InvalidUuidException::class); -}); - -it('extracts exact utc datetime with millisecond precision from v7 uuid', function (): void { - // GIVEN - $expected = new \DateTimeImmutable('2025-06-15 12:34:56.789000', new \DateTimeZone('UTC')); - $v7 = Uuid::uuid7($expected); - - // WHEN - $actual = UuidHelper::toDateTime($v7); - - // THEN - expect($actual->getTimezone()->getName())->toBe('UTC') - ->and($actual->format('Y-m-d H:i:s.v'))->toBe($expected->format('Y-m-d H:i:s.v')); -}); - -it('throws InvalidUuidException when extracting datetime from non-v7 uuid', function (): void { - // GIVEN - $v4 = Uuid::uuid4(); - - // WHEN & THEN - expect(static fn (): \DateTimeImmutable => UuidHelper::toDateTime($v4)) - ->toThrow(InvalidUuidException::class); + // WHEN & THEN + expect(UuidHelper::isValid($v4))->toBeTrue() + ->and(UuidHelper::isValid($v7))->toBeTrue() + ->and(UuidHelper::isValid($invalid))->toBeFalse(); + }); + + it('roundtrips v4 and v7 uuids through base58 including surrounding whitespace', function (): void { + // GIVEN + $v4 = Uuid::uuid4(); + $v7 = Uuid::uuid7(); + + // WHEN + $v4Base58 = UuidHelper::toBase58($v4); + $v7Base58 = UuidHelper::toBase58($v7); + + $decodedV4 = UuidHelper::fromBase58(" {$v4Base58} \n"); + $decodedV7 = UuidHelper::fromBase58("\t{$v7Base58} "); + + // THEN + expect($decodedV4->toString())->toBe($v4->toString()) + ->and($decodedV7->toString())->toBe($v7->toString()); + }); + + it('rejects invalid base58 inputs', function (string $input): void { + // GIVEN / WHEN / THEN + expect(static fn (): UuidInterface => UuidHelper::fromBase58($input)) + ->toThrow(InvalidUuidException::class); + })->with([ + 'empty string' => [''], + 'too short' => ['12345678901234567890'], + 'too long' => ['12345678901234567890123'], + 'ambiguous chars 0OIl' => ['0OIl123456789012345678'], + 'invalid payload' => ['zzzzzzzzzzzzzzzzzzzzzz'], + ]); + + it('detects uuid versions for v4, v7, and v1', function (): void { + // GIVEN + $v4 = Uuid::uuid4(); + $v7 = Uuid::uuid7(); + $v1 = Uuid::uuid1(); + + // WHEN & THEN + expect(UuidHelper::version($v4))->toBe(4) + ->and(UuidHelper::isV4($v4))->toBeTrue() + ->and(UuidHelper::isV7($v4))->toBeFalse() + ->and(UuidHelper::version($v7))->toBe(7) + ->and(UuidHelper::isV4($v7))->toBeFalse() + ->and(UuidHelper::isV7($v7))->toBeTrue() + ->and(UuidHelper::version($v1))->toBe(1) + ->and(UuidHelper::isV4($v1))->toBeFalse() + ->and(UuidHelper::isV7($v1))->toBeFalse(); + }); + + it('passes validateUuid for valid uuid and throws for invalid UuidInterface', function (): void { + // GIVEN + $valid = Uuid::uuid4(); + $invalid = new LazyUuidFromString('invalid'); + + // WHEN + UuidHelper::validateUuid($valid); + + // THEN + expect(static function () use ($invalid): void { + UuidHelper::validateUuid($invalid); + })->toThrow(InvalidUuidException::class); + }); + + it('extracts exact utc datetime with millisecond precision from v7 uuid', function (): void { + // GIVEN + $expected = new \DateTimeImmutable('2025-06-15 12:34:56.789000', new \DateTimeZone('UTC')); + $v7 = Uuid::uuid7($expected); + + // WHEN + $actual = UuidHelper::toDateTime($v7); + + // THEN + expect($actual->getTimezone()->getName())->toBe('UTC') + ->and($actual->format('Y-m-d H:i:s.v'))->toBe($expected->format('Y-m-d H:i:s.v')); + }); + + it('throws InvalidUuidException when extracting datetime from non-v7 uuid', function (): void { + // GIVEN + $v4 = Uuid::uuid4(); + + // WHEN & THEN + expect(static fn (): \DateTimeImmutable => UuidHelper::toDateTime($v4)) + ->toThrow(InvalidUuidException::class); + }); + + it('generates a v7 uuid using CarbonImmutable::now when no datetime is provided', function (): void { + // GIVEN + $frozen = CarbonImmutable::parse('2026-11-16 12:34:56.000', 'UTC'); + CarbonImmutable::setTestNow($frozen); + + try { + // WHEN + $uuid = UuidHelper::v7(); + + // THEN + expect(UuidHelper::isV7($uuid))->toBeTrue() + ->and(UuidHelper::toDateTime($uuid)->format('Y-m-d H:i:s'))->toBe('2026-11-16 12:34:56'); + } finally { + CarbonImmutable::setTestNow(); + } + }); + + it('generates a v7 uuid using the provided datetime', function (): void { + // GIVEN + $dateTime = new \DateTimeImmutable('2025-05-01 08:15:30', new \DateTimeZone('UTC')); + + // WHEN + $uuid = UuidHelper::v7($dateTime); + + // THEN + expect(UuidHelper::isV7($uuid))->toBeTrue() + ->and(UuidHelper::toDateTime($uuid)->format('Y-m-d H:i:s'))->toBe('2025-05-01 08:15:30'); + }); + + it('generates a v4 uuid with UuidHelper::v4', function (): void { + // WHEN + $uuid = UuidHelper::v4(); + + // THEN + expect(UuidHelper::isV4($uuid))->toBeTrue(); + }); + + it('parses both rfc4122 and base58 uuids with UuidHelper::parse and throws on invalid input', function (): void { + // GIVEN + $v7 = UuidHelper::v7(); + $base58 = UuidHelper::toBase58($v7); + + // WHEN & THEN + expect(UuidHelper::parse($v7->toString())->toString())->toBe($v7->toString()) + ->and(UuidHelper::parse($base58)->toString())->toBe($v7->toString()) + ->and(static fn (): UuidInterface => UuidHelper::parse('invalid-uuid')) + ->toThrow(InvalidUuidException::class); + }); }); diff --git a/tests/Unit/Shared/ValueObjects/CrmHashcodeTest.php b/tests/Unit/Shared/ValueObjects/CrmHashcodeTest.php index 99f5e973..62300f30 100644 --- a/tests/Unit/Shared/ValueObjects/CrmHashcodeTest.php +++ b/tests/Unit/Shared/ValueObjects/CrmHashcodeTest.php @@ -4,42 +4,44 @@ declare(strict_types=1); namespace Tests\Unit\Shared\ValueObjects; -use Ramsey\Uuid\Exception\InvalidUuidStringException; -use Ramsey\Uuid\Uuid; +use Shared\Exceptions\InvalidUuidException; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; covers(CrmHashcode::class); -it('instantiates from Uuid v4 and fromString with matching value and string cast', function (): void { - // GIVEN - $uuid = Uuid::uuid4(); - $v4String = $uuid->toString(); +describe('CrmHashcode', function (): void { + it('instantiates from Uuid v4 and fromString with matching value and string cast', function (): void { + // GIVEN + $uuid = UuidHelper::v4(); + $v4String = $uuid->toString(); - // WHEN - $fromUuid = new CrmHashcode($uuid); - $fromString = CrmHashcode::fromString($v4String); + // WHEN + $fromUuid = new CrmHashcode($uuid); + $fromString = CrmHashcode::fromString($v4String); - // THEN - expect($fromUuid->value)->toBe($v4String) - ->and((string) $fromUuid)->toBe($v4String) - ->and($fromString->value)->toBe($v4String) - ->and((string) $fromString)->toBe($v4String); -}); - -it('rejects non-v4 uuids with DomainException', function (): void { - // GIVEN - $v7 = Uuid::uuid7(); - $v1 = Uuid::uuid1(); - - // WHEN & THEN - expect(static fn (): CrmHashcode => new CrmHashcode($v7)) - ->toThrow(\DomainException::class) - ->and(static fn (): CrmHashcode => new CrmHashcode($v1)) - ->toThrow(\DomainException::class); -}); - -it('throws InvalidUuidStringException when fromString receives invalid uuid', function (): void { - // GIVEN / WHEN / THEN - expect(static fn (): CrmHashcode => CrmHashcode::fromString('not-a-uuid')) - ->toThrow(InvalidUuidStringException::class); + // THEN + expect($fromUuid->value)->toBe($v4String) + ->and((string) $fromUuid)->toBe($v4String) + ->and($fromString->value)->toBe($v4String) + ->and((string) $fromString)->toBe($v4String); + }); + + it('rejects non-v4 uuids with DomainException', function (): void { + // GIVEN + $v7 = UuidHelper::v7(); + $v1 = UuidHelper::fromString('00000000-0000-1000-8000-000000000000'); + + // WHEN & THEN + expect(static fn (): CrmHashcode => new CrmHashcode($v7)) + ->toThrow(\DomainException::class) + ->and(static fn (): CrmHashcode => new CrmHashcode($v1)) + ->toThrow(\DomainException::class); + }); + + it('throws InvalidUuidException when fromString receives invalid uuid', function (): void { + // GIVEN / WHEN / THEN + expect(static fn (): CrmHashcode => CrmHashcode::fromString('not-a-uuid')) + ->toThrow(InvalidUuidException::class); + }); }); From 75784ae7190b37b96fc941dbe518d7ac9f125025 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Tue, 17 Nov 2026 12:15:34 +0100 Subject: [PATCH 177/183] refactor(uuid): migrate app, domain, infra, and factories to UuidHelper --- app/Casts/CrmHashcodeCast.php | 6 +++--- app/Casts/OrderLineProductCast.php | 7 ++----- app/Cqs/Actions/Customers/RegisterCustomer.php | 4 ++-- app/Http/Requests/Basket/AddBasketRequest.php | 6 +++--- app/Http/Requests/Basket/RemoveBasketRequest.php | 4 ++-- app/Http/Requests/Bo/Shops/IndexShopRequest.php | 5 ++--- app/Http/Requests/Fo/UnsubscribeNewsletterRequest.php | 4 ++-- app/Models/Customer.php | 4 ++-- app/Models/Order.php | 8 ++++---- app/Models/OrderTunnelAttempt.php | 4 ++-- app/Models/PickupException.php | 4 ++-- app/Models/Product.php | 4 ++-- app/Models/Shop.php | 4 ++-- app/Traits/Models/HasUuidV7AsPrimaryKey.php | 7 +++---- database/factories/PickupExceptionFactory.php | 4 ++-- database/factories/ShopFactory.php | 4 ++-- domain/Models/ValueObjects/OrderReference.php | 3 +-- domain/Services/OrderService.php | 6 +++--- infra/Adapters/Repositories/EloquentOrderRepository.php | 6 +++--- infra/Adapters/Repositories/EloquentProductRepository.php | 4 ++-- infra/Adapters/Serializers/BasketSerializer.php | 6 +++--- infra/Adapters/Services/AppSessionService.php | 6 +++--- 22 files changed, 52 insertions(+), 58 deletions(-) diff --git a/app/Casts/CrmHashcodeCast.php b/app/Casts/CrmHashcodeCast.php index 91d8beeb..2a8b6330 100644 --- a/app/Casts/CrmHashcodeCast.php +++ b/app/Casts/CrmHashcodeCast.php @@ -6,7 +6,7 @@ namespace App\Casts; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Database\Eloquent\Model; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; /** @implements CastsAttributes */ @@ -19,7 +19,7 @@ class CrmHashcodeCast implements CastsAttributes throw new \UnexpectedValueException('CrmHashcode must be a string.'); } - $uuid = Uuid::fromString($value); + $uuid = UuidHelper::fromString($value); return new CrmHashcode($uuid); } @@ -32,7 +32,7 @@ class CrmHashcodeCast implements CastsAttributes } if (is_string($value)) { - $value = new CrmHashcode(Uuid::fromString($value)); + $value = new CrmHashcode(UuidHelper::fromString($value)); } if (! ($value instanceof CrmHashcode)) { diff --git a/app/Casts/OrderLineProductCast.php b/app/Casts/OrderLineProductCast.php index f1958d37..26376096 100644 --- a/app/Casts/OrderLineProductCast.php +++ b/app/Casts/OrderLineProductCast.php @@ -14,8 +14,7 @@ use Domain\Models\ValueObjects\ProductWeight; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Arr; -use Ramsey\Uuid\Uuid; -use Symfony\Component\Uid\Uuid as SymfonyUuid; +use Shared\Helpers\UuidHelper; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; /** @@ -45,9 +44,7 @@ class OrderLineProductCast implements CastsAttributes return new OrderLineProduct( incoId: new IncoId(Arr::integer($data, 'inco_id')), - originalId: new ProductId(Uuid::fromString( - SymfonyUuid::fromString(Arr::string($data, 'original_id'))->toRfc4122() - )), + originalId: new ProductId(UuidHelper::parse(Arr::string($data, 'original_id'))), name: Arr::string($data, 'name'), weight: new ProductWeight( value: Arr::integer($data, 'weight'), diff --git a/app/Cqs/Actions/Customers/RegisterCustomer.php b/app/Cqs/Actions/Customers/RegisterCustomer.php index 34a25a72..2082196b 100644 --- a/app/Cqs/Actions/Customers/RegisterCustomer.php +++ b/app/Cqs/Actions/Customers/RegisterCustomer.php @@ -22,7 +22,7 @@ use Domain\Models\ValueObjects\CrmCustomer; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Validation\ValidationException; use Infrastructure\Adapters\Services\AppCustomerAuthService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; use Webmozart\Assert\Assert; @@ -114,7 +114,7 @@ final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeo 'email' => $input->email, ]); // * Temp hashcode to satisfy constraint - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->saveOrFail(); $employee->customer()->associate($customer); diff --git a/app/Http/Requests/Basket/AddBasketRequest.php b/app/Http/Requests/Basket/AddBasketRequest.php index 1263699a..d128d2a3 100644 --- a/app/Http/Requests/Basket/AddBasketRequest.php +++ b/app/Http/Requests/Basket/AddBasketRequest.php @@ -11,7 +11,7 @@ use App\Cqs\Queries\Products\GetProductWithPricingQuery; use Domain\Models\ValueObjects\Entities\ProductId; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Gate; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; class AddBasketRequest extends FormRequest { @@ -25,7 +25,7 @@ class AddBasketRequest extends FormRequest { $rowId = $this->input('rowId'); - if (! is_string($rowId) || ! Uuid::isValid($rowId)) { + if (! is_string($rowId) || ! UuidHelper::isValid($rowId)) { return false; } @@ -48,7 +48,7 @@ class AddBasketRequest extends FormRequest public function getProductId(): ProductId { return new ProductId( - Uuid::fromString( + UuidHelper::fromString( $this->string('rowId')->value() ) ); diff --git a/app/Http/Requests/Basket/RemoveBasketRequest.php b/app/Http/Requests/Basket/RemoveBasketRequest.php index ec523d6b..bab01434 100644 --- a/app/Http/Requests/Basket/RemoveBasketRequest.php +++ b/app/Http/Requests/Basket/RemoveBasketRequest.php @@ -8,7 +8,7 @@ use App\Cqs\Actions\Basket\RemoveProductFromBasketInput; use App\Cqs\Actions\Basket\RemoveQuantityFromBasketInput; use Domain\Models\ValueObjects\Entities\ProductId; use Illuminate\Foundation\Http\FormRequest; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; class RemoveBasketRequest extends FormRequest { @@ -36,7 +36,7 @@ class RemoveBasketRequest extends FormRequest public function getProductId(): ProductId { return new ProductId( - Uuid::fromString( + UuidHelper::fromString( $this->string('rowId')->value() ) ); diff --git a/app/Http/Requests/Bo/Shops/IndexShopRequest.php b/app/Http/Requests/Bo/Shops/IndexShopRequest.php index b157ec67..7f116bd8 100644 --- a/app/Http/Requests/Bo/Shops/IndexShopRequest.php +++ b/app/Http/Requests/Bo/Shops/IndexShopRequest.php @@ -7,7 +7,6 @@ namespace App\Http\Requests\Bo\Shops; use Domain\Models\ValueObjects\Entities\PickupExceptionId; use Illuminate\Foundation\Http\FormRequest; use Infrastructure\Adapters\Services\AppAdminAuthService; -use Ramsey\Uuid\Uuid; use Shared\Helpers\UuidHelper; class IndexShopRequest extends FormRequest @@ -41,11 +40,11 @@ class IndexShopRequest extends FormRequest public function toPickupExceptionId(): ?PickupExceptionId { $raw = $this->session()->get(self::SESSION_KEY); - if ($raw === null || ! is_string($raw) || $raw === '' || ! Uuid::isValid($raw)) { + if ($raw === null || ! is_string($raw) || $raw === '' || ! UuidHelper::isValid($raw)) { return null; } - $uuid = Uuid::fromString($raw); + $uuid = UuidHelper::fromString($raw); if (! UuidHelper::isV7($uuid)) { return null; } diff --git a/app/Http/Requests/Fo/UnsubscribeNewsletterRequest.php b/app/Http/Requests/Fo/UnsubscribeNewsletterRequest.php index c44703c6..4aec3346 100644 --- a/app/Http/Requests/Fo/UnsubscribeNewsletterRequest.php +++ b/app/Http/Requests/Fo/UnsubscribeNewsletterRequest.php @@ -5,7 +5,7 @@ declare(strict_types=1); namespace App\Http\Requests\Fo; use Illuminate\Foundation\Http\FormRequest; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; class UnsubscribeNewsletterRequest extends FormRequest @@ -24,7 +24,7 @@ class UnsubscribeNewsletterRequest extends FormRequest $this->string('hashcode')->whenIsUuid( function (string $value) use (&$hashcode) { - $hashcode = new CrmHashcode(Uuid::fromString($value)); + $hashcode = new CrmHashcode(UuidHelper::fromString($value)); } ); diff --git a/app/Models/Customer.php b/app/Models/Customer.php index 9c4dec09..469b7a6e 100644 --- a/app/Models/Customer.php +++ b/app/Models/Customer.php @@ -15,7 +15,7 @@ use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; /** * @property string $id @@ -76,7 +76,7 @@ class Customer extends Authenticatable implements CustomerDetails, MustVerifyEma public function getId(): ShopperId { - return new ShopperId(Uuid::fromString($this->id)); + return new ShopperId(UuidHelper::fromString($this->id)); } /** @return \Illuminate\Database\Eloquent\Relations\HasOne<\App\Models\Employee,$this> */ diff --git a/app/Models/Order.php b/app/Models/Order.php index 4c957457..e7330305 100644 --- a/app/Models/Order.php +++ b/app/Models/Order.php @@ -19,7 +19,7 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; /** * @property string $id @@ -50,7 +50,7 @@ class Order extends Model public function getId(): OrderId { - return new OrderId(Uuid::fromString($this->id)); + return new OrderId(UuidHelper::fromString($this->id)); } /** @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\OrderLine,$this> */ @@ -68,8 +68,8 @@ class Order extends Model /** @param Builder $query */ protected function scopeWhereCreatedAtBetween(Builder $query, CarbonInterface $start, CarbonInterface $end): void { - $minUuid = (string) Uuid::uuid7($start->copy()->startOfDay()); - $maxUuid = (string) Uuid::uuid7($end->copy()->endOfDay()); + $minUuid = (string) UuidHelper::v7($start->copy()->startOfDay()); + $maxUuid = (string) UuidHelper::v7($end->copy()->endOfDay()); $query->whereBetween('id', [$minUuid, $maxUuid]); } diff --git a/app/Models/OrderTunnelAttempt.php b/app/Models/OrderTunnelAttempt.php index ee92e7f2..970e2b9f 100644 --- a/app/Models/OrderTunnelAttempt.php +++ b/app/Models/OrderTunnelAttempt.php @@ -9,7 +9,7 @@ use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Concerns\HasUuids; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; /** * @property string $id @@ -34,7 +34,7 @@ class OrderTunnelAttempt extends Model public function newUniqueId(): string { - return Uuid::uuid7()->toString(); + return UuidHelper::v7()->toString(); } /** diff --git a/app/Models/PickupException.php b/app/Models/PickupException.php index 38514381..cb223e57 100644 --- a/app/Models/PickupException.php +++ b/app/Models/PickupException.php @@ -13,7 +13,7 @@ use Illuminate\Database\Eloquent\Attributes\Guarded; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; /** * @property string $id @@ -49,7 +49,7 @@ class PickupException extends Model public function getId(): PickupExceptionId { - return new PickupExceptionId(Uuid::fromString($this->id)); + return new PickupExceptionId(UuidHelper::fromString($this->id)); } public function setAsManuallySaved(): void diff --git a/app/Models/Product.php b/app/Models/Product.php index 17830478..71675ad6 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -33,7 +33,7 @@ use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Facades\Date; use Illuminate\Support\Str; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Spatie\Sitemap\Tags\Url; use Uwil\Laravel\Redirections\Interfaces\RedirectableInterface; use Uwil\Laravel\Redirections\Traits\IsRedirectable; @@ -138,7 +138,7 @@ class Product extends Model implements ModelWithOrder, ModelWithStar, ModelWithS public function getId(): ProductId { - return new ProductId(Uuid::fromString($this->id)); + return new ProductId(UuidHelper::fromString($this->id)); } #[\Override] diff --git a/app/Models/Shop.php b/app/Models/Shop.php index e0ecca4e..f97d0042 100644 --- a/app/Models/Shop.php +++ b/app/Models/Shop.php @@ -12,7 +12,7 @@ use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; /** * @property string $id @@ -55,7 +55,7 @@ class Shop extends Model public function getId(): ShopId { - return new ShopId(Uuid::fromString($this->id)); + return new ShopId(UuidHelper::fromString($this->id)); } /** @return \Illuminate\Database\Eloquent\Relations\BelongsToMany<\App\Models\PickupException,$this,\App\Models\ShopPickupExceptionPivot> */ diff --git a/app/Traits/Models/HasUuidV7AsPrimaryKey.php b/app/Traits/Models/HasUuidV7AsPrimaryKey.php index ad2269f3..70d87a35 100644 --- a/app/Traits/Models/HasUuidV7AsPrimaryKey.php +++ b/app/Traits/Models/HasUuidV7AsPrimaryKey.php @@ -8,8 +8,7 @@ use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Concerns\HasUuids; -use Ramsey\Uuid\Uuid; -use Symfony\Component\Uid\UuidV7; +use Shared\Helpers\UuidHelper; /** @mixin \Illuminate\Database\Eloquent\Model */ trait HasUuidV7AsPrimaryKey @@ -24,7 +23,7 @@ trait HasUuidV7AsPrimaryKey public function newUniqueId(): string { - return (string) Uuid::uuid7(); + return (string) UuidHelper::v7(); } public function getCreatedAtColumn() @@ -39,7 +38,7 @@ trait HasUuidV7AsPrimaryKey { return Attribute::make( get: fn (): ?CarbonInterface => is_string($this->{$this->getKeyName()}) - ? CarbonImmutable::instance(UuidV7::fromString($this->{$this->getKeyName()})->getDateTime()) + ? CarbonImmutable::instance(UuidHelper::toDateTime(UuidHelper::fromString($this->{$this->getKeyName()}))) : null, ); } diff --git a/database/factories/PickupExceptionFactory.php b/database/factories/PickupExceptionFactory.php index e28f9969..eb8944d2 100644 --- a/database/factories/PickupExceptionFactory.php +++ b/database/factories/PickupExceptionFactory.php @@ -7,7 +7,7 @@ namespace Database\Factories; use App\Models\PickupException; use Domain\Enums\RepeatFrequency; use Illuminate\Database\Eloquent\Factories\Factory; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; /** * @extends Factory @@ -29,7 +29,7 @@ class PickupExceptionFactory extends Factory public function definition(): array { return [ - 'id' => (string) Uuid::uuid7(), + 'id' => (string) UuidHelper::v7(), 'date' => fake()->date(), 'label' => fake()->streetAddress(), 'repeatable' => fake()->boolean(), diff --git a/database/factories/ShopFactory.php b/database/factories/ShopFactory.php index 48e6c0b6..b3612b19 100644 --- a/database/factories/ShopFactory.php +++ b/database/factories/ShopFactory.php @@ -6,7 +6,7 @@ namespace Database\Factories; use App\Models\Shop; use Illuminate\Database\Eloquent\Factories\Factory; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; /** * @extends Factory @@ -28,7 +28,7 @@ class ShopFactory extends Factory public function definition(): array { return [ - 'id' => (string) Uuid::uuid7(), + 'id' => (string) UuidHelper::v7(), 'name' => fake()->company(), 'address' => fake()->streetAddress(), 'postcode' => fake()->postcode(), diff --git a/domain/Models/ValueObjects/OrderReference.php b/domain/Models/ValueObjects/OrderReference.php index 59b6edc1..fe849e09 100644 --- a/domain/Models/ValueObjects/OrderReference.php +++ b/domain/Models/ValueObjects/OrderReference.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace Domain\Models\ValueObjects; -use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; use Shared\Exceptions\InvalidUuidException; use Shared\Helpers\UuidHelper; @@ -22,7 +21,7 @@ final readonly class OrderReference implements \Stringable public static function fromString(string $value): self { if (UuidHelper::isValid($value)) { - return new self(Uuid::fromString($value)); + return new self(UuidHelper::fromString($value)); } return self::fromBase58($value); diff --git a/domain/Services/OrderService.php b/domain/Services/OrderService.php index a1016e05..401b356c 100644 --- a/domain/Services/OrderService.php +++ b/domain/Services/OrderService.php @@ -12,7 +12,7 @@ use Domain\Models\ValueObjects\Entities\OrderId; use Domain\Models\ValueObjects\OrderReference; use Domain\Models\ValueObjects\PickupTimeSlot; use Domain\Ports\Repositories\OrderRepository; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; class OrderService { @@ -55,12 +55,12 @@ class OrderService private function newOrderId(): OrderId { - return new OrderId(Uuid::uuid7()); + return new OrderId(UuidHelper::v7()); } private function newReference(): OrderReference { - return new OrderReference(Uuid::uuid7()); + return new OrderReference(UuidHelper::v7()); } public function validateOrder(OrderId $id): Order diff --git a/infra/Adapters/Repositories/EloquentOrderRepository.php b/infra/Adapters/Repositories/EloquentOrderRepository.php index d5494464..23d3c094 100644 --- a/infra/Adapters/Repositories/EloquentOrderRepository.php +++ b/infra/Adapters/Repositories/EloquentOrderRepository.php @@ -16,7 +16,7 @@ use Domain\Models\ValueObjects\OrderLine as DomainOrderLine; use Domain\Models\ValueObjects\PickupTimeSlot; use Domain\Ports\Repositories\OrderRepository; use Illuminate\Support\Carbon; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; class EloquentOrderRepository implements OrderRepository { @@ -67,7 +67,7 @@ class EloquentOrderRepository implements OrderRepository ->all(); return array_map( - static fn (string $id): OrderId => new OrderId(Uuid::fromString($id)), + static fn (string $id): OrderId => new OrderId(UuidHelper::fromString($id)), $ids, ); } @@ -169,7 +169,7 @@ class EloquentOrderRepository implements OrderRepository return new DomainOrder( id: $model->getId(), - shopId: new ShopId(Uuid::fromString((string) $model->shop_id)), + shopId: new ShopId(UuidHelper::fromString((string) $model->shop_id)), reference: $model->reference, employee: clone $model->employee, deliveryAddress: clone $model->delivery_address, diff --git a/infra/Adapters/Repositories/EloquentProductRepository.php b/infra/Adapters/Repositories/EloquentProductRepository.php index 155ec077..b1aaafee 100644 --- a/infra/Adapters/Repositories/EloquentProductRepository.php +++ b/infra/Adapters/Repositories/EloquentProductRepository.php @@ -14,7 +14,7 @@ use Domain\Models\ValueObjects\Entities\ProductId; use Domain\Models\ValueObjects\Slug; use Domain\Ports\Repositories\ProductRepository; use Illuminate\Support\Carbon; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; class EloquentProductRepository implements ProductRepository { @@ -139,7 +139,7 @@ class EloquentProductRepository implements ProductRepository public function toEntity(Product $model): DomainProduct { return new DomainProduct( - id: new ProductId(Uuid::fromString($model->id)), + id: new ProductId(UuidHelper::fromString($model->id)), price: $model->price, tax_rate: $model->tax_rate, product_weight: $model->product_weight ? clone $model->product_weight : null, diff --git a/infra/Adapters/Serializers/BasketSerializer.php b/infra/Adapters/Serializers/BasketSerializer.php index d90c5648..16a9121c 100644 --- a/infra/Adapters/Serializers/BasketSerializer.php +++ b/infra/Adapters/Serializers/BasketSerializer.php @@ -16,7 +16,7 @@ use Domain\Models\ValueObjects\IncoId; use Illuminate\Support\Arr; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; @@ -67,7 +67,7 @@ class BasketSerializer } return new Basket( - id: new BasketId(Uuid::fromString($basketId)), + id: new BasketId(UuidHelper::fromString($basketId)), items: $hydratedItems ); } @@ -88,7 +88,7 @@ class BasketSerializer } return new BasketProduct( - id: new ProductId(Uuid::fromString($id)), + id: new ProductId(UuidHelper::fromString($id)), name: Arr::string($itemData, 'name'), qty: Arr::integer($itemData, 'qty'), unitPriceHt: $this->hydrateMoney($id, 'unitPriceHt', Arr::array($itemData, 'unitPriceHt')), diff --git a/infra/Adapters/Services/AppSessionService.php b/infra/Adapters/Services/AppSessionService.php index 1d7cac70..9cb9adb8 100644 --- a/infra/Adapters/Services/AppSessionService.php +++ b/infra/Adapters/Services/AppSessionService.php @@ -7,7 +7,7 @@ namespace Infrastructure\Adapters\Services; use Domain\Models\ValueObjects\SessionId; use Domain\Ports\Services\SessionService; use Illuminate\Support\Facades\Session; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; class AppSessionService implements SessionService { @@ -19,12 +19,12 @@ class AppSessionService implements SessionService public function get(): SessionId { if (! Session::has($this->sessionKey)) { - Session::put($this->sessionKey, Uuid::uuid7()->toString()); + Session::put($this->sessionKey, UuidHelper::v7()->toString()); } /** @var string $uuidString */ $uuidString = Session::get($this->sessionKey); - return new SessionId(Uuid::fromString($uuidString)); + return new SessionId(UuidHelper::fromString($uuidString)); } } From d9edcd7f6b4d4e2ca8b59c6f841b99cf7e58bc20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Tue, 17 Nov 2026 12:15:39 +0100 Subject: [PATCH 178/183] test(uuid): migrate test suite to UuidHelper and add missing describe blocks --- .../Controllers/Bo/OrdersControllerTest.php | 54 +-- .../Fo/Ajax/BasketControllerTest.php | 8 +- .../Fo/Ajax/PickupControllerTest.php | 6 +- .../Fo/Ajax/ProductsControllerTest.php | 6 +- .../Fo/Auth/LoginControllerTest.php | 4 +- .../Fo/Auth/RegisterControllerTest.php | 6 +- .../Fo/Customers/CustomerControllerTest.php | 16 +- .../Fo/Customers/OrderControllerTest.php | 30 +- .../Fo/Customers/PasswordControllerTest.php | 6 +- .../Fo/NewsletterControllerTest.php | 4 +- .../Fo/Pages/ContactControllerTest.php | 4 +- .../Fo/Pages/HomeControllerTest.php | 10 +- .../Fo/ProductCharacterizationTest.php | 4 +- .../Controllers/Fo/TunnelControllerTest.php | 78 +-- .../Requests/Basket/AddBasketRequestTest.php | 18 +- .../Basket/RemoveBasketRequestTest.php | 6 +- .../Bo/Shops/IndexShopRequestTest.php | 10 +- .../Requests/Fo/Auth/RegisterRequestTest.php | 4 +- .../Requests/Fo/ContactFormRequestTest.php | 6 +- .../Fo/Orders/ConfirmOrderRequestTest.php | 4 +- .../Fo/Orders/PickTimeSlotRequestTest.php | 8 +- .../Fo/Orders/ValidateSummaryRequestTest.php | 8 +- .../Fo/UnsubscribeNewsletterRequestTest.php | 6 +- .../Jobs/SendMissingOrderReminderJobTest.php | 10 +- .../Feature/App/Jobs/SendReminderMailTest.php | 10 +- .../Orders/SendAdminOrderConfirmationTest.php | 6 +- .../SendCustomerOrderConfirmationTest.php | 6 +- .../Listeners/UpdateCustomerLastLoginTest.php | 44 +- .../SessionBasketRepositoryTest.php | 12 +- .../SessionOrderBuilderManagerTest.php | 14 +- .../App/Casts/OrderLineProductCastTest.php | 8 +- .../App/Casts/OrderReferenceCastTest.php | 159 +++--- .../Cqs/Actions/Basket/AddToBasketTest.php | 6 +- .../Cqs/Actions/Basket/EmptyBasketTest.php | 6 +- .../Actions/Basket/RemoveFromBasketTest.php | 6 +- .../Actions/Contact/SubmitContactFormTest.php | 4 +- .../Crm/UnsubscribeFromNewsletterTest.php | 8 +- .../Crm/UpdateCustomerPasswordTest.php | 8 +- .../Cqs/Actions/Crm/UpdateCustomerTest.php | 8 +- .../Customers/RegisterCustomerTest.php | 10 +- .../Customers/UpdateCustomerLastLoginTest.php | 4 +- .../Actions/Orders/ApplyPickTimeSlotTest.php | 8 +- .../Cqs/Actions/Orders/CancelOrderTest.php | 8 +- .../Orders/ClaimTodayOrderReminderTest.php | 6 +- .../Orders/FailStalePendingOrdersTest.php | 18 +- .../Orders/InitializeOrderTunnelTest.php | 10 +- .../Actions/Orders/PlacePendingOrderTest.php | 12 +- .../Orders/ReleaseTodayOrderReminderTest.php | 6 +- .../Cqs/Queries/Basket/GetBasketQueryTest.php | 10 +- .../Customers/GetCustomerByEmailQueryTest.php | 4 +- .../Orders/GetBoPaginatedOrdersQueryTest.php | 6 +- .../Orders/GetBoTodayOrdersQueryTest.php | 4 +- .../GetFoCustomerPaginatedOrdersQueryTest.php | 6 +- .../GetTunnelOrderConfirmedQueryTest.php | 6 +- .../GetProductIncoForEditQueryTest.php | 4 +- .../GetProductWithPricingQueryTest.php | 6 +- .../GetAvailableTimeslotsQueryTest.php | 8 +- .../WithApp/App/Dto/OrderLineDtoTest.php | 8 +- .../WithApp/App/Models/ProductTest.php | 4 +- .../WithApp/App/Services/CrmServiceTest.php | 22 +- .../App/Services/MailRegateServiceTest.php | 6 +- .../Services/OrderOwnershipServiceTest.php | 26 +- .../WithApp/App/Services/StatsServiceTest.php | 24 +- .../Directories/EloquentShopDirectoryTest.php | 110 ++--- .../EloquentOrderRepositoryTest.php | 274 +++++------ .../EloquentPickupExceptionRepositoryTest.php | 200 ++++---- .../EloquentProductRepositoryTest.php | 454 +++++++++--------- .../EloquentShopRepositoryTest.php | 348 +++++++------- .../EloquentShopperRepositoryTest.php | 310 ++++++------ .../SessionBasketRepositoryTest.php | 12 +- .../Services/AppCustomerAuthServiceTest.php | 14 +- .../Services/AppSessionServiceTest.php | 3 +- ...atabaseTunnelAttemptTrackerServiceTest.php | 28 +- .../EloquentEmployeeStatisticsServiceTest.php | 188 ++++---- .../Actions/Orders/ApplyPickTimeSlotTest.php | 10 +- .../Cqs/Actions/Orders/CancelOrderTest.php | 6 +- .../Actions/Orders/PlacePendingOrderTest.php | 20 +- .../AssociateProductIncoInputTest.php | 6 +- .../Orders/GetBasketSummaryQueryTest.php | 4 +- .../Orders/GetOrderConfirmationQueryTest.php | 10 +- .../Orders/GetPickTimeSlotQueryTest.php | 6 +- tests/Unit/App/Dto/ShopDtoTest.php | 4 +- .../Orders/EmptyBasketOnOrderPlacedTest.php | 8 +- ...validateOrderBuilderOnBasketChangeTest.php | 6 +- .../Policies/Backend/ProductPolicyTest.php | 10 +- .../Policies/Frontend/BasketPolicyTest.php | 4 +- .../Unit/Domain/Builders/OrderBuilderTest.php | 20 +- .../Events/AnOrderHasBeenPlacedTest.php | 10 +- .../Events/BasketHasBeenModifiedTest.php | 4 +- .../Unit/Domain/Events/BasketRemovedTest.php | 4 +- tests/Unit/Domain/Events/DtoTest.php | 4 +- .../Domain/Models/Entities/BasketTest.php | 42 +- .../Unit/Domain/Models/Entities/OrderTest.php | 34 +- .../Entities/PickupExceptionOnDateTest.php | 8 +- .../Domain/Models/Entities/ProductTest.php | 6 +- .../Unit/Domain/Models/Entities/ShopTest.php | 12 +- .../Domain/Models/Entities/ShopperTest.php | 24 +- .../Models/ValueObjects/BasketProductTest.php | 6 +- .../ValueObjects/ContactFormDataTest.php | 4 +- .../EditablePickupExceptionForShopTest.php | 4 +- .../ValueObjects/Entities/BasketIdTest.php | 6 +- .../ValueObjects/Entities/OrderIdTest.php | 6 +- .../Entities/PickupExceptionIdTest.php | 6 +- .../ValueObjects/Entities/ProductIdTest.php | 6 +- .../ValueObjects/Entities/ShopIdTest.php | 6 +- .../ValueObjects/Entities/ShopperIdTest.php | 6 +- .../ValueObjects/OrderLineProductTest.php | 16 +- .../Models/ValueObjects/OrderLineTest.php | 4 +- .../ValueObjects/OrderReferenceTest.php | 13 +- .../Models/ValueObjects/SessionIdTest.php | 6 +- .../ValueObjects/ShopPickupOverrideTest.php | 8 +- .../Domain/Services/BasketServiceTest.php | 40 +- .../Unit/Domain/Services/OrderServiceTest.php | 37 +- .../Services/OrderTunnelServiceTest.php | 63 +-- .../Services/PickupSchedulingServiceTest.php | 10 +- .../Domain/Services/ShopperServiceTest.php | 30 +- .../Serializers/BasketSerializerTest.php | 332 ++++++------- 117 files changed, 1838 insertions(+), 1821 deletions(-) diff --git a/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php index ae7a39b8..b2d9076b 100644 --- a/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php @@ -29,7 +29,7 @@ use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Date; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use function Pest\Laravel\get; @@ -57,9 +57,9 @@ describe('Bo\OrdersController', function (): void { // GIVEN $shop = Shop::factory()->create(['name' => 'Boutique Test']); Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(2500, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -91,9 +91,9 @@ describe('Bo\OrdersController', function (): void { $shop = Shop::factory()->create(['name' => 'Boutique Pagination']); for ($i = 0; $i < 30; $i++) { Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(2500, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -123,12 +123,12 @@ describe('Bo\OrdersController', function (): void { it('can filter index by search term', function (): void { /** @var \Tests\TestCase $this */ // GIVEN - $refUuid = Uuid::uuid7(); + $refUuid = UuidHelper::v7(); $reference = new OrderReference($refUuid); $ref = (string) $reference; $shop = Shop::factory()->create(['name' => 'UniqueShopSearch']); Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, 'reference' => $reference, 'status' => OrderStatus::VALIDATED->value, @@ -163,9 +163,9 @@ describe('Bo\OrdersController', function (): void { // GIVEN $shop = Shop::factory()->create(); $olderOrder = Order::query()->forceCreate([ - 'id' => Uuid::uuid7(Date::now()->subHours(2))->toString(), + 'id' => UuidHelper::v7(Date::now()->subHours(2))->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(1000, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -180,9 +180,9 @@ describe('Bo\OrdersController', function (): void { 'pickup_day' => Date::now()->addDays(7)->toDateString(), ]); $newerOrder = Order::query()->forceCreate([ - 'id' => Uuid::uuid7(Date::now())->toString(), + 'id' => UuidHelper::v7(Date::now())->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(2000, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -213,9 +213,9 @@ describe('Bo\OrdersController', function (): void { // GIVEN $shop = Shop::factory()->create(); $todayOrder = Order::query()->forceCreate([ - 'id' => Uuid::uuid7(Date::now())->toString(), + 'id' => UuidHelper::v7(Date::now())->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(3000, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -230,9 +230,9 @@ describe('Bo\OrdersController', function (): void { 'pickup_day' => Date::now()->addDays(7)->toDateString(), ]); $pastOrder = Order::query()->forceCreate([ - 'id' => Uuid::uuid7(Date::now()->subDays(3))->toString(), + 'id' => UuidHelper::v7(Date::now()->subDays(3))->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(4000, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -264,8 +264,8 @@ describe('Bo\OrdersController', function (): void { // GIVEN $shop = Shop::factory()->create(); $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('customer@example.com'), ]); Employee::query()->forceCreate([ @@ -287,9 +287,9 @@ describe('Bo\OrdersController', function (): void { App::instance(CrmService::class, $crmMock); $order = Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(4000, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -318,9 +318,9 @@ describe('Bo\OrdersController', function (): void { // GIVEN $shop = Shop::factory()->create(); $order = Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(2000, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -364,9 +364,9 @@ describe('Bo\OrdersController', function (): void { // GIVEN $shop = Shop::factory()->create(); $order = Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::CANCELED->value, 'total' => new Money(2000, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -392,9 +392,9 @@ describe('Bo\OrdersController', function (): void { // GIVEN $shop = Shop::factory()->create(); $validated = Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(2500, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -409,9 +409,9 @@ describe('Bo\OrdersController', function (): void { 'pickup_day' => Date::now()->toDateString(), ]); $failed = Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::FAILED->value, 'total' => new Money(1500, new Currency('EUR')), 'employee' => new OrderEmployee( diff --git a/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php index 5f4034d0..421dbed1 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php @@ -29,7 +29,7 @@ use Infrastructure\Adapters\Repositories\SessionBasketRepository; use Infrastructure\Adapters\Serializers\BasketSerializer; use Infrastructure\Adapters\Services\AppSessionService; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('BasketController', function () { it('can access post /ajax/basket/add', function () { @@ -111,9 +111,9 @@ describe('BasketController', function () { Cache::flush(); $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'email' => new Email('basket-nplusone@example.com'), - 'hashcode' => Uuid::uuid4()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), ]); $range = new Range(); @@ -156,7 +156,7 @@ describe('BasketController', function () { $product->save(); $basket->addOrUpdate(new BasketProduct( - id: new ProductId(Uuid::fromString((string) $product->id)), + id: new ProductId(UuidHelper::fromString((string) $product->id)), name: $product->name, qty: 1, unitPriceHt: Money::EUR(1000), diff --git a/tests/Feature/App/Http/Controllers/Fo/Ajax/PickupControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Ajax/PickupControllerTest.php index 5691618f..27a0feaf 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Ajax/PickupControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Ajax/PickupControllerTest.php @@ -13,7 +13,7 @@ use Database\Seeders\ContentSeeder; use Domain\Models\ValueObjects\Email; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\View; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('PickupController', function (): void { @@ -46,7 +46,7 @@ describe('PickupController', function (): void { $customer = new Customer(); $customer->email = new Email('employee@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); $this->withoutMiddleware([ @@ -74,7 +74,7 @@ describe('PickupController', function (): void { $shop = Shop::factory()->create(); $customer = new Customer(); $customer->email = new Email('employee2@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); $this->withoutMiddleware([ diff --git a/tests/Feature/App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php index 4cf2759c..2a1d9726 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php @@ -21,7 +21,7 @@ use Domain\Models\ValueObjects\Email; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\View; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('ProductsController (Ajax)', function () { @@ -79,7 +79,7 @@ describe('ProductsController (Ajax)', function () { Cache::flush(); $customer = new Customer(); $customer->email = new Email('test1@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -143,7 +143,7 @@ describe('ProductsController (Ajax)', function () { Cache::flush(); $customer = new Customer(); $customer->email = new Email('test2@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php index 362b5d67..2c910148 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php @@ -28,7 +28,7 @@ use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\View; use Illuminate\Support\Str; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('LoginController', function () { @@ -119,7 +119,7 @@ describe('LoginController', function () { Cache::flush(); $user = \Mockery::mock(Customer::class)->makePartial(); $user->shouldReceive('getAuthIdentifier')->andReturn(1); - $user->hashcode = new CrmHashcode(Uuid::uuid4()); + $user->hashcode = new CrmHashcode(UuidHelper::v4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php index a4fd68bd..a74e74b6 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php @@ -24,7 +24,7 @@ use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\View; use Illuminate\Support\ViewErrorBag; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; use Webmozart\Assert\Assert; @@ -67,7 +67,7 @@ describe('RegisterController', function () { /** @var \Tests\TestCase $this */ // GIVEN $customer = new Customer(['email' => new Email('existing@example.com')]); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->saveOrFail(); $employee = new Employee(); @@ -105,7 +105,7 @@ describe('RegisterController', function () { /** @var \Tests\TestCase $this */ // GIVEN $customer = new Customer(['email' => new Email('john.doe@example.com')]); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->saveOrFail(); $input = new RegisterCustomerInput( diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php index e34efc43..d76df87d 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php @@ -20,7 +20,7 @@ use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\View; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('CustomerController', function () { @@ -48,7 +48,7 @@ describe('CustomerController', function () { Cache::flush(); $user = \Mockery::mock(Customer::class)->makePartial(); $user->shouldReceive('getAuthIdentifier')->andReturn(1); - $user->hashcode = new CrmHashcode(Uuid::uuid4()); + $user->hashcode = new CrmHashcode(UuidHelper::v4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); $crmMock = \Mockery::mock(CrmService::class)->makePartial(); @@ -73,7 +73,7 @@ describe('CustomerController', function () { Cache::flush(); $user = \Mockery::mock(Customer::class)->makePartial(); $user->shouldReceive('getAuthIdentifier')->andReturn(1); - $user->hashcode = new CrmHashcode(Uuid::uuid4()); + $user->hashcode = new CrmHashcode(UuidHelper::v4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); $crmMock = \Mockery::mock(CrmService::class)->makePartial(); @@ -98,7 +98,7 @@ describe('CustomerController', function () { Cache::flush(); $user = \Mockery::mock(Customer::class)->makePartial(); $user->shouldReceive('getAuthIdentifier')->andReturn(1); - $user->hashcode = new CrmHashcode(Uuid::uuid4()); + $user->hashcode = new CrmHashcode(UuidHelper::v4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); $crmMock = \Mockery::mock(CrmService::class)->makePartial(); @@ -122,9 +122,9 @@ describe('CustomerController', function () { ])); Cache::flush(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'hashcode' => $hashcode->value, 'email' => new Email('jean.dupont@example.com'), ]); @@ -188,9 +188,9 @@ describe('CustomerController', function () { ])); Cache::flush(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'hashcode' => $hashcode->value, 'email' => new Email('jean.dupont@example.com'), ]); diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php index 8ad770de..aba25ed8 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/OrderControllerTest.php @@ -33,7 +33,7 @@ use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\View; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('OrderController', function () { @@ -61,7 +61,7 @@ describe('OrderController', function () { Cache::flush(); $user = \Mockery::mock(Customer::class)->makePartial(); $user->shouldReceive('getAuthIdentifier')->andReturn(1); - $user->hashcode = new CrmHashcode(Uuid::uuid4()); + $user->hashcode = new CrmHashcode(UuidHelper::v4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); $crmMock = \Mockery::mock(CrmService::class)->makePartial(); @@ -86,7 +86,7 @@ describe('OrderController', function () { Cache::flush(); $user = \Mockery::mock(Customer::class)->makePartial(); $user->shouldReceive('getAuthIdentifier')->andReturn(1); - $user->hashcode = new CrmHashcode(Uuid::uuid4()); + $user->hashcode = new CrmHashcode(UuidHelper::v4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); $crmMock = \Mockery::mock(CrmService::class)->makePartial(); @@ -110,9 +110,9 @@ describe('OrderController', function () { ])); Cache::flush(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'hashcode' => $hashcode->value, 'email' => new Email('verified@example.com'), ]); @@ -132,11 +132,11 @@ describe('OrderController', function () { ]); $shop = Shop::factory()->create(); - $refUuid = Uuid::uuid7(); + $refUuid = UuidHelper::v7(); $reference = new OrderReference($refUuid); $ref = (string) $reference; Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, 'reference' => $reference, 'status' => OrderStatus::VALIDATED->value, @@ -207,9 +207,9 @@ describe('OrderController', function () { ])); Cache::flush(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'hashcode' => $hashcode->value, 'email' => new Email('verified_show@example.com'), ]); @@ -229,11 +229,11 @@ describe('OrderController', function () { ]); $shop = Shop::factory()->create(); - $refUuid = Uuid::uuid7(); + $refUuid = UuidHelper::v7(); $reference = new OrderReference($refUuid); $ref = (string) $reference; $order = Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, 'reference' => $reference, 'status' => OrderStatus::VALIDATED->value, @@ -294,9 +294,9 @@ describe('OrderController', function () { ])); Cache::flush(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'hashcode' => $hashcode->value, 'email' => new Email('tech-order-' . $status->value . '@example.com'), ]); @@ -315,9 +315,9 @@ describe('OrderController', function () { ]); $shop = Shop::factory()->create(); - $reference = new OrderReference(Uuid::uuid7()); + $reference = new OrderReference(UuidHelper::v7()); Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, 'reference' => $reference, 'status' => $status->value, diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/PasswordControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/PasswordControllerTest.php index b827e731..0754aa5a 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/PasswordControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/PasswordControllerTest.php @@ -11,7 +11,7 @@ use Database\Seeders\ContentSeeder; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\View; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('PasswordController', function () { @@ -26,7 +26,7 @@ describe('PasswordController', function () { Cache::flush(); $user = \Mockery::mock(Customer::class)->makePartial(); $user->shouldReceive('getAuthIdentifier')->andReturn(1); - $user->hashcode = new CrmHashcode(Uuid::uuid4()); + $user->hashcode = new CrmHashcode(UuidHelper::v4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); $crmMock = \Mockery::mock(CrmService::class)->makePartial(); @@ -51,7 +51,7 @@ describe('PasswordController', function () { Cache::flush(); $user = \Mockery::mock(Customer::class)->makePartial(); $user->shouldReceive('getAuthIdentifier')->andReturn(1); - $user->hashcode = new CrmHashcode(Uuid::uuid4()); + $user->hashcode = new CrmHashcode(UuidHelper::v4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); $crmMock = \Mockery::mock(CrmService::class)->makePartial(); diff --git a/tests/Feature/App/Http/Controllers/Fo/NewsletterControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/NewsletterControllerTest.php index 73822b80..ddd8d185 100644 --- a/tests/Feature/App/Http/Controllers/Fo/NewsletterControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/NewsletterControllerTest.php @@ -9,7 +9,7 @@ use App\Services\CrmService; use Database\Seeders\ContentSeeder; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\View; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('NewsletterController', function () { it('can access get /unsubscribe with valid hashcode', function () { @@ -23,7 +23,7 @@ describe('NewsletterController', function () { $page->slug->value() => $page, ])); Cache::flush(); - $hashcode = Uuid::uuid4()->toString(); + $hashcode = UuidHelper::v4()->toString(); // WHEN $response = $this->get('/unsubscribe?hashcode=' . $hashcode); diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php index e5338af3..66d40e5d 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php @@ -17,7 +17,7 @@ use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\View; use Mockery\MockInterface; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Uwil\Storage\Contracts\StorageService; use Uwil\Storage\Lib\ValueObjects\DiskName; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; @@ -81,7 +81,7 @@ describe('ContactController', function (): void { 'last_name' => 'Dupont', 'email' => 'jean.dupont@gmail.com', 'subject' => 'Question', - 'order_ref' => (string) new OrderReference(Uuid::uuid7()), + 'order_ref' => (string) new OrderReference(UuidHelper::v7()), 'message' => 'Bonjour, ceci est un message de test qui contient au moins vingt caractères.', 'ok_cgv' => '1', ]; diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php index 4fe02123..f3bd4030 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php @@ -21,7 +21,7 @@ use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\View; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('HomeController', function () { @@ -84,7 +84,7 @@ describe('HomeController', function () { $slide->save(); $product = new Product(); - $product->id = (string) Uuid::uuid7(); + $product->id = (string) UuidHelper::v7(); $product->name = 'Poulet Fermier'; $product->brand = ProductBrand::loue; $product->slug = 'poulet-fermier'; @@ -171,7 +171,7 @@ describe('HomeController', function () { $discount->save(); $promoProduct = new Product(); - $promoProduct->id = (string) Uuid::uuid7(); + $promoProduct->id = (string) UuidHelper::v7(); $promoProduct->name = 'Foie Gras Promo'; $promoProduct->brand = ProductBrand::loue; $promoProduct->slug = 'foie-gras-promo'; @@ -193,7 +193,7 @@ describe('HomeController', function () { $promoProduct->save(); $regularProduct = new Product(); - $regularProduct->id = (string) Uuid::uuid7(); + $regularProduct->id = (string) UuidHelper::v7(); $regularProduct->name = 'Poulet Standard'; $regularProduct->brand = ProductBrand::loue; $regularProduct->slug = 'poulet-standard'; @@ -246,7 +246,7 @@ describe('HomeController', function () { $range->save(); $product = new Product(); - $product->id = (string) Uuid::uuid7(); + $product->id = (string) UuidHelper::v7(); $product->name = 'Poulet Sûr'; $product->brand = ProductBrand::loue; $product->slug = 'poulet-sur'; diff --git a/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php b/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php index 2b6cb007..d90bc829 100644 --- a/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php @@ -28,7 +28,7 @@ use Domain\Models\ValueObjects\Email; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\View; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; use Tests\TestCase; use Webmozart\Assert\Assert; @@ -53,7 +53,7 @@ function characterizationCustomer(string $email): Customer { $customer = new Customer(); $customer->email = new Email($email); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); return $customer; diff --git a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php index a5ed75fb..11202ec6 100644 --- a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php @@ -83,8 +83,8 @@ use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\View; use Mockery\MockInterface; use Money\Money; -use Ramsey\Uuid\Uuid; use Sentry\State\HubInterface; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('TunnelController', function (): void { @@ -219,7 +219,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('test@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -229,7 +229,7 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); - $basket = new Basket(new BasketId(Uuid::uuid7())); + $basket = new Basket(new BasketId(UuidHelper::v7())); $this->mock(Executor::class, function (MockInterface $mock) use ($basket): void { $mock->shouldReceive('execute') ->once() @@ -261,7 +261,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('test@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -295,7 +295,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('test@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -351,7 +351,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('test@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -376,7 +376,7 @@ describe('TunnelController', function (): void { $this->mock(ShopperRepository::class, function (MockInterface $mock) use ($shopper): void { $mock->shouldReceive('getByIdOrFail')->andReturn($shopper); }); - $basket = new Basket(new BasketId(Uuid::uuid7())); + $basket = new Basket(new BasketId(UuidHelper::v7())); $builder = \Mockery::mock(OrderBuilderWithBasket::class); $builder->shouldReceive('getBasket')->andReturn($basket); $this->mock(OrderTunnelService::class, function (MockInterface $mock) use ($builder): void { @@ -412,7 +412,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('test@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -437,7 +437,7 @@ describe('TunnelController', function (): void { $this->mock(ShopperRepository::class, function (MockInterface $mock) use ($shopper): void { $mock->shouldReceive('getByIdOrFail')->andReturn($shopper); }); - $basket = new Basket(new BasketId(Uuid::uuid7())); + $basket = new Basket(new BasketId(UuidHelper::v7())); $builder = \Mockery::mock(OrderBuilderWithBasket::class); $builder->shouldReceive('getBasket')->andReturn($basket); $this->mock(OrderTunnelService::class, function (MockInterface $mock) use ($builder): void { @@ -473,7 +473,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('test@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -483,7 +483,7 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); - $basket = new Basket(new BasketId(Uuid::uuid7())); + $basket = new Basket(new BasketId(UuidHelper::v7())); $builder = \Mockery::mock(OrderBuilderCompleted::class); $slot = new PickupTimeSlot(now(), new \DateInterval('PT1H')); $builder->shouldReceive('getPickupTimeSlot')->andReturn($slot); @@ -534,7 +534,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('test@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -544,8 +544,8 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); - $orderId = new OrderId(Uuid::uuid7()); - $orderReference = new OrderReference(Uuid::uuid7()); + $orderId = new OrderId(UuidHelper::v7()); + $orderReference = new OrderReference(UuidHelper::v7()); $this->mock(Executor::class, function (MockInterface $mock) use ($orderId, $orderReference): void { $mock->shouldReceive('execute') ->once() @@ -582,7 +582,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('regate-export-fail@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -592,8 +592,8 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); - $orderId = new OrderId(Uuid::uuid7()); - $orderReference = new OrderReference(Uuid::uuid7()); + $orderId = new OrderId(UuidHelper::v7()); + $orderReference = new OrderReference(UuidHelper::v7()); $this->mock(Executor::class, function (MockInterface $mock) use ($orderId, $orderReference): void { $mock->shouldReceive('execute') ->once() @@ -631,7 +631,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('confirm-sql-fail@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -641,8 +641,8 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); - $orderId = new OrderId(Uuid::uuid7()); - $orderReference = new OrderReference(Uuid::uuid7()); + $orderId = new OrderId(UuidHelper::v7()); + $orderReference = new OrderReference(UuidHelper::v7()); $this->mock(Executor::class, function (MockInterface $mock) use ($orderId, $orderReference): void { $mock->shouldReceive('execute') ->once() @@ -680,7 +680,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('test@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -720,7 +720,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('test@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -760,7 +760,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('test@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -802,7 +802,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('test@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -844,7 +844,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('test@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -882,7 +882,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('test-inactive@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -921,7 +921,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('test@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -939,7 +939,7 @@ describe('TunnelController', function (): void { $shop->default = true; $shop->save(); - $orderReference = new OrderReference(Uuid::uuid7()); + $orderReference = new OrderReference(UuidHelper::v7()); $order = new Order(); $order->reference = $orderReference; $order->total = Money::EUR(3000); @@ -986,7 +986,7 @@ describe('TunnelController', function (): void { $customer = new Customer(); $customer->email = new Email('regate-fail@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $this->actingAs($customer, 'frontend'); @@ -1039,10 +1039,10 @@ describe('TunnelController', function (): void { ])); Cache::flush(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); /** @var Customer $customer */ $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'email' => new Email('e2e-success@example.com'), 'hashcode' => $hashcode, ]); @@ -1179,10 +1179,10 @@ describe('TunnelController', function (): void { ])); Cache::flush(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); /** @var Customer $customer */ $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'email' => new Email('e2e-fail@example.com'), 'hashcode' => $hashcode, ]); @@ -1332,10 +1332,10 @@ describe('TunnelController', function (): void { ])); Cache::flush(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); /** @var Customer $customer */ $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'email' => new Email('e2e-lock@example.com'), 'hashcode' => $hashcode, ]); @@ -1473,10 +1473,10 @@ describe('TunnelController', function (): void { ])); Cache::flush(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); /** @var Customer $customer */ $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'email' => new Email('e2e-attempt@example.com'), 'hashcode' => $hashcode, ]); @@ -1616,10 +1616,10 @@ describe('TunnelController', function (): void { ])); Cache::flush(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); /** @var Customer $customer */ $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'email' => new Email('e2e-attempt-ko@example.com'), 'hashcode' => $hashcode, ]); diff --git a/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php b/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php index 9f4dd9b1..2b6698ae 100644 --- a/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php +++ b/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php @@ -22,8 +22,8 @@ use Infrastructure\Adapters\Repositories\EloquentProductRepository; use Money\Currency; use Money\Money; use Psr\Log\NullLogger; -use Ramsey\Uuid\Uuid; use Shared\Concurrency\Lock; +use Shared\Helpers\UuidHelper; function makeAddBasketRequest(): AddBasketRequest { @@ -50,9 +50,9 @@ describe('AddBasketRequest', function () { 'picture_title' => '', ]); $product = Product::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'name' => 'Test', - 'slug' => Uuid::uuid7()->toString(), + 'slug' => UuidHelper::v7()->toString(), 'brand' => ProductBrand::cases()[0]->value, 'description' => 'Test', 'price' => new Money(100, new Currency('EUR')), @@ -90,7 +90,7 @@ describe('AddBasketRequest', function () { $request->initialize(); // WHEN - $request->merge(['rowId' => Uuid::uuid7()->toString()]); + $request->merge(['rowId' => UuidHelper::v7()->toString()]); // THEN expect($request->authorize())->toBeFalse(); @@ -106,9 +106,9 @@ describe('AddBasketRequest', function () { 'picture_title' => '', ]); $product = Product::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'name' => 'Test', - 'slug' => Uuid::uuid7()->toString(), + 'slug' => UuidHelper::v7()->toString(), 'brand' => ProductBrand::cases()[0]->value, 'description' => 'Test', 'price' => new Money(100, new Currency('EUR')), @@ -150,9 +150,9 @@ describe('AddBasketRequest', function () { 'picture_title' => '', ]); $product = Product::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'name' => 'Test', - 'slug' => Uuid::uuid7()->toString(), + 'slug' => UuidHelper::v7()->toString(), 'brand' => ProductBrand::cases()[0]->value, 'description' => 'Test', 'price' => new Money(100, new Currency('EUR')), @@ -203,7 +203,7 @@ describe('AddBasketRequest', function () { it('can get product id as value object', function () { // GIVEN - $uuid = Uuid::uuid7()->toString(); + $uuid = UuidHelper::v7()->toString(); $request = makeAddBasketRequest(); $request->initialize(); $request->merge(['rowId' => $uuid]); diff --git a/tests/Feature/App/Http/Requests/Basket/RemoveBasketRequestTest.php b/tests/Feature/App/Http/Requests/Basket/RemoveBasketRequestTest.php index 269bca07..816a818b 100644 --- a/tests/Feature/App/Http/Requests/Basket/RemoveBasketRequestTest.php +++ b/tests/Feature/App/Http/Requests/Basket/RemoveBasketRequestTest.php @@ -6,7 +6,7 @@ namespace Tests\Feature\App\Http\Requests\Basket; use App\Http\Requests\Basket\RemoveBasketRequest; use Illuminate\Support\Facades\Validator; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('RemoveBasketRequest', function () { it('authorizes always', function () { @@ -25,7 +25,7 @@ describe('RemoveBasketRequest', function () { $request = new RemoveBasketRequest(); $request->initialize(); $request->merge([ - 'rowId' => Uuid::uuid7()->toString(), + 'rowId' => UuidHelper::v7()->toString(), 'qty' => 1, ]); @@ -55,7 +55,7 @@ describe('RemoveBasketRequest', function () { it('can get product id as value object', function () { // GIVEN - $uuid = Uuid::uuid7()->toString(); + $uuid = UuidHelper::v7()->toString(); $request = new RemoveBasketRequest(); $request->initialize(); $request->merge(['rowId' => $uuid]); diff --git a/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php index da332046..317f48d0 100644 --- a/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php @@ -12,7 +12,7 @@ use Illuminate\Session\ArraySessionHandler; use Illuminate\Session\Store; use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppAdminAuthService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use function Pest\Laravel\actingAs; use function Pest\Laravel\get; @@ -42,7 +42,7 @@ describe('IndexShopRequest', function (): void { // WHEN $invalid = Validator::make(['pickup-exception' => 'not-a-uuid'], $rules); - $valid = Validator::make(['pickup-exception' => Uuid::uuid7()->toString()], $rules); + $valid = Validator::make(['pickup-exception' => UuidHelper::v7()->toString()], $rules); // THEN expect($invalid->errors()->has('pickup-exception'))->toBeTrue() @@ -53,7 +53,7 @@ describe('IndexShopRequest', function (): void { // GIVEN $admin = User::factory()->createOne(['role' => UserRole::SuperAdmin]); actingAs($admin, 'backend'); - $uuid = Uuid::uuid7()->toString(); + $uuid = UuidHelper::v7()->toString(); // WHEN $withFilter = get(route('bo.shops.index', ['pickup-exception' => $uuid])); @@ -74,7 +74,7 @@ describe('IndexShopRequest', function (): void { // GIVEN $authService = \Mockery::mock(AppAdminAuthService::class); $session = new Store('test', new ArraySessionHandler(120)); - $uuidV7 = Uuid::uuid7()->toString(); + $uuidV7 = UuidHelper::v7()->toString(); $session->put(IndexShopRequest::SESSION_KEY, $uuidV7); $request = new IndexShopRequest($authService); @@ -90,7 +90,7 @@ describe('IndexShopRequest', function (): void { ->and((string) $request->getPickupExceptionId())->toBe($uuidV7); // GIVEN - $session->put(IndexShopRequest::SESSION_KEY, Uuid::uuid4()->toString()); + $session->put(IndexShopRequest::SESSION_KEY, UuidHelper::v4()->toString()); // WHEN & THEN expect($request->toPickupExceptionId())->toBeNull(); diff --git a/tests/Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php index d11dca6f..193b1083 100644 --- a/tests/Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php @@ -17,7 +17,7 @@ use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppCustomerAuthService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('RegisterRequest', function (): void { @@ -84,7 +84,7 @@ describe('RegisterRequest', function (): void { it('rejects matricule and code when employee already has a customer_id', function (): void { // GIVEN $customer = new Customer(['email' => new Email('existing@example.com')]); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->saveOrFail(); $employee = new Employee(); diff --git a/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php b/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php index 2f28960a..012cb60b 100644 --- a/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php @@ -9,7 +9,7 @@ use Domain\Models\ValueObjects\OrderReference; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('ContactFormRequest', function () { it('validates correct rules', function () { @@ -23,7 +23,7 @@ describe('ContactFormRequest', function () { 'first_name' => 'John', 'email' => 'john.doe@gmail.com', 'subject' => 'Help with my order', - 'order_ref' => (string) new OrderReference(Uuid::uuid7()), + 'order_ref' => (string) new OrderReference(UuidHelper::v7()), 'message' => 'This is a message that is longer than 20 characters.', 'ok_cgv' => true, ]); @@ -108,7 +108,7 @@ describe('ContactFormRequest', function () { it('converts to action input without file', function () { // GIVEN - $orderRef = new OrderReference(Uuid::uuid7()); + $orderRef = new OrderReference(UuidHelper::v7()); $request = new ContactFormRequest(); $request->initialize(); $request->merge([ diff --git a/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php index 2e19b5ee..8851cc76 100644 --- a/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php @@ -9,7 +9,7 @@ use App\Models\Customer; use Domain\Models\ValueObjects\Entities\ShopperId; use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppCustomerAuthService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('ConfirmOrderRequest', function (): void { it('authorizes only when customer auth service returns true', function (): void { @@ -47,7 +47,7 @@ describe('ConfirmOrderRequest', function (): void { it('maps to PlacePendingOrderInput', function (): void { // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); + $shopperId = new ShopperId(UuidHelper::v7()); $customer = new Customer(); $customer->id = $shopperId->value->toString(); diff --git a/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php index eb6b4ab2..9fa17dfa 100644 --- a/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php @@ -23,7 +23,7 @@ use Domain\Ports\Repositories\ShopperRepository; use Domain\Services\OrderTunnelService; use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppCustomerAuthService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; const VALID_TIMESLOT_DATE = '2023-10-15'; @@ -88,11 +88,11 @@ describe('PickTimeSlotRequest', function (): void { it('fails basketTotal validation when weekly limit is exceeded', function (): void { // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); + $shopperId = new ShopperId(UuidHelper::v7()); $customer = new Customer(); $customer->id = $shopperId->value->toString(); - $basket = new Basket(new BasketId(Uuid::uuid7()), []); + $basket = new Basket(new BasketId(UuidHelper::v7()), []); $shopper = new Shopper( $shopperId, new Email('shopper@example.com'), @@ -160,7 +160,7 @@ describe('PickTimeSlotRequest', function (): void { it('maps to ApplyPickTimeSlotInput', function (): void { // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); + $shopperId = new ShopperId(UuidHelper::v7()); $customer = new Customer(); $customer->id = $shopperId->value->toString(); diff --git a/tests/Feature/App/Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php index 621a00f5..1d6e842d 100644 --- a/tests/Feature/App/Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php @@ -14,7 +14,7 @@ use Domain\Services\BasketService; use Domain\Services\OrderTunnelService; use Illuminate\Support\Facades\Validator; use Infrastructure\Adapters\Services\AppCustomerAuthService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('ValidateSummaryRequest', function (): void { it('authorizes only when customer auth service returns true', function (): void { @@ -40,7 +40,7 @@ describe('ValidateSummaryRequest', function (): void { it('fails basketTotal validation when order limit is exceeded', function (): void { // GIVEN - $basket = new Basket(new BasketId(Uuid::uuid7()), []); + $basket = new Basket(new BasketId(UuidHelper::v7()), []); $authService = \Mockery::mock(AppCustomerAuthService::class); $basketService = \Mockery::mock(BasketService::class); @@ -70,11 +70,11 @@ describe('ValidateSummaryRequest', function (): void { it('maps to InitializeOrderTunnelInput', function (): void { // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); + $shopperId = new ShopperId(UuidHelper::v7()); $customer = new Customer(); $customer->id = $shopperId->value->toString(); - $basket = new Basket(new BasketId(Uuid::uuid7()), []); + $basket = new Basket(new BasketId(UuidHelper::v7()), []); $authService = \Mockery::mock(AppCustomerAuthService::class); $authService->shouldReceive('getCustomerAsMandatory')->once()->andReturn($customer); diff --git a/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php b/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php index 8749c31d..1504aaef 100644 --- a/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php @@ -6,7 +6,7 @@ namespace Tests\Feature\App\Http\Requests\Fo; use App\Http\Requests\Fo\UnsubscribeNewsletterRequest; use Illuminate\Support\Facades\Validator; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('UnsubscribeNewsletterRequest', function () { it('validates correct rules', function () { @@ -14,7 +14,7 @@ describe('UnsubscribeNewsletterRequest', function () { $request = new UnsubscribeNewsletterRequest(); $request->initialize(); $request->merge([ - 'hashcode' => Uuid::uuid4()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), ]); // WHEN @@ -58,7 +58,7 @@ describe('UnsubscribeNewsletterRequest', function () { // GIVEN $request = new UnsubscribeNewsletterRequest(); $request->initialize(); - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); $request->merge([ 'hashcode' => $uuid->toString(), ]); diff --git a/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php b/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php index 9628d687..3808c6b2 100644 --- a/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php +++ b/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php @@ -37,7 +37,7 @@ use Illuminate\Support\Facades\Notification; use Illuminate\Support\Str; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('SendMissingOrderReminderJob', function (): void { it('dispatches MissingOrderReminderNotification once per week with precomputed cutoff and ICS content', function (): void { @@ -134,7 +134,7 @@ describe('SendMissingOrderReminderJob', function (): void { ]); $exception = new PickupExceptionOnDate( - id: new PickupExceptionId(Uuid::uuid7()), + id: new PickupExceptionId(UuidHelper::v7()), date: CarbonImmutable::parse('2026-11-20', 'Europe/Paris'), label: 'Fermeture exceptionnelle', repeatable: false, @@ -194,9 +194,9 @@ describe('SendMissingOrderReminderJob', function (): void { ]); Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(2500, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -229,7 +229,7 @@ describe('SendMissingOrderReminderJob', function (): void { ]); $exception = new PickupExceptionOnDate( - id: new PickupExceptionId(Uuid::uuid7()), + id: new PickupExceptionId(UuidHelper::v7()), date: CarbonImmutable::parse('2026-11-20', 'Europe/Paris'), label: 'Décalage jeudi', repeatable: false, diff --git a/tests/Feature/App/Jobs/SendReminderMailTest.php b/tests/Feature/App/Jobs/SendReminderMailTest.php index 6a9992ca..25cc87ce 100644 --- a/tests/Feature/App/Jobs/SendReminderMailTest.php +++ b/tests/Feature/App/Jobs/SendReminderMailTest.php @@ -34,7 +34,7 @@ use Money\Currency; use Money\Money; use Money\MoneyFormatter; use Psr\Log\NullLogger; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('SendReminderMail job', function (): void { it('sends today reminder once and marks orders as reminded idempotently', function (): void { @@ -60,9 +60,9 @@ describe('SendReminderMail job', function (): void { ]); $order = Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(3000, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -126,9 +126,9 @@ describe('SendReminderMail job', function (): void { ]); $order = Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(3000, new Currency('EUR')), 'employee' => new OrderEmployee( diff --git a/tests/Feature/App/Listeners/Orders/SendAdminOrderConfirmationTest.php b/tests/Feature/App/Listeners/Orders/SendAdminOrderConfirmationTest.php index 851ebcab..fde7b6ad 100644 --- a/tests/Feature/App/Listeners/Orders/SendAdminOrderConfirmationTest.php +++ b/tests/Feature/App/Listeners/Orders/SendAdminOrderConfirmationTest.php @@ -22,13 +22,13 @@ use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Mail; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; function makeOrderPlacedEvent(): AnOrderHasBeenPlaced { return new AnOrderHasBeenPlaced( - orderId: new OrderId(Uuid::uuid7()), - reference: new OrderReference(Uuid::uuid7()), + orderId: new OrderId(UuidHelper::v7()), + reference: new OrderReference(UuidHelper::v7()), totalTtc: new Money(1500, new Currency('EUR')), byMatricule: new Matricule('1234567'), employee: new OrderEmployee( diff --git a/tests/Feature/App/Listeners/Orders/SendCustomerOrderConfirmationTest.php b/tests/Feature/App/Listeners/Orders/SendCustomerOrderConfirmationTest.php index 750f93ea..40250500 100644 --- a/tests/Feature/App/Listeners/Orders/SendCustomerOrderConfirmationTest.php +++ b/tests/Feature/App/Listeners/Orders/SendCustomerOrderConfirmationTest.php @@ -23,13 +23,13 @@ use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Support\Facades\Notification; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; function makeCustomerOrderPlacedEvent(string $matricule): AnOrderHasBeenPlaced { return new AnOrderHasBeenPlaced( - orderId: new OrderId(Uuid::uuid7()), - reference: new OrderReference(Uuid::uuid7()), + orderId: new OrderId(UuidHelper::v7()), + reference: new OrderReference(UuidHelper::v7()), totalTtc: new Money(1500, new Currency('EUR')), byMatricule: new Matricule($matricule), employee: new OrderEmployee( diff --git a/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php b/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php index 55afe162..54802504 100644 --- a/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php +++ b/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php @@ -13,32 +13,34 @@ use Illuminate\Auth\Events\Login; use Illuminate\Support\Facades\Date; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Psr\Log\NullLogger; -use Ramsey\Uuid\Uuid; use Shared\Concurrency\Lock; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; -it('updates customer last_login_at via Executor when Login event is handled', function (): void { - // GIVEN - Date::setTestNow('2026-11-14 14:00:00'); - $customer = new Customer(); - $customer->email = new Email('login@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); - $customer->last_login_at = null; - $customer->saveOrFail(); +describe('UpdateCustomerLastLogin', function (): void { + it('updates customer last_login_at via Executor when Login event is handled', function (): void { + // GIVEN + Date::setTestNow('2026-11-14 14:00:00'); + $customer = new Customer(); + $customer->email = new Email('login@example.com'); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); + $customer->last_login_at = null; + $customer->saveOrFail(); - $executor = new ActionExecutorService( - lock: \Mockery::mock(Lock::class), - logger: new NullLogger(), - eventDispatcher: new LaravelDomainEventDispatcher(), - ); - $listener = new UpdateCustomerLastLogin($executor, new UpdateCustomerLastLoginAction()); + $executor = new ActionExecutorService( + lock: \Mockery::mock(Lock::class), + logger: new NullLogger(), + eventDispatcher: new LaravelDomainEventDispatcher(), + ); + $listener = new UpdateCustomerLastLogin($executor, new UpdateCustomerLastLoginAction()); - // WHEN - $listener->handle(new Login('frontend', $customer, false)); + // WHEN + $listener->handle(new Login('frontend', $customer, false)); - // THEN - $customer->refresh(); - expect($customer->last_login_at?->format('Y-m-d H:i:s'))->toBe('2026-11-14 14:00:00'); + // THEN + $customer->refresh(); + expect($customer->last_login_at?->format('Y-m-d H:i:s'))->toBe('2026-11-14 14:00:00'); - Date::setTestNow(); + Date::setTestNow(); + }); }); diff --git a/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php b/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php index e01cb739..80607fc9 100644 --- a/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php +++ b/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php @@ -10,14 +10,14 @@ use Illuminate\Session\ArraySessionHandler; use Illuminate\Session\Store; use Infrastructure\Adapters\Repositories\SessionBasketRepository; use Infrastructure\Adapters\Serializers\BasketSerializer; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; covers(SessionBasketRepository::class); describe('SessionBasketRepository', function (): void { it('returns null if session is empty', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $session = new Store('test', new ArraySessionHandler(120)); $repo = new SessionBasketRepository($session, 'basket_key', new BasketSerializer()); @@ -30,7 +30,7 @@ describe('SessionBasketRepository', function (): void { it('persists and retrieves a basket using real Store and BasketSerializer', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId, []); $session = new Store('test', new ArraySessionHandler(120)); $repo = new SessionBasketRepository($session, 'basket_key', new BasketSerializer()); @@ -47,7 +47,7 @@ describe('SessionBasketRepository', function (): void { it('returns null if session data is invalid json', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $session = new Store('test', new ArraySessionHandler(120)); $session->put('basket_key' . $basketId->value->toString(), 'invalid-json'); $repo = new SessionBasketRepository($session, 'basket_key', new BasketSerializer()); @@ -61,7 +61,7 @@ describe('SessionBasketRepository', function (): void { it('returns null if deserialization throws exception', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $session = new Store('test', new ArraySessionHandler(120)); $session->put('basket_key' . $basketId->value->toString(), '{"invalid":"payload"}'); $repo = new SessionBasketRepository($session, 'basket_key', new BasketSerializer()); @@ -75,7 +75,7 @@ describe('SessionBasketRepository', function (): void { it('deletes basket from session', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId, []); $session = new Store('test', new ArraySessionHandler(120)); $repo = new SessionBasketRepository($session, 'basket_key', new BasketSerializer()); diff --git a/tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php b/tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php index 66f51a63..b1ffc87f 100644 --- a/tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php +++ b/tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php @@ -11,7 +11,7 @@ use Domain\Models\ValueObjects\Entities\ShopperId; use Illuminate\Session\ArraySessionHandler; use Illuminate\Session\Store; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('SessionOrderBuilderManager', function (): void { it('throws exception if session key is empty', function (): void { @@ -29,8 +29,8 @@ describe('SessionOrderBuilderManager', function (): void { // GIVEN $session = new Store('test', new ArraySessionHandler(120)); $builder = OrderBuilder::fromBasket( - new Basket(new BasketId(Uuid::uuid7()), []), - new ShopperId(Uuid::uuid7()), + new Basket(new BasketId(UuidHelper::v7()), []), + new ShopperId(UuidHelper::v7()), ); $session->put('builder_key', $builder); $manager = new SessionOrderBuilderManager($session, 'builder_key'); @@ -71,8 +71,8 @@ describe('SessionOrderBuilderManager', function (): void { // GIVEN $session = new Store('test', new ArraySessionHandler(120)); $builder = OrderBuilder::fromBasket( - new Basket(new BasketId(Uuid::uuid7()), []), - new ShopperId(Uuid::uuid7()), + new Basket(new BasketId(UuidHelper::v7()), []), + new ShopperId(UuidHelper::v7()), ); $manager = new SessionOrderBuilderManager($session, 'builder_key'); @@ -88,8 +88,8 @@ describe('SessionOrderBuilderManager', function (): void { // GIVEN $session = new Store('test', new ArraySessionHandler(120)); $builder = OrderBuilder::fromBasket( - new Basket(new BasketId(Uuid::uuid7()), []), - new ShopperId(Uuid::uuid7()), + new Basket(new BasketId(UuidHelper::v7()), []), + new ShopperId(UuidHelper::v7()), ); $session->put('builder_key', $builder); $manager = new SessionOrderBuilderManager($session, 'builder_key'); diff --git a/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php b/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php index 9dd90386..b818b461 100644 --- a/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php +++ b/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php @@ -16,7 +16,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Arr; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; covers(OrderLineProductCast::class); @@ -49,7 +49,7 @@ describe('OrderLineProductCast', function () { // GIVEN $cast = new OrderLineProductCast(); $model = \Mockery::mock(Model::class); - $uuid = Uuid::uuid7()->toString(); + $uuid = UuidHelper::v7()->toString(); $json = json_encode([ 'inco_id' => 123, @@ -83,7 +83,7 @@ describe('OrderLineProductCast', function () { // GIVEN $cast = new OrderLineProductCast(); $model = \Mockery::mock(Model::class); - $uuid = Uuid::uuid7()->toString(); + $uuid = UuidHelper::v7()->toString(); $json = json_encode([ 'inco_id' => 123, @@ -131,7 +131,7 @@ describe('OrderLineProductCast', function () { $product = new OrderLineProduct( incoId: new IncoId(123), - originalId: new ProductId(Uuid::uuid7()), + originalId: new ProductId(UuidHelper::v7()), name: 'Product Name', weight: new ProductWeight(1000, false), brand: ProductBrand::cases()[0], // Pick first enum case diff --git a/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php b/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php index 8a01f98b..9a47ba67 100644 --- a/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php +++ b/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php @@ -7,87 +7,88 @@ namespace Tests\Integration\WithApp\App\Casts; use App\Casts\OrderReferenceCast; use Domain\Models\ValueObjects\OrderReference; use Illuminate\Database\Eloquent\Model; -use Ramsey\Uuid\Uuid; use Shared\Helpers\UuidHelper; -it('gets a reference', function () { - // GIVEN - $cast = new OrderReferenceCast(); - $model = \Mockery::mock(Model::class); - $uuid = Uuid::uuid7(); - $value = UuidHelper::toBase58($uuid); +describe('OrderReferenceCast', function (): void { + it('gets a reference', function () { + // GIVEN + $cast = new OrderReferenceCast(); + $model = \Mockery::mock(Model::class); + $uuid = UuidHelper::v7(); + $value = UuidHelper::toBase58($uuid); - // WHEN - $reference = $cast->get($model, 'reference', $value, []); + // WHEN + $reference = $cast->get($model, 'reference', $value, []); - // THEN - expect((string) $reference)->toBe($value) - ->and($reference->value->equals($uuid))->toBeTrue(); -}); - -it('gets a reference from raw uuid string', function () { - // GIVEN - $cast = new OrderReferenceCast(); - $model = \Mockery::mock(Model::class); - $uuid = Uuid::uuid7(); - $value = $uuid->toString(); - - // WHEN - $reference = $cast->get($model, 'reference', $value, []); - - // THEN - expect((string) $reference)->toBe(UuidHelper::toBase58($uuid)) - ->and($reference->value->equals($uuid))->toBeTrue(); -}); - -it('throws exception when getting invalid reference', function () { - // GIVEN - $cast = new OrderReferenceCast(); - $model = \Mockery::mock(Model::class); - - // WHEN - $cast->get($model, 'reference', 123, []); - - // THEN -})->throws(\UnexpectedValueException::class, 'OrderReference cannot be null.'); - -it('throws exception when getting null reference', function () { - // GIVEN - $cast = new OrderReferenceCast(); - $model = \Mockery::mock(Model::class); - - // WHEN - $cast->get($model, 'reference', null, []); - - // THEN -})->throws(\UnexpectedValueException::class, 'OrderReference cannot be null.'); - -it('throws exception when setting invalid reference type', function () { - // GIVEN - $cast = new OrderReferenceCast(); - $model = \Mockery::mock(Model::class); - $value = UuidHelper::toBase58(Uuid::uuid7()); - - // WHEN - /** @phpstan-ignore argument.type */ - $cast->set($model, 'reference', $value, []); - - // THEN -})->throws( - \UnexpectedValueException::class, - 'The given value is not an instance of OrderReference.' -); - -it('sets a reference', function () { - // GIVEN - $cast = new OrderReferenceCast(); - $model = \Mockery::mock(Model::class); - $uuid = Uuid::uuid7(); - $reference = new OrderReference($uuid); - - // WHEN - $value = $cast->set($model, 'reference', $reference, []); - - // THEN - expect($value)->toBe(UuidHelper::toBase58($uuid)); + // THEN + expect((string) $reference)->toBe($value) + ->and($reference->value->equals($uuid))->toBeTrue(); + }); + + it('gets a reference from raw uuid string', function () { + // GIVEN + $cast = new OrderReferenceCast(); + $model = \Mockery::mock(Model::class); + $uuid = UuidHelper::v7(); + $value = $uuid->toString(); + + // WHEN + $reference = $cast->get($model, 'reference', $value, []); + + // THEN + expect((string) $reference)->toBe(UuidHelper::toBase58($uuid)) + ->and($reference->value->equals($uuid))->toBeTrue(); + }); + + it('throws exception when getting invalid reference', function () { + // GIVEN + $cast = new OrderReferenceCast(); + $model = \Mockery::mock(Model::class); + + // WHEN + $cast->get($model, 'reference', 123, []); + + // THEN + })->throws(\UnexpectedValueException::class, 'OrderReference cannot be null.'); + + it('throws exception when getting null reference', function () { + // GIVEN + $cast = new OrderReferenceCast(); + $model = \Mockery::mock(Model::class); + + // WHEN + $cast->get($model, 'reference', null, []); + + // THEN + })->throws(\UnexpectedValueException::class, 'OrderReference cannot be null.'); + + it('throws exception when setting invalid reference type', function () { + // GIVEN + $cast = new OrderReferenceCast(); + $model = \Mockery::mock(Model::class); + $value = UuidHelper::toBase58(UuidHelper::v7()); + + // WHEN + /** @phpstan-ignore argument.type */ + $cast->set($model, 'reference', $value, []); + + // THEN + })->throws( + \UnexpectedValueException::class, + 'The given value is not an instance of OrderReference.' + ); + + it('sets a reference', function () { + // GIVEN + $cast = new OrderReferenceCast(); + $model = \Mockery::mock(Model::class); + $uuid = UuidHelper::v7(); + $reference = new OrderReference($uuid); + + // WHEN + $value = $cast->set($model, 'reference', $reference, []); + + // THEN + expect($value)->toBe(UuidHelper::toBase58($uuid)); + }); }); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php index f0294da8..f407f3c9 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php @@ -33,7 +33,7 @@ use Infrastructure\Adapters\Services\AppSessionService; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; use Money\Money; use Psr\Log\NullLogger; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; function makeBasketProductFixture(bool $status = true, bool $withInco = true): Product { @@ -112,8 +112,8 @@ describe('AddToBasket action', function (): void { $repository = new SessionBasketRepository($session, 'basket_', new BasketSerializer()); $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); $builderManager->save(OrderBuilder::fromBasket( - new Basket(new BasketId(Uuid::uuid7()), []), - new ShopperId(Uuid::uuid7()), + new Basket(new BasketId(UuidHelper::v7()), []), + new ShopperId(UuidHelper::v7()), )); $dispatcher = new LaravelDomainEventDispatcher(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php index 86fa7928..38535638 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php @@ -32,7 +32,7 @@ use Infrastructure\Adapters\Services\AppSessionService; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; use Money\Money; use Psr\Log\NullLogger; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('EmptyBasket action', function (): void { it('removes all items from session basket and clears order builder', function (): void { @@ -82,8 +82,8 @@ describe('EmptyBasket action', function (): void { $basketSvc->add($product->getId(), 2); $builderManager->save(OrderBuilder::fromBasket( - new Basket(new BasketId(Uuid::uuid7()), []), - new ShopperId(Uuid::uuid7()), + new Basket(new BasketId(UuidHelper::v7()), []), + new ShopperId(UuidHelper::v7()), )); $executor = new ActionExecutorService( diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php index ab37e5a1..6bded19c 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php @@ -33,7 +33,7 @@ use Infrastructure\Adapters\Services\AppSessionService; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; use Money\Money; use Psr\Log\NullLogger; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; function makeRemovableProductFixture(): Product { @@ -120,8 +120,8 @@ describe('RemoveFromBasket action', function (): void { $basketSvc->add($product2->getId(), 2); $builderManager->save(OrderBuilder::fromBasket( - new Basket(new BasketId(Uuid::uuid7()), []), - new ShopperId(Uuid::uuid7()), + new Basket(new BasketId(UuidHelper::v7()), []), + new ShopperId(UuidHelper::v7()), )); $executor = new ActionExecutorService( diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php index 4e3a860f..d03e0d04 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php @@ -11,7 +11,7 @@ use App\Lib\PrivateS3Disk; use Domain\Models\ValueObjects\AttachedFile; use Domain\Models\ValueObjects\OrderReference; use Illuminate\Http\UploadedFile; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Uwil\Storage\Contracts\StorageService; use Uwil\Storage\Lib\ValueObjects\DiskName; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; @@ -22,7 +22,7 @@ describe('SubmitContactForm action', function (): void { $storage = \Mockery::mock(StorageService::class); $storage->shouldNotReceive('storeUploadedOntoDisk'); $action = new SubmitContactForm($storage, new PrivateS3Disk()); - $orderRef = new OrderReference(Uuid::uuid7()); + $orderRef = new OrderReference(UuidHelper::v7()); $input = new SubmitContactFormInput( lastName: 'Doe', firstName: 'John', diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UnsubscribeFromNewsletterTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UnsubscribeFromNewsletterTest.php index 42e68d77..d3ce64b6 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UnsubscribeFromNewsletterTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UnsubscribeFromNewsletterTest.php @@ -8,13 +8,13 @@ use App\Cqs\Actions\Crm\UnsubscribeFromNewsletter; use App\Cqs\Actions\Crm\UnsubscribeFromNewsletterInput; use App\Cqs\Actions\Crm\UnsubscribeFromNewsletterOutput; use App\Services\CrmService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('UnsubscribeFromNewsletter action', function (): void { it('returns SUCCESS when CRM service unsubscribes the customer', function (): void { // GIVEN - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ $crmService = \Mockery::mock(CrmService::class); @@ -34,7 +34,7 @@ describe('UnsubscribeFromNewsletter action', function (): void { it('returns FAILURE when CRM service returns false', function (): void { // GIVEN - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ $crmService = \Mockery::mock(CrmService::class); @@ -54,7 +54,7 @@ describe('UnsubscribeFromNewsletter action', function (): void { it('returns FAILURE without throwing when CRM service throws an exception', function (): void { // GIVEN - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ $crmService = \Mockery::mock(CrmService::class); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php index 40c12fc3..fd1e567e 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php @@ -14,7 +14,7 @@ use Domain\Models\ValueObjects\CrmCustomer; use Domain\Models\ValueObjects\Email; use Illuminate\Support\Facades\Auth; use Infrastructure\Adapters\Services\AppCustomerAuthService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; function makePasswordTestCrmCustomer(string $hashcode, string $email): CrmCustomer @@ -42,7 +42,7 @@ describe('UpdateCustomerPassword action', function (): void { it('changes password in CRM for authenticated customer', function (): void { /** @var \Tests\TestCase $this */ // GIVEN - $hashcodeUuid = Uuid::uuid4(); + $hashcodeUuid = UuidHelper::v4(); $hashcode = $hashcodeUuid->toString(); $customer = new Customer(); $customer->email = new Email('claire.dupuis@example.com'); @@ -79,7 +79,7 @@ describe('UpdateCustomerPassword action', function (): void { // GIVEN $customer = new Customer(); $customer->email = new Email('missing.crm@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->saveOrFail(); $this->actingAs($customer, 'frontend'); @@ -104,7 +104,7 @@ describe('UpdateCustomerPassword action', function (): void { it('returns false output when changePassword throws an unexpected exception', function (): void { /** @var \Tests\TestCase $this */ // GIVEN - $hashcodeUuid = Uuid::uuid4(); + $hashcodeUuid = UuidHelper::v4(); $hashcode = $hashcodeUuid->toString(); $customer = new Customer(); $customer->email = new Email('pwd.error@example.com'); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php index ffa16dbe..059f0211 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php @@ -15,7 +15,7 @@ use Domain\Models\ValueObjects\Email; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\ValidationException; use Infrastructure\Adapters\Services\AppCustomerAuthService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; function makeCrmCustomerDto(string $hashcode, string $email): CrmCustomer @@ -43,7 +43,7 @@ describe('UpdateCustomer action', function (): void { it('updates customer information in CRM for the authenticated customer', function (): void { /** @var \Tests\TestCase $this */ // GIVEN - $hashcodeUuid = Uuid::uuid4(); + $hashcodeUuid = UuidHelper::v4(); $hashcode = $hashcodeUuid->toString(); $customer = new Customer(); $customer->email = new Email('jeanne.martin@example.com'); @@ -97,7 +97,7 @@ describe('UpdateCustomer action', function (): void { it('omits nullable phone and address when null and propagates validation exceptions', function (): void { /** @var \Tests\TestCase $this */ // GIVEN - $hashcodeUuid = Uuid::uuid4(); + $hashcodeUuid = UuidHelper::v4(); $customer = new Customer(); $customer->email = new Email('no.phone@example.com'); $customer->hashcode = new CrmHashcode($hashcodeUuid); @@ -144,7 +144,7 @@ describe('UpdateCustomer action', function (): void { // GIVEN $customer = new Customer(); $customer->email = new Email('err.crm@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->saveOrFail(); $this->actingAs($customer, 'frontend'); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php index df76db1f..876281d5 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php @@ -34,9 +34,9 @@ use Illuminate\Validation\ValidationException; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Infrastructure\Adapters\Services\AppCustomerAuthService; use Psr\Log\NullLogger; -use Ramsey\Uuid\Uuid; use Shared\Concurrency\Lock; use Shared\Concurrency\LockTimeoutException; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('RegisterCustomer action', function (): void { @@ -62,7 +62,7 @@ describe('RegisterCustomer action', function (): void { $employee->service = new ShopperServiceCode('1'); $employee->saveOrFail(); - $crmReturnedHashcode = Uuid::uuid4()->toString(); + $crmReturnedHashcode = UuidHelper::v4()->toString(); $crmService = \Mockery::mock(CrmService::class); $crmService->shouldReceive('persist') @@ -138,7 +138,7 @@ describe('RegisterCustomer action', function (): void { it('returns EMPLOYEE_ALREADY_REGISTERED when employee already has a customer_id', function (): void { // GIVEN $existingCustomer = new Customer(['email' => new Email('already@example.com')]); - $existingCustomer->hashcode = new CrmHashcode(Uuid::uuid4()); + $existingCustomer->hashcode = new CrmHashcode(UuidHelper::v4()); $existingCustomer->saveOrFail(); $matricule = new Matricule('5678901'); @@ -576,7 +576,7 @@ describe('RegisterCustomer action', function (): void { $employee->service = new ShopperServiceCode('1'); $employee->saveOrFail(); - $crmReturnedHashcode = Uuid::uuid4()->toString(); + $crmReturnedHashcode = UuidHelper::v4()->toString(); $crmService = \Mockery::mock(CrmService::class); $crmService->shouldReceive('persist')->once()->andReturn(new CrmCustomer( @@ -645,7 +645,7 @@ describe('RegisterCustomer action', function (): void { $employee->service = new ShopperServiceCode('1'); $employee->saveOrFail(); - $crmUuid = Uuid::uuid4(); + $crmUuid = UuidHelper::v4(); $crmReturnedHashcode = $crmUuid->toString(); $crmService = \Mockery::mock(CrmService::class); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Customers/UpdateCustomerLastLoginTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Customers/UpdateCustomerLastLoginTest.php index 89dd859a..e9003f68 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Customers/UpdateCustomerLastLoginTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Customers/UpdateCustomerLastLoginTest.php @@ -10,7 +10,7 @@ use App\Cqs\Actions\Customers\UpdateCustomerLastLoginInput; use App\Models\Customer; use Domain\Models\ValueObjects\Email; use Illuminate\Support\Facades\Date; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('UpdateCustomerLastLogin action', function (): void { @@ -19,7 +19,7 @@ describe('UpdateCustomerLastLogin action', function (): void { Date::setTestNow('2026-11-14 10:30:00'); $customer = new Customer(); $customer->email = new Email('customer@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->last_login_at = null; $customer->saveOrFail(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php index 18e743e4..a27f113c 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php @@ -49,7 +49,7 @@ use Infrastructure\Adapters\Services\EloquentEmployeeStatisticsService; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('ApplyPickTimeSlot action', function (): void { @@ -73,7 +73,7 @@ describe('ApplyPickTimeSlot action', function (): void { $customer = new Customer(); $customer->email = new Email('slot.buyer@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->saveOrFail(); $employee = new Employee(); @@ -88,8 +88,8 @@ describe('ApplyPickTimeSlot action', function (): void { $employee->service = new ShopperServiceCode('01'); $employee->saveOrFail(); - $productId = new ProductId(Uuid::uuid7()); - $basket = new Basket(new BasketId(Uuid::uuid7()), [ + $productId = new ProductId(UuidHelper::v7()); + $basket = new Basket(new BasketId(UuidHelper::v7()), [ $productId->value->toString() => new BasketProduct( id: $productId, name: 'Filet de Poulet', diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php index 3e639b20..ea48952e 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php @@ -21,16 +21,16 @@ use Domain\Services\OrderService; use Infrastructure\Adapters\Repositories\EloquentOrderRepository; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; function makeCancelOrderFixture(OrderStatus $status = OrderStatus::VALIDATED): Order { $shop = Shop::factory()->create(); return Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => $status->value, 'total' => new Money(2500, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -63,7 +63,7 @@ describe('CancelOrder action', function (): void { it('returns NOT_FOUND when the order does not exist in database', function (): void { // GIVEN $missingOrder = new Order(); - $missingOrder->id = Uuid::uuid7()->toString(); + $missingOrder->id = UuidHelper::v7()->toString(); $action = new CancelOrder(new OrderService(new EloquentOrderRepository())); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php index 0f8c5c38..e32d88d3 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php @@ -19,16 +19,16 @@ use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('ClaimTodayOrderReminder action', function (): void { it('claims an unreminded validated order atomically and rejects duplicate claims', function (): void { // GIVEN $shop = Shop::factory()->create(); $order = Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(2000, new Currency('EUR')), 'employee' => new OrderEmployee( diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/FailStalePendingOrdersTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/FailStalePendingOrdersTest.php index 97e762b3..97b4575a 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/FailStalePendingOrdersTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/FailStalePendingOrdersTest.php @@ -22,7 +22,7 @@ use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Infrastructure\Adapters\Locks\LaravelCacheLock; use Infrastructure\Adapters\Repositories\EloquentOrderRepository; use Psr\Log\NullLogger; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('FailStalePendingOrders', function (): void { afterEach(function (): void { @@ -38,10 +38,10 @@ describe('FailStalePendingOrders', function (): void { $shop = Shop::factory()->create(); - $stalePendingId = Uuid::uuid7()->toString(); - $freshPendingId = Uuid::uuid7()->toString(); - $staleWaitingId = Uuid::uuid7()->toString(); - $staleValidatedId = Uuid::uuid7()->toString(); + $stalePendingId = UuidHelper::v7()->toString(); + $freshPendingId = UuidHelper::v7()->toString(); + $staleWaitingId = UuidHelper::v7()->toString(); + $staleValidatedId = UuidHelper::v7()->toString(); $baseRow = [ 'shop_id' => $shop->id, @@ -61,25 +61,25 @@ describe('FailStalePendingOrders', function (): void { DB::table('orders')->insert([ array_merge($baseRow, [ 'id' => $stalePendingId, - 'reference' => (string) new OrderReference(Uuid::uuid7()), + 'reference' => (string) new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::PENDING->value, 'updated_at' => $now->subMinutes(15)->toDateTimeString(), ]), array_merge($baseRow, [ 'id' => $freshPendingId, - 'reference' => (string) new OrderReference(Uuid::uuid7()), + 'reference' => (string) new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::PENDING->value, 'updated_at' => $now->subMinutes(4)->toDateTimeString(), ]), array_merge($baseRow, [ 'id' => $staleWaitingId, - 'reference' => (string) new OrderReference(Uuid::uuid7()), + 'reference' => (string) new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::WAITING->value, 'updated_at' => $now->subHours(2)->toDateTimeString(), ]), array_merge($baseRow, [ 'id' => $staleValidatedId, - 'reference' => (string) new OrderReference(Uuid::uuid7()), + 'reference' => (string) new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'updated_at' => $now->subHours(2)->toDateTimeString(), ]), diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php index c474fbb8..a5b1ed40 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php @@ -36,7 +36,7 @@ use Infrastructure\Adapters\Services\EloquentEmployeeStatisticsService; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('InitializeOrderTunnel action', function (): void { it('stores OrderBuilderWithBasket in session for the shopper and basket', function (): void { @@ -67,8 +67,8 @@ describe('InitializeOrderTunnel action', function (): void { new DatabaseTunnelAttemptTrackerService($session, 'order_tunnel_attempt_id'), ); - $productId = new ProductId(Uuid::uuid7()); - $basket = new Basket(new BasketId(Uuid::uuid7()), [ + $productId = new ProductId(UuidHelper::v7()); + $basket = new Basket(new BasketId(UuidHelper::v7()), [ $productId->value->toString() => new BasketProduct( id: $productId, name: 'Poulet Rôti', @@ -91,9 +91,9 @@ describe('InitializeOrderTunnel action', function (): void { ]); /** @var Customer $customer */ $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'email' => new Email('init-tunnel@example.com'), - 'hashcode' => Uuid::uuid4()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), ]); $shopperId = $customer->getId(); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php index d1107e01..48ef9267 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -82,9 +82,9 @@ use Infrastructure\Adapters\Services\SessionOrderBuilderManager; use Money\Currency; use Money\Money; use Psr\Log\NullLogger; -use Ramsey\Uuid\Uuid; use Shared\Concurrency\Lock; use Shared\Concurrency\LockTimeoutException; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('Order placement two-step CQS actions', function (): void { @@ -128,9 +128,9 @@ describe('Order placement two-step CQS actions', function (): void { ): array { /** @var Customer $customer */ $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'email' => new Email('buyer-' . uniqid() . '@example.com'), - 'hashcode' => new CrmHashcode(Uuid::uuid4()), + 'hashcode' => new CrmHashcode(UuidHelper::v4()), ]); /** @var int $sequence */ @@ -389,9 +389,9 @@ describe('Order placement two-step CQS actions', function (): void { $ctx = buildOrderPlacementScenario(priceCents: 6000, qty: 1); Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $ctx['shop']->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::PENDING->value, 'total' => Money::EUR(16000), 'employee' => new OrderEmployee( @@ -472,7 +472,7 @@ describe('Order placement two-step CQS actions', function (): void { it('executes ExportOrderToRegate without opening a DB transaction and returns LOCK_TIMEOUT when lock fails', function (): void { // GIVEN - $orderId = new OrderId(Uuid::uuid7()); + $orderId = new OrderId(UuidHelper::v7()); $input = new ExportOrderToRegateInput($orderId); $levelBeforeExecute = DB::transactionLevel(); $levelInsideAction = null; diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php index 82297be7..3aa9d435 100644 --- a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php @@ -19,7 +19,7 @@ use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('ReleaseTodayOrderReminder action', function (): void { it('releases reminded_at only when timestamp matches the claim timestamp', function (): void { @@ -28,9 +28,9 @@ describe('ReleaseTodayOrderReminder action', function (): void { $otherAt = CarbonImmutable::parse('2026-11-20 10:05:00'); $shop = Shop::factory()->create(); $order = Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(2000, new Currency('EUR')), 'employee' => new OrderEmployee( diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Basket/GetBasketQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Basket/GetBasketQueryTest.php index ceb24a0d..3513e394 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Basket/GetBasketQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Basket/GetBasketQueryTest.php @@ -27,13 +27,13 @@ use Domain\Ports\Services\SessionService; use Domain\Services\BasketService; use Mockery; use Money\Money; -use Ramsey\Uuid\Uuid; use Shared\DDD\DomainEventDispatcher; +use Shared\Helpers\UuidHelper; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; function makeBasketServiceWithBasket(?Basket $basket): BasketService { - $basketId = $basket !== null ? $basket->id : new BasketId(Uuid::uuid7()); + $basketId = $basket !== null ? $basket->id : new BasketId(UuidHelper::v7()); $sessionId = new SessionId($basketId->value); $sessionService = Mockery::mock(SessionService::class); @@ -135,10 +135,10 @@ describe('GetBasketQuery', function (): void { $unpublishedProduct->price = Money::EUR(1000); $unpublishedProduct->save(); - $publishedId = new ProductId(Uuid::fromString($publishedProduct->id)); - $unpublishedId = new ProductId(Uuid::fromString($unpublishedProduct->id)); + $publishedId = new ProductId(UuidHelper::fromString($publishedProduct->id)); + $unpublishedId = new ProductId(UuidHelper::fromString($unpublishedProduct->id)); - $basket = new Basket(new BasketId(Uuid::uuid7()), [ + $basket = new Basket(new BasketId(UuidHelper::v7()), [ makeBasketProductItem($publishedId, 'Poulet Publié', 2), makeBasketProductItem($unpublishedId, 'Poulet Dépublié', 1), ]); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php index 3e7a9557..060033c9 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php @@ -9,7 +9,7 @@ use App\Cqs\Queries\Customers\GetCustomerByEmailQueryInput; use App\Models\Customer; use Domain\Models\ValueObjects\Email; use Domain\Models\ValueObjects\Entities\ShopperId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('GetCustomerByEmailQuery', function (): void { @@ -17,7 +17,7 @@ describe('GetCustomerByEmailQuery', function (): void { // GIVEN $email = new Email('john.doe@example.com'); $customer = new Customer(['email' => $email]); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); $query = new GetCustomerByEmailQuery(); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoPaginatedOrdersQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoPaginatedOrdersQueryTest.php index bc1063fd..af0825fc 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoPaginatedOrdersQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoPaginatedOrdersQueryTest.php @@ -25,7 +25,7 @@ use Illuminate\Session\Store; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Schema; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\Pagination\PageNumber; use Shared\Pagination\PageSize; use Shared\Pagination\Pagination; @@ -56,9 +56,9 @@ describe('GetBoPaginatedOrdersQuery', function (): void { ): Order { $order = new Order(); if ($createdAt !== null) { - $order->id = (string) Uuid::uuid7($createdAt); + $order->id = (string) UuidHelper::v7($createdAt); } - $order->reference = new OrderReference(Uuid::uuid7()); + $order->reference = new OrderReference(UuidHelper::v7()); $order->total = Money::EUR(2500); $order->status = $status; $order->pickup_day = Carbon::instance($pickupDay); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoTodayOrdersQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoTodayOrdersQueryTest.php index abfb405e..63e8dda4 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoTodayOrdersQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoTodayOrdersQueryTest.php @@ -21,7 +21,7 @@ use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Http\Request; use Illuminate\Support\Facades\Date; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\Pagination\PageNumber; use Shared\Pagination\PageSize; use Shared\Pagination\Pagination; @@ -42,7 +42,7 @@ describe('GetBoTodayOrdersQuery', function (): void { $createOrder = static function (OrderStatus $status) use ($shop): Order { $order = new Order(); - $order->reference = new OrderReference(Uuid::uuid7()); + $order->reference = new OrderReference(UuidHelper::v7()); $order->total = Money::EUR(2000); $order->status = $status; $order->pickup_day = Date::now()->addDays(4); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQueryTest.php index dd0c0b99..c60d6e05 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQueryTest.php @@ -23,7 +23,7 @@ use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Support\Carbon; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\Pagination\PageNumber; use Shared\Pagination\PageSize; use Shared\Pagination\Pagination; @@ -37,7 +37,7 @@ describe('GetFoCustomerPaginatedOrdersQuery', function (): void { $createCustomer = function (): Customer { $customer = new Customer(); $customer->email = new Email('customer-' . uniqid() . '@example.com'); - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->save(); return $customer; @@ -72,7 +72,7 @@ describe('GetFoCustomerPaginatedOrdersQuery', function (): void { $createOrder = function (Shop $shop, string $matricule): Order { $order = new Order(); - $order->reference = new OrderReference(Uuid::uuid7()); + $order->reference = new OrderReference(UuidHelper::v7()); $order->total = Money::EUR(2500); $order->status = OrderStatus::WAITING; $order->pickup_day = Carbon::now()->addDays(2); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php index 972932ae..402674a6 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php @@ -19,7 +19,7 @@ use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('GetTunnelOrderConfirmedQuery', function (): void { it('returns order confirmed output with step, orderDto, shopDto and mapUrl', function (): void { @@ -32,7 +32,7 @@ describe('GetTunnelOrderConfirmedQuery', function (): void { $shop->default = true; $shop->save(); - $reference = new OrderReference(Uuid::uuid7()); + $reference = new OrderReference(UuidHelper::v7()); $order = new Order(); $order->reference = $reference; @@ -70,7 +70,7 @@ describe('GetTunnelOrderConfirmedQuery', function (): void { it('throws UnexpectedValueException when order has no shop', function (): void { // GIVEN - $reference = new OrderReference(Uuid::uuid7()); + $reference = new OrderReference(UuidHelper::v7()); $order = new Order(); $order->reference = $reference; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php index 06cb6ecc..c00ba0a7 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php @@ -18,7 +18,7 @@ use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; use Infrastructure\Adapters\Repositories\EloquentProductRepository; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; function createTestProductForIncoQuery(): Product { @@ -41,7 +41,7 @@ function createTestProductForIncoQuery(): Product 'description' => 'Description test', 'status' => true, ]); - $product->id = Uuid::uuid7()->toString(); + $product->id = UuidHelper::v7()->toString(); $product->order = random_int(1, 999999); $product->price = Money::EUR(1000); $product->short_description = 'Court'; diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductWithPricingQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductWithPricingQueryTest.php index 2ad30406..99b4209c 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductWithPricingQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductWithPricingQueryTest.php @@ -23,7 +23,7 @@ use Domain\Models\ValueObjects\Entities\ProductId; use Domain\Models\ValueObjects\Slug; use Infrastructure\Adapters\Repositories\EloquentProductRepository; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; afterEach(function (): void { CarbonImmutable::setTestNow(); @@ -95,7 +95,7 @@ describe('GetProductWithPricingQuery', function (): void { ->and($bySlug?->pricing->discountedPriceHt->getAmount())->toBe('1500'); // WHEN: by ProductId - $byId = $query(new GetProductQueryInput(new ProductId(Uuid::fromString($product->id)))); + $byId = $query(new GetProductQueryInput(new ProductId(UuidHelper::fromString($product->id)))); // THEN expect($byId)->toBeInstanceOf(ProductWithPricingDto::class) @@ -109,7 +109,7 @@ describe('GetProductWithPricingQuery', function (): void { // WHEN $bySlug = $query(new GetProductQueryInput(new Slug('non-existent-slug-' . uniqid()))); - $byId = $query(new GetProductQueryInput(new ProductId(Uuid::uuid7()))); + $byId = $query(new GetProductQueryInput(new ProductId(UuidHelper::v7()))); // THEN expect($bySlug)->toBeNull() diff --git a/tests/Integration/WithApp/App/Cqs/Queries/Timeslots/GetAvailableTimeslotsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Timeslots/GetAvailableTimeslotsQueryTest.php index 3e81c75d..79721470 100644 --- a/tests/Integration/WithApp/App/Cqs/Queries/Timeslots/GetAvailableTimeslotsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Timeslots/GetAvailableTimeslotsQueryTest.php @@ -17,7 +17,7 @@ use Domain\Services\PickupSchedulingService; use Illuminate\Support\Carbon; use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; use Infrastructure\Adapters\Repositories\EloquentShopRepository; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; afterEach(function (): void { CarbonImmutable::setTestNow(); @@ -31,7 +31,7 @@ describe('GetAvailableTimeslotsQuery', function (): void { new PickupSchedulingService(new EloquentPickupExceptionRepository()), new EloquentShopRepository(), ); - $input = new GetAvailableTimeslotsQueryInput(new ShopId(Uuid::uuid7())); + $input = new GetAvailableTimeslotsQueryInput(new ShopId(UuidHelper::v7())); // WHEN $result = $query($input); @@ -57,7 +57,7 @@ describe('GetAvailableTimeslotsQuery', function (): void { new PickupSchedulingService(new EloquentPickupExceptionRepository()), new EloquentShopRepository(), ); - $input = new GetAvailableTimeslotsQueryInput(new ShopId(Uuid::fromString($shop->id))); + $input = new GetAvailableTimeslotsQueryInput(new ShopId(UuidHelper::fromString($shop->id))); // WHEN $result = $query($input); @@ -100,7 +100,7 @@ describe('GetAvailableTimeslotsQuery', function (): void { new PickupSchedulingService(new EloquentPickupExceptionRepository()), new EloquentShopRepository(), ); - $input = new GetAvailableTimeslotsQueryInput(new ShopId(Uuid::fromString($shop->id))); + $input = new GetAvailableTimeslotsQueryInput(new ShopId(UuidHelper::fromString($shop->id))); // WHEN $result = $query($input); diff --git a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php index 1f0107c3..6331d804 100644 --- a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php @@ -27,7 +27,7 @@ use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Support\Facades\Date; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; beforeEach(function (): void { $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); @@ -47,9 +47,9 @@ describe('OrderLineDto Integration', function (): void { // GIVEN $shop = Shop::factory()->create(); $order = Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => Money::EUR(4154), 'employee' => new OrderEmployee( @@ -66,7 +66,7 @@ describe('OrderLineDto Integration', function (): void { $orderLineProduct = new OrderLineProduct( incoId: new IncoId(999), - originalId: new ProductId(Uuid::uuid7()), + originalId: new ProductId(UuidHelper::v7()), name: 'Terrine de Foie Gras de Canard mi-cuit 500g', weight: new ProductWeight(500, false), brand: ProductBrand::loue, diff --git a/tests/Integration/WithApp/App/Models/ProductTest.php b/tests/Integration/WithApp/App/Models/ProductTest.php index 8c051599..f0d34ea2 100644 --- a/tests/Integration/WithApp/App/Models/ProductTest.php +++ b/tests/Integration/WithApp/App/Models/ProductTest.php @@ -14,7 +14,7 @@ use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; use Illuminate\Support\Facades\Date; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; function createOrderableTestProduct( Range $range, @@ -34,7 +34,7 @@ function createOrderableTestProduct( 'orderable_start' => $orderableStart, 'orderable_end' => $orderableEnd, ]); - $product->id = Uuid::uuid7()->toString(); + $product->id = UuidHelper::v7()->toString(); $product->order = random_int(1, 999999); $product->price = Money::EUR(1000); $product->short_description = 'Description courte'; diff --git a/tests/Integration/WithApp/App/Services/CrmServiceTest.php b/tests/Integration/WithApp/App/Services/CrmServiceTest.php index 9a2ae38e..27dc5184 100644 --- a/tests/Integration/WithApp/App/Services/CrmServiceTest.php +++ b/tests/Integration/WithApp/App/Services/CrmServiceTest.php @@ -23,7 +23,7 @@ use LDC\LDCCRM\Models\ClientModel; use LDC\LDCCRM\Models\Customer; use LDC\LDCCRM\Transport\ApiInterface; use LDC\LDCCRM\Utils; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('CrmService', function (): void { @@ -32,7 +32,7 @@ describe('CrmService', function (): void { $crmApi = \Mockery::mock(CrmApiV4::class); $cacheRepository = \Mockery::mock(CacheRepository::class); - $uuidObj = Uuid::uuid4(); + $uuidObj = UuidHelper::v4(); $uuid = $uuidObj->toString(); $libCustomer = new Customer([ @@ -105,7 +105,7 @@ describe('CrmService', function (): void { $cacheKey = 'crm_customer_email_' . hash('sha256', $email); $expectedCustomer = new CrmCustomer( - hashcode: (string) Uuid::uuid4(), + hashcode: (string) UuidHelper::v4(), email: $email, password: 'Secret123!', firstname: 'Jane', @@ -142,7 +142,7 @@ describe('CrmService', function (): void { $crmApi = \Mockery::mock(CrmApiV4::class); $cacheRepository = \Mockery::mock(CacheRepository::class); - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); $cacheKey = "crm_customer_hashcode_{$uuid}"; $cacheRepository->shouldReceive('remember') @@ -171,7 +171,7 @@ describe('CrmService', function (): void { $crmApi = \Mockery::mock(CrmApiV4::class); $cacheRepository = \Mockery::mock(CacheRepository::class); - $uuid = (string) Uuid::uuid4(); + $uuid = (string) UuidHelper::v4(); $customer = new CrmCustomer( hashcode: $uuid, @@ -224,7 +224,7 @@ describe('CrmService', function (): void { $crmApi = \Mockery::mock(CrmApiV4::class); $cacheRepository = new ArrayCacheRepository(new ArrayStore()); - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); $email = 'error@example.com'; $hashKey = "crm_customer_hashcode_{$uuid}"; $emailKey = 'crm_customer_email_' . hash('sha256', $email); @@ -256,7 +256,7 @@ describe('CrmService', function (): void { // GIVEN $crmApi = \Mockery::mock(CrmApiV4::class); $cacheRepository = \Mockery::mock(CacheRepository::class); - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); $expectedHashKey = "crm_customer_hashcode_{$uuid->toString()}"; $cacheRepository->shouldReceive('get')->with($expectedHashKey)->once()->andReturnNull(); @@ -288,7 +288,7 @@ describe('CrmService', function (): void { // GIVEN $crmApi = \Mockery::mock(CrmApiV4::class); $cacheRepository = new ArrayCacheRepository(new ArrayStore()); - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); $apiException = \Mockery::mock(ApiErrorException::class); $apiException->shouldReceive('getApiError')->andReturn(ApiError::modelNotFound); @@ -311,7 +311,7 @@ describe('CrmService', function (): void { // GIVEN $crmApi = \Mockery::mock(CrmApiV4::class); $cacheRepository = new ArrayCacheRepository(new ArrayStore()); - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); $apiInterface = \Mockery::mock(ApiInterface::class); $apiInterface->shouldReceive('call')->once()->andThrow(new CrmException('CRM delete error')); @@ -330,7 +330,7 @@ describe('CrmService', function (): void { /** @var CrmApiV4&\Mockery\MockInterface $crmApi */ $crmApi = \Mockery::mock(CrmApiV4::class); $cacheRepository = new ArrayCacheRepository(new ArrayStore()); - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); $email = new Email('Rollback@Example.com'); $hashKey = "crm_customer_hashcode_{$uuid->toString()}"; $emailKey = 'crm_customer_email_' . hash('sha256', 'rollback@example.com'); @@ -388,7 +388,7 @@ describe('CrmService', function (): void { /** @var CrmApiV4&\Mockery\MockInterface $crmApi */ $crmApi = \Mockery::mock(CrmApiV4::class); $cacheRepository = new ArrayCacheRepository(new ArrayStore()); - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); $hashKey = "crm_customer_hashcode_{$uuid->toString()}"; $emailKey = 'crm_customer_email_' . hash('sha256', 'cached@example.com'); diff --git a/tests/Integration/WithApp/App/Services/MailRegateServiceTest.php b/tests/Integration/WithApp/App/Services/MailRegateServiceTest.php index 047cbb50..59dda112 100644 --- a/tests/Integration/WithApp/App/Services/MailRegateServiceTest.php +++ b/tests/Integration/WithApp/App/Services/MailRegateServiceTest.php @@ -19,7 +19,7 @@ use Illuminate\Mail\PendingMail; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Mail; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('MailRegateService', function (): void { it('generates expected CSV rows and sends RegateOrderMail to configured regate address', function (): void { @@ -27,7 +27,7 @@ describe('MailRegateService', function (): void { Mail::fake(); Config::set('mail.to.regate', 'regate@example.com'); - $uuid = Uuid::uuid7(); + $uuid = UuidHelper::v7(); $reference = new OrderReference($uuid); $orderReferenceValue = (string) $reference; $employeeMatricule = new Matricule('1234567'); @@ -104,7 +104,7 @@ describe('MailRegateService', function (): void { // GIVEN Config::set('mail.to.regate', 'regate@example.com'); - $reference = new OrderReference(Uuid::uuid7()); + $reference = new OrderReference(UuidHelper::v7()); $employeeMatricule = new Matricule('1234567'); $pickupDay = CarbonImmutable::parse('2025-01-01'); diff --git a/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php b/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php index 0592e1f2..add14fea 100644 --- a/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php +++ b/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php @@ -23,7 +23,7 @@ use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Support\Facades\Date; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; covers(OrderOwnershipService::class); @@ -44,8 +44,8 @@ describe('OrderOwnershipService', function () { it('returns true if order is owned by customer', function () { // GIVEN $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('owner@example.com'), ]); @@ -64,8 +64,8 @@ describe('OrderOwnershipService', function () { ]); $order = Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), + 'id' => UuidHelper::v7()->toString(), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(1000, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -91,8 +91,8 @@ describe('OrderOwnershipService', function () { it('returns false if order is not owned by customer', function () { // GIVEN $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('notowner@example.com'), ]); @@ -111,8 +111,8 @@ describe('OrderOwnershipService', function () { ]); $order = Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), + 'id' => UuidHelper::v7()->toString(), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(1000, new Currency('EUR')), 'employee' => new OrderEmployee( @@ -138,14 +138,14 @@ describe('OrderOwnershipService', function () { it('returns false if customer has no employee', function () { // GIVEN $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('noemp@example.com'), ]); $order = Order::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), + 'id' => UuidHelper::v7()->toString(), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => new Money(1000, new Currency('EUR')), 'employee' => new OrderEmployee( diff --git a/tests/Integration/WithApp/App/Services/StatsServiceTest.php b/tests/Integration/WithApp/App/Services/StatsServiceTest.php index 08bf3ab5..e9758c92 100644 --- a/tests/Integration/WithApp/App/Services/StatsServiceTest.php +++ b/tests/Integration/WithApp/App/Services/StatsServiceTest.php @@ -34,7 +34,7 @@ use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Support\Facades\Date; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; covers(StatsService::class); @@ -80,8 +80,8 @@ describe('StatsService', function (): void { int $totalCents = 1000, ): Order { return Order::query()->forceCreate([ - 'id' => Uuid::uuid7($createdAt)->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), + 'id' => UuidHelper::v7($createdAt)->toString(), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => $status->value, 'total' => new Money($totalCents, new Currency('EUR')), 'pickup_day' => $pickupDay, @@ -103,8 +103,8 @@ describe('StatsService', function (): void { expect($service->getMembershipPercentage())->toBe(0.0); $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('member@example.com'), ]); $createEmployee(101, '1000101', $customer); @@ -126,8 +126,8 @@ describe('StatsService', function (): void { $inRange = $now->subDays(3); $outRange = $now->subDays(20); $customer1 = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('range1@example.com'), ]); $createEmployee(201, '1000201', $customer1, $inRange); @@ -152,8 +152,8 @@ describe('StatsService', function (): void { $service = new StatsService(new Currency('EUR')); $now = CarbonImmutable::now(); $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('stats@example.com'), ]); $createEmployee(301, '1000301', $customer, $now->subDays(3)); @@ -175,7 +175,7 @@ describe('StatsService', function (): void { $productVo = new OrderLineProduct( incoId: new IncoId(1), - originalId: new ProductId(Uuid::uuid7()), + originalId: new ProductId(UuidHelper::v7()), name: 'Poulet', weight: new ProductWeight(1000, false), brand: ProductBrand::loue, @@ -225,8 +225,8 @@ describe('StatsService', function (): void { $service = new StatsService(new Currency('EUR')); $now = CarbonImmutable::now(); $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('attempts-stats@example.com'), ]); diff --git a/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php index 33899d21..c0032a65 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php @@ -7,61 +7,63 @@ namespace Tests\Integration\WithApp\Infra\Adapters\Directories; use App\Models\Shop; use Domain\Models\ValueObjects\Entities\ShopId; use Infrastructure\Adapters\Directories\EloquentShopDirectory; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; -it('retrieves all available shops', function () { - // GIVEN - Shop::query()->forceCreate([ - 'name' => 'Shop 1', - 'address' => 'Addr 1', - 'postcode' => '75000', - 'city' => 'Paris', - 'default' => false, - ]); - Shop::query()->forceCreate([ - 'name' => 'Shop 2', - 'address' => 'Addr 2', - 'postcode' => '75001', - 'city' => 'Paris', - 'default' => false, - ]); - $directory = new EloquentShopDirectory(); +describe('EloquentShopDirectory', function (): void { + it('retrieves all available shops', function () { + // GIVEN + Shop::query()->forceCreate([ + 'name' => 'Shop 1', + 'address' => 'Addr 1', + 'postcode' => '75000', + 'city' => 'Paris', + 'default' => false, + ]); + Shop::query()->forceCreate([ + 'name' => 'Shop 2', + 'address' => 'Addr 2', + 'postcode' => '75001', + 'city' => 'Paris', + 'default' => false, + ]); + $directory = new EloquentShopDirectory(); - // WHEN - $shops = $directory->getAll(); + // WHEN + $shops = $directory->getAll(); - // THEN - expect($shops)->toHaveCount(2); -}); - -it('finds a shop by its identifier', function () { - // GIVEN - $model = Shop::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'name' => 'Shop X', - 'address' => 'Addr X', - 'postcode' => '75000', - 'city' => 'Paris', - 'default' => false, - ]); - $directory = new EloquentShopDirectory(); - - // WHEN - $shop = $directory->find(new ShopId(Uuid::fromString($model->id))); - - // THEN - expect($shop)->not->toBeNull() - ->and($shop?->id->value->toString())->toBe($model->id) - ->and($shop?->name)->toBe($model->name); -}); - -it('returns null if shop by id is not found', function () { - // GIVEN - $directory = new EloquentShopDirectory(); - - // WHEN - $shop = $directory->find(new ShopId(Uuid::uuid7())); - - // THEN - expect($shop)->toBeNull(); + // THEN + expect($shops)->toHaveCount(2); + }); + + it('finds a shop by its identifier', function () { + // GIVEN + $model = Shop::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'name' => 'Shop X', + 'address' => 'Addr X', + 'postcode' => '75000', + 'city' => 'Paris', + 'default' => false, + ]); + $directory = new EloquentShopDirectory(); + + // WHEN + $shop = $directory->find(new ShopId(UuidHelper::fromString($model->id))); + + // THEN + expect($shop)->not->toBeNull() + ->and($shop?->id->value->toString())->toBe($model->id) + ->and($shop?->name)->toBe($model->name); + }); + + it('returns null if shop by id is not found', function () { + // GIVEN + $directory = new EloquentShopDirectory(); + + // WHEN + $shop = $directory->find(new ShopId(UuidHelper::v7())); + + // THEN + expect($shop)->toBeNull(); + }); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php index 238fed0f..aa3d4154 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php @@ -10,144 +10,146 @@ use Domain\Models\Entities\Order as DomainOrder; use Domain\Models\ValueObjects\Entities\OrderId; use Illuminate\Support\Facades\DB; use Infrastructure\Adapters\Repositories\EloquentOrderRepository; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Webmozart\Assert\Assert; -it('returns null when finding a non-existent order by id', function () { - // GIVEN - $repo = new EloquentOrderRepository(); - $orderId = new OrderId(Uuid::fromString('018e4567-e89b-72d3-a456-426614174001')); +describe('EloquentOrderRepository', function (): void { + it('returns null when finding a non-existent order by id', function () { + // GIVEN + $repo = new EloquentOrderRepository(); + $orderId = new OrderId(UuidHelper::fromString('018e4567-e89b-72d3-a456-426614174001')); - // WHEN - $result = $repo->find($orderId); + // WHEN + $result = $repo->find($orderId); - // THEN - expect($result)->toBeNull(); -}); - -it('updates an existing order in the repository', function () { - // GIVEN - $shopId = Uuid::uuid7()->toString(); - DB::table('shops')->insertOrIgnore(['id' => $shopId, 'name' => 'Shop 1', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); - - DB::table('orders')->insert([ - 'id' => '018e4567-e89b-72d3-a456-426614174002', - 'shop_id' => $shopId, - 'reference' => Uuid::uuid7()->toString(), - 'employee' => json_encode([ - 'matricule' => '1234567', - 'firstname' => 'Jean', - 'lastname' => 'Dupont', - 'facility' => 'FAC01', - 'site' => 'HQ', - 'service' => '101', - ]), - 'delivery_address' => '{}', - 'pickup_day' => '2023-01-05', - 'status' => OrderStatus::WAITING->value, - 'total' => 1000, - ]); - - $repo = new EloquentOrderRepository(); - - $domainOrder = $repo->find(new OrderId(Uuid::fromString('018e4567-e89b-72d3-a456-426614174002'))); - Assert::isInstanceOf($domainOrder, DomainOrder::class); - $domainOrder->status = OrderStatus::VALIDATED; - - // WHEN - $repo->persist($domainOrder); - - // THEN - /** @var object{status: int}|null $updatedOrder */ - $updatedOrder = DB::table('orders')->where('id', '018e4567-e89b-72d3-a456-426614174002')->first(); - expect($updatedOrder?->status)->toBe(OrderStatus::VALIDATED->value); -}); - -it('finds an order for update inside a transaction', function (): void { - // GIVEN - $shopId = Uuid::uuid7()->toString(); - $orderId = Uuid::uuid7()->toString(); - DB::table('shops')->insertOrIgnore(['id' => $shopId, 'name' => 'Shop Lock', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); - DB::table('orders')->insert([ - 'id' => $orderId, - 'shop_id' => $shopId, - 'reference' => Uuid::uuid7()->toString(), - 'employee' => json_encode([ - 'matricule' => '1234567', - 'firstname' => 'Jean', - 'lastname' => 'Dupont', - 'facility' => 'FAC01', - 'site' => 'HQ', - 'service' => '101', - ]), - 'delivery_address' => '{}', - 'pickup_day' => '2026-11-20', - 'status' => OrderStatus::PENDING->value, - 'total' => 1000, - ]); - - $repo = new EloquentOrderRepository(); - - // WHEN - $found = DB::transaction(static fn () => $repo->findForUpdate(new OrderId(Uuid::fromString($orderId)))); - - // THEN - expect($found)->toBeInstanceOf(DomainOrder::class) - ->and($found?->status)->toBe(OrderStatus::PENDING); -}); - -it('returns only stale PENDING order ids older than cutoff', function (): void { - // GIVEN - $shopId = Uuid::uuid7()->toString(); - $staleId = Uuid::uuid7()->toString(); - $freshId = Uuid::uuid7()->toString(); - $staleWaiting = Uuid::uuid7()->toString(); - $now = CarbonImmutable::parse('2026-11-16 12:00:00', 'UTC'); - - DB::table('shops')->insertOrIgnore(['id' => $shopId, 'name' => 'Shop Stale', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); - - $baseRow = [ - 'shop_id' => $shopId, - 'employee' => json_encode([ - 'matricule' => '1234567', - 'firstname' => 'Jean', - 'lastname' => 'Dupont', - 'facility' => 'FAC01', - 'site' => 'HQ', - 'service' => '101', - ]), - 'delivery_address' => '{}', - 'pickup_day' => '2026-11-20', - 'total' => 1000, - ]; - - DB::table('orders')->insert([ - array_merge($baseRow, [ - 'id' => $staleId, - 'reference' => Uuid::uuid7()->toString(), - 'status' => OrderStatus::PENDING->value, - 'updated_at' => $now->subMinutes(15)->toDateTimeString(), - ]), - array_merge($baseRow, [ - 'id' => $freshId, - 'reference' => Uuid::uuid7()->toString(), - 'status' => OrderStatus::PENDING->value, - 'updated_at' => $now->subMinutes(5)->toDateTimeString(), - ]), - array_merge($baseRow, [ - 'id' => $staleWaiting, - 'reference' => Uuid::uuid7()->toString(), - 'status' => OrderStatus::WAITING->value, - 'updated_at' => $now->subMinutes(30)->toDateTimeString(), - ]), - ]); - - $repo = new EloquentOrderRepository(); - - // WHEN - $staleIds = $repo->findStalePendingOrderIds($now->subMinutes(10)); - - // THEN - expect($staleIds)->toHaveCount(1) - ->and($staleIds[0]->value->toString())->toBe($staleId); + // THEN + expect($result)->toBeNull(); + }); + + it('updates an existing order in the repository', function () { + // GIVEN + $shopId = UuidHelper::v7()->toString(); + DB::table('shops')->insertOrIgnore(['id' => $shopId, 'name' => 'Shop 1', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); + + DB::table('orders')->insert([ + 'id' => '018e4567-e89b-72d3-a456-426614174002', + 'shop_id' => $shopId, + 'reference' => UuidHelper::v7()->toString(), + 'employee' => json_encode([ + 'matricule' => '1234567', + 'firstname' => 'Jean', + 'lastname' => 'Dupont', + 'facility' => 'FAC01', + 'site' => 'HQ', + 'service' => '101', + ]), + 'delivery_address' => '{}', + 'pickup_day' => '2023-01-05', + 'status' => OrderStatus::WAITING->value, + 'total' => 1000, + ]); + + $repo = new EloquentOrderRepository(); + + $domainOrder = $repo->find(new OrderId(UuidHelper::fromString('018e4567-e89b-72d3-a456-426614174002'))); + Assert::isInstanceOf($domainOrder, DomainOrder::class); + $domainOrder->status = OrderStatus::VALIDATED; + + // WHEN + $repo->persist($domainOrder); + + // THEN + /** @var object{status: int}|null $updatedOrder */ + $updatedOrder = DB::table('orders')->where('id', '018e4567-e89b-72d3-a456-426614174002')->first(); + expect($updatedOrder?->status)->toBe(OrderStatus::VALIDATED->value); + }); + + it('finds an order for update inside a transaction', function (): void { + // GIVEN + $shopId = UuidHelper::v7()->toString(); + $orderId = UuidHelper::v7()->toString(); + DB::table('shops')->insertOrIgnore(['id' => $shopId, 'name' => 'Shop Lock', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); + DB::table('orders')->insert([ + 'id' => $orderId, + 'shop_id' => $shopId, + 'reference' => UuidHelper::v7()->toString(), + 'employee' => json_encode([ + 'matricule' => '1234567', + 'firstname' => 'Jean', + 'lastname' => 'Dupont', + 'facility' => 'FAC01', + 'site' => 'HQ', + 'service' => '101', + ]), + 'delivery_address' => '{}', + 'pickup_day' => '2026-11-20', + 'status' => OrderStatus::PENDING->value, + 'total' => 1000, + ]); + + $repo = new EloquentOrderRepository(); + + // WHEN + $found = DB::transaction(static fn () => $repo->findForUpdate(new OrderId(UuidHelper::fromString($orderId)))); + + // THEN + expect($found)->toBeInstanceOf(DomainOrder::class) + ->and($found?->status)->toBe(OrderStatus::PENDING); + }); + + it('returns only stale PENDING order ids older than cutoff', function (): void { + // GIVEN + $shopId = UuidHelper::v7()->toString(); + $staleId = UuidHelper::v7()->toString(); + $freshId = UuidHelper::v7()->toString(); + $staleWaiting = UuidHelper::v7()->toString(); + $now = CarbonImmutable::parse('2026-11-16 12:00:00', 'UTC'); + + DB::table('shops')->insertOrIgnore(['id' => $shopId, 'name' => 'Shop Stale', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); + + $baseRow = [ + 'shop_id' => $shopId, + 'employee' => json_encode([ + 'matricule' => '1234567', + 'firstname' => 'Jean', + 'lastname' => 'Dupont', + 'facility' => 'FAC01', + 'site' => 'HQ', + 'service' => '101', + ]), + 'delivery_address' => '{}', + 'pickup_day' => '2026-11-20', + 'total' => 1000, + ]; + + DB::table('orders')->insert([ + array_merge($baseRow, [ + 'id' => $staleId, + 'reference' => UuidHelper::v7()->toString(), + 'status' => OrderStatus::PENDING->value, + 'updated_at' => $now->subMinutes(15)->toDateTimeString(), + ]), + array_merge($baseRow, [ + 'id' => $freshId, + 'reference' => UuidHelper::v7()->toString(), + 'status' => OrderStatus::PENDING->value, + 'updated_at' => $now->subMinutes(5)->toDateTimeString(), + ]), + array_merge($baseRow, [ + 'id' => $staleWaiting, + 'reference' => UuidHelper::v7()->toString(), + 'status' => OrderStatus::WAITING->value, + 'updated_at' => $now->subMinutes(30)->toDateTimeString(), + ]), + ]); + + $repo = new EloquentOrderRepository(); + + // WHEN + $staleIds = $repo->findStalePendingOrderIds($now->subMinutes(10)); + + // THEN + expect($staleIds)->toHaveCount(1) + ->and($staleIds[0]->value->toString())->toBe($staleId); + }); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php index efaa9bc4..13a0d326 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php @@ -11,110 +11,112 @@ use Domain\Enums\RepeatFrequency; use Domain\Models\ValueObjects\Entities\ShopId; use Illuminate\Support\Facades\DB; use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; -it('retrieves exceptions within a period for a shop', function () { - // GIVEN - $shopUuid = Uuid::uuid7(); - $shop = Shop::query()->forceCreate([ - 'id' => $shopUuid->toString(), - 'name' => 'Shop 1', - 'postcode' => '75000', - 'city' => 'Paris', - 'address' => 'Addr', - ]); +describe('EloquentPickupExceptionRepository', function (): void { + it('retrieves exceptions within a period for a shop', function () { + // GIVEN + $shopUuid = UuidHelper::v7(); + $shop = Shop::query()->forceCreate([ + 'id' => $shopUuid->toString(), + 'name' => 'Shop 1', + 'postcode' => '75000', + 'city' => 'Paris', + 'address' => 'Addr', + ]); - $exUuid = Uuid::uuid7(); - $ex1 = PickupException::query()->forceCreate([ - 'id' => $exUuid->toString(), - 'date' => '2023-01-10', - 'label' => 'Fermé', - 'repeatable' => false, - 'repeat_frequency' => RepeatFrequency::WEEKLY->value, - 'auto_updated' => false, - ]); + $exUuid = UuidHelper::v7(); + $ex1 = PickupException::query()->forceCreate([ + 'id' => $exUuid->toString(), + 'date' => '2023-01-10', + 'label' => 'Fermé', + 'repeatable' => false, + 'repeat_frequency' => RepeatFrequency::WEEKLY->value, + 'auto_updated' => false, + ]); - DB::table('shop_pickup_exception')->insert([ - 'shop_id' => $shop->id, - 'pickup_exception_id' => $ex1->id, - 'replacement_date' => '2023-01-11', - 'order_deadline_at' => '2023-01-09 10:00:00', - ]); + DB::table('shop_pickup_exception')->insert([ + 'shop_id' => $shop->id, + 'pickup_exception_id' => $ex1->id, + 'replacement_date' => '2023-01-11', + 'order_deadline_at' => '2023-01-09 10:00:00', + ]); - $shopId = new ShopId($shopUuid); - $period = CarbonPeriod::create('2023-01-01', '2023-01-31'); + $shopId = new ShopId($shopUuid); + $period = CarbonPeriod::create('2023-01-01', '2023-01-31'); - $repo = new EloquentPickupExceptionRepository(); + $repo = new EloquentPickupExceptionRepository(); - // WHEN - $result = $repo->getExceptionsForShop($shopId, $period); + // WHEN + $result = $repo->getExceptionsForShop($shopId, $period); - // THEN - expect($result)->toHaveCount(1) - ->and($result[0]->exception->id->value->toString())->toBe($exUuid->toString()) - ->and($result[0]->replacementDate?->format('Y-m-d'))->toBe('2023-01-11') - ->and($result[0]->orderDeadlineAt?->format('Y-m-d H:i:s'))->toBe('2023-01-09 10:00:00'); -}); - -it('retrieves all exceptions', function () { - // GIVEN - $exUuid = Uuid::uuid7(); - PickupException::query()->forceCreate([ - 'id' => $exUuid->toString(), - 'date' => '2023-01-10', - 'label' => 'Fermé', - 'repeatable' => false, - 'repeat_frequency' => RepeatFrequency::WEEKLY->value, - 'auto_updated' => false, - ]); - - $repo = new EloquentPickupExceptionRepository(); - - // WHEN - $result = $repo->getAllExceptions(); - - // THEN - expect($result)->toHaveCount(1) - ->and($result[0]->id->value->toString())->toBe($exUuid->toString()); -}); - -it('retrieves exceptions associated with a shop', function () { - // GIVEN - $shopUuid = Uuid::uuid7(); - $shop = Shop::query()->forceCreate([ - 'id' => $shopUuid->toString(), - 'name' => 'Shop 1', - 'postcode' => '75000', - 'city' => 'Paris', - 'address' => 'Addr', - ]); - - $exUuid = Uuid::uuid7(); - $ex1 = PickupException::query()->forceCreate([ - 'id' => $exUuid->toString(), - 'date' => '2023-01-10', - 'label' => 'Fermé', - 'repeatable' => false, - 'repeat_frequency' => RepeatFrequency::WEEKLY->value, - 'auto_updated' => false, - ]); - - DB::table('shop_pickup_exception')->insert([ - 'shop_id' => $shop->id, - 'pickup_exception_id' => $ex1->id, - 'replacement_date' => '2023-01-11', - 'order_deadline_at' => '2023-01-09 10:00:00', - ]); - - $shopId = new ShopId($shopUuid); - - $repo = new EloquentPickupExceptionRepository(); - - // WHEN - $result = $repo->getExceptionsAssociatedWithShop($shopId); - - // THEN - expect($result)->toHaveCount(1) - ->and($result[0]->exception->id->value->toString())->toBe($exUuid->toString()) - ->and($result[0]->replacementDate?->format('Y-m-d'))->toBe('2023-01-11'); + // THEN + expect($result)->toHaveCount(1) + ->and($result[0]->exception->id->value->toString())->toBe($exUuid->toString()) + ->and($result[0]->replacementDate?->format('Y-m-d'))->toBe('2023-01-11') + ->and($result[0]->orderDeadlineAt?->format('Y-m-d H:i:s'))->toBe('2023-01-09 10:00:00'); + }); + + it('retrieves all exceptions', function () { + // GIVEN + $exUuid = UuidHelper::v7(); + PickupException::query()->forceCreate([ + 'id' => $exUuid->toString(), + 'date' => '2023-01-10', + 'label' => 'Fermé', + 'repeatable' => false, + 'repeat_frequency' => RepeatFrequency::WEEKLY->value, + 'auto_updated' => false, + ]); + + $repo = new EloquentPickupExceptionRepository(); + + // WHEN + $result = $repo->getAllExceptions(); + + // THEN + expect($result)->toHaveCount(1) + ->and($result[0]->id->value->toString())->toBe($exUuid->toString()); + }); + + it('retrieves exceptions associated with a shop', function () { + // GIVEN + $shopUuid = UuidHelper::v7(); + $shop = Shop::query()->forceCreate([ + 'id' => $shopUuid->toString(), + 'name' => 'Shop 1', + 'postcode' => '75000', + 'city' => 'Paris', + 'address' => 'Addr', + ]); + + $exUuid = UuidHelper::v7(); + $ex1 = PickupException::query()->forceCreate([ + 'id' => $exUuid->toString(), + 'date' => '2023-01-10', + 'label' => 'Fermé', + 'repeatable' => false, + 'repeat_frequency' => RepeatFrequency::WEEKLY->value, + 'auto_updated' => false, + ]); + + DB::table('shop_pickup_exception')->insert([ + 'shop_id' => $shop->id, + 'pickup_exception_id' => $ex1->id, + 'replacement_date' => '2023-01-11', + 'order_deadline_at' => '2023-01-09 10:00:00', + ]); + + $shopId = new ShopId($shopUuid); + + $repo = new EloquentPickupExceptionRepository(); + + // WHEN + $result = $repo->getExceptionsAssociatedWithShop($shopId); + + // THEN + expect($result)->toHaveCount(1) + ->and($result[0]->exception->id->value->toString())->toBe($exUuid->toString()) + ->and($result[0]->replacementDate?->format('Y-m-d'))->toBe('2023-01-11'); + }); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php index 80836375..def8aca2 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php @@ -14,7 +14,7 @@ use Illuminate\Support\Facades\DB; use Infrastructure\Adapters\Repositories\EloquentProductRepository; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; function createRepoTestProductRange(): int { @@ -28,234 +28,236 @@ function createRepoTestProductRange(): int return $range->id; } -it('retrieves a basket product', function () { - // GIVEN - $uuid = Uuid::uuid7()->toString(); - $currency = new Currency('EUR'); - $rangeId = createRepoTestProductRange(); +describe('EloquentProductRepository', function (): void { + it('retrieves a basket product', function () { + // GIVEN + $uuid = UuidHelper::v7()->toString(); + $currency = new Currency('EUR'); + $rangeId = createRepoTestProductRange(); - Product::query()->forceCreate([ - 'id' => $uuid, - 'name' => 'Product Name', - 'tax_rate' => 1, - 'weight' => 1000, - 'brand' => 'none', - 'order_unit' => OrderUnit::PCE->value, - 'invoicing_unit' => 'PCE', - 'sell_unit' => 'PCE', - 'range_id' => $rangeId, - 'slug' => 'product-name', - 'picture' => 'pic.jpg', - 'picture_alt' => '', - 'picture_title' => '', - 'picture_large_alt' => '', - 'picture_large_title' => '', - 'description' => 'Desc', - 'weight_variable' => false, - 'status' => 1, - 'price' => new Money(100, $currency), - ]); - DB::table('product_incos')->insert(['product_id' => $uuid, 'no_art' => 12345]); + Product::query()->forceCreate([ + 'id' => $uuid, + 'name' => 'Product Name', + 'tax_rate' => 1, + 'weight' => 1000, + 'brand' => 'none', + 'order_unit' => OrderUnit::PCE->value, + 'invoicing_unit' => 'PCE', + 'sell_unit' => 'PCE', + 'range_id' => $rangeId, + 'slug' => 'product-name', + 'picture' => 'pic.jpg', + 'picture_alt' => '', + 'picture_title' => '', + 'picture_large_alt' => '', + 'picture_large_title' => '', + 'description' => 'Desc', + 'weight_variable' => false, + 'status' => 1, + 'price' => new Money(100, $currency), + ]); + DB::table('product_incos')->insert(['product_id' => $uuid, 'no_art' => 12345]); - $id = new ProductId(Uuid::fromString($uuid)); + $id = new ProductId(UuidHelper::fromString($uuid)); - $repo = new EloquentProductRepository(); + $repo = new EloquentProductRepository(); - // WHEN - $result = $repo->getBasketProduct($id, 2); + // WHEN + $result = $repo->getBasketProduct($id, 2); - // THEN - expect($result->name)->toBe('Product Name') - ->and($result->qty)->toBe(2); -}); - -it('throws UnorderableProductException when retrieving a basket product without inco', function (): void { - // GIVEN - $uuid = Uuid::uuid7()->toString(); - $currency = new Currency('EUR'); - $rangeId = createRepoTestProductRange(); - - Product::query()->forceCreate([ - 'id' => $uuid, - 'name' => 'Product Without Inco', - 'tax_rate' => 1, - 'weight' => 1000, - 'brand' => 'none', - 'order_unit' => OrderUnit::PCE->value, - 'invoicing_unit' => 'PCE', - 'sell_unit' => 'PCE', - 'range_id' => $rangeId, - 'slug' => 'product-without-inco', - 'picture' => 'pic.jpg', - 'picture_alt' => '', - 'picture_title' => '', - 'picture_large_alt' => '', - 'picture_large_title' => '', - 'description' => 'Desc', - 'weight_variable' => false, - 'status' => 1, - 'price' => new Money(100, $currency), - ]); - - $id = new ProductId(Uuid::fromString($uuid)); - $repo = new EloquentProductRepository(); - - // WHEN - $action = fn () => $repo->getBasketProduct($id, 1); - - // THEN - expect($action)->toThrow(UnorderableProductException::class); -}); - -it('throws UnorderableProductException when retrieving an unpublished basket product', function (): void { - // GIVEN - $uuid = Uuid::uuid7()->toString(); - $currency = new Currency('EUR'); - $rangeId = createRepoTestProductRange(); - - Product::query()->forceCreate([ - 'id' => $uuid, - 'name' => 'Unpublished Product', - 'tax_rate' => 1, - 'weight' => 1000, - 'brand' => 'none', - 'order_unit' => OrderUnit::PCE->value, - 'invoicing_unit' => 'PCE', - 'sell_unit' => 'PCE', - 'range_id' => $rangeId, - 'slug' => 'unpublished-product', - 'picture' => 'pic.jpg', - 'picture_alt' => '', - 'picture_title' => '', - 'picture_large_alt' => '', - 'picture_large_title' => '', - 'description' => 'Desc', - 'weight_variable' => false, - 'status' => 0, - 'price' => new Money(100, $currency), - ]); - DB::table('product_incos')->insert(['product_id' => $uuid, 'no_art' => 12345]); - - $id = new ProductId(Uuid::fromString($uuid)); - $repo = new EloquentProductRepository(); - - // WHEN - $action = fn () => $repo->getBasketProduct($id, 1); - - // THEN - expect($action)->toThrow(UnorderableProductException::class); -}); - -it('throws UnorderableProductException when retrieving a basket product outside orderable dates', function (): void { - // GIVEN - $expiredUuid = Uuid::uuid7()->toString(); - $futureUuid = Uuid::uuid7()->toString(); - $currency = new Currency('EUR'); - $rangeId = createRepoTestProductRange(); - - Product::query()->forceCreate([ - 'id' => $expiredUuid, - 'name' => 'Expired Product', - 'tax_rate' => 1, - 'weight' => 1000, - 'brand' => 'none', - 'order_unit' => OrderUnit::PCE->value, - 'invoicing_unit' => 'PCE', - 'sell_unit' => 'PCE', - 'range_id' => $rangeId, - 'slug' => 'expired-product', - 'picture' => 'pic.jpg', - 'picture_alt' => '', - 'picture_title' => '', - 'picture_large_alt' => '', - 'picture_large_title' => '', - 'description' => 'Desc', - 'weight_variable' => false, - 'status' => 1, - 'orderable_end' => now()->subDay(), - 'price' => new Money(100, $currency), - ]); - DB::table('product_incos')->insert(['product_id' => $expiredUuid, 'no_art' => 12345]); - - Product::query()->forceCreate([ - 'id' => $futureUuid, - 'name' => 'Future Product', - 'tax_rate' => 1, - 'weight' => 1000, - 'brand' => 'none', - 'order_unit' => OrderUnit::PCE->value, - 'invoicing_unit' => 'PCE', - 'sell_unit' => 'PCE', - 'range_id' => $rangeId, - 'slug' => 'future-product', - 'picture' => 'pic.jpg', - 'picture_alt' => '', - 'picture_title' => '', - 'picture_large_alt' => '', - 'picture_large_title' => '', - 'description' => 'Desc', - 'weight_variable' => false, - 'status' => 1, - 'orderable_start' => now()->addDay(), - 'price' => new Money(100, $currency), - ]); - DB::table('product_incos')->insert(['product_id' => $futureUuid, 'no_art' => 12346]); - - $repo = new EloquentProductRepository(); - - // WHEN - $expiredAction = fn () => $repo->getBasketProduct(new ProductId(Uuid::fromString($expiredUuid)), 1); - $futureAction = fn () => $repo->getBasketProduct(new ProductId(Uuid::fromString($futureUuid)), 1); - - // THEN - expect($expiredAction)->toThrow(UnorderableProductException::class) - ->and($futureAction)->toThrow(UnorderableProductException::class); -}); - -it('finds a product by id', function () { - // GIVEN - $uuid = Uuid::uuid7()->toString(); - $rangeId = createRepoTestProductRange(); - - Product::query()->forceCreate([ - 'id' => $uuid, - 'name' => 'Product Name', - 'tax_rate' => 1, - 'weight' => 1000, - 'brand' => 'none', - 'slug' => 'product-name', - 'invoicing_unit' => 'PCE', - 'sell_unit' => 'PCE', - 'range_id' => $rangeId, - 'picture_alt' => '', - 'picture_title' => '', - 'picture_large_alt' => '', - 'picture_large_title' => '', - 'description' => '', - 'status' => 1, - 'price' => new Money(100, new Currency('EUR')), - ]); - - $id = new ProductId(Uuid::fromString($uuid)); - - $repo = new EloquentProductRepository(); - - // WHEN - $result = $repo->find($id); - - // THEN - expect($result)->toBeInstanceOf(DomainProduct::class); -}); - -it('returns null if product by id is not found', function () { - // GIVEN - $id = new ProductId(Uuid::uuid7()); - - $repo = new EloquentProductRepository(); - - // WHEN - $result = $repo->find($id); - - // THEN - expect($result)->toBeNull(); + // THEN + expect($result->name)->toBe('Product Name') + ->and($result->qty)->toBe(2); + }); + + it('throws UnorderableProductException when retrieving a basket product without inco', function (): void { + // GIVEN + $uuid = UuidHelper::v7()->toString(); + $currency = new Currency('EUR'); + $rangeId = createRepoTestProductRange(); + + Product::query()->forceCreate([ + 'id' => $uuid, + 'name' => 'Product Without Inco', + 'tax_rate' => 1, + 'weight' => 1000, + 'brand' => 'none', + 'order_unit' => OrderUnit::PCE->value, + 'invoicing_unit' => 'PCE', + 'sell_unit' => 'PCE', + 'range_id' => $rangeId, + 'slug' => 'product-without-inco', + 'picture' => 'pic.jpg', + 'picture_alt' => '', + 'picture_title' => '', + 'picture_large_alt' => '', + 'picture_large_title' => '', + 'description' => 'Desc', + 'weight_variable' => false, + 'status' => 1, + 'price' => new Money(100, $currency), + ]); + + $id = new ProductId(UuidHelper::fromString($uuid)); + $repo = new EloquentProductRepository(); + + // WHEN + $action = fn () => $repo->getBasketProduct($id, 1); + + // THEN + expect($action)->toThrow(UnorderableProductException::class); + }); + + it('throws UnorderableProductException when retrieving an unpublished basket product', function (): void { + // GIVEN + $uuid = UuidHelper::v7()->toString(); + $currency = new Currency('EUR'); + $rangeId = createRepoTestProductRange(); + + Product::query()->forceCreate([ + 'id' => $uuid, + 'name' => 'Unpublished Product', + 'tax_rate' => 1, + 'weight' => 1000, + 'brand' => 'none', + 'order_unit' => OrderUnit::PCE->value, + 'invoicing_unit' => 'PCE', + 'sell_unit' => 'PCE', + 'range_id' => $rangeId, + 'slug' => 'unpublished-product', + 'picture' => 'pic.jpg', + 'picture_alt' => '', + 'picture_title' => '', + 'picture_large_alt' => '', + 'picture_large_title' => '', + 'description' => 'Desc', + 'weight_variable' => false, + 'status' => 0, + 'price' => new Money(100, $currency), + ]); + DB::table('product_incos')->insert(['product_id' => $uuid, 'no_art' => 12345]); + + $id = new ProductId(UuidHelper::fromString($uuid)); + $repo = new EloquentProductRepository(); + + // WHEN + $action = fn () => $repo->getBasketProduct($id, 1); + + // THEN + expect($action)->toThrow(UnorderableProductException::class); + }); + + it('throws UnorderableProductException when retrieving a basket product outside orderable dates', function (): void { + // GIVEN + $expiredUuid = UuidHelper::v7()->toString(); + $futureUuid = UuidHelper::v7()->toString(); + $currency = new Currency('EUR'); + $rangeId = createRepoTestProductRange(); + + Product::query()->forceCreate([ + 'id' => $expiredUuid, + 'name' => 'Expired Product', + 'tax_rate' => 1, + 'weight' => 1000, + 'brand' => 'none', + 'order_unit' => OrderUnit::PCE->value, + 'invoicing_unit' => 'PCE', + 'sell_unit' => 'PCE', + 'range_id' => $rangeId, + 'slug' => 'expired-product', + 'picture' => 'pic.jpg', + 'picture_alt' => '', + 'picture_title' => '', + 'picture_large_alt' => '', + 'picture_large_title' => '', + 'description' => 'Desc', + 'weight_variable' => false, + 'status' => 1, + 'orderable_end' => now()->subDay(), + 'price' => new Money(100, $currency), + ]); + DB::table('product_incos')->insert(['product_id' => $expiredUuid, 'no_art' => 12345]); + + Product::query()->forceCreate([ + 'id' => $futureUuid, + 'name' => 'Future Product', + 'tax_rate' => 1, + 'weight' => 1000, + 'brand' => 'none', + 'order_unit' => OrderUnit::PCE->value, + 'invoicing_unit' => 'PCE', + 'sell_unit' => 'PCE', + 'range_id' => $rangeId, + 'slug' => 'future-product', + 'picture' => 'pic.jpg', + 'picture_alt' => '', + 'picture_title' => '', + 'picture_large_alt' => '', + 'picture_large_title' => '', + 'description' => 'Desc', + 'weight_variable' => false, + 'status' => 1, + 'orderable_start' => now()->addDay(), + 'price' => new Money(100, $currency), + ]); + DB::table('product_incos')->insert(['product_id' => $futureUuid, 'no_art' => 12346]); + + $repo = new EloquentProductRepository(); + + // WHEN + $expiredAction = fn () => $repo->getBasketProduct(new ProductId(UuidHelper::fromString($expiredUuid)), 1); + $futureAction = fn () => $repo->getBasketProduct(new ProductId(UuidHelper::fromString($futureUuid)), 1); + + // THEN + expect($expiredAction)->toThrow(UnorderableProductException::class) + ->and($futureAction)->toThrow(UnorderableProductException::class); + }); + + it('finds a product by id', function () { + // GIVEN + $uuid = UuidHelper::v7()->toString(); + $rangeId = createRepoTestProductRange(); + + Product::query()->forceCreate([ + 'id' => $uuid, + 'name' => 'Product Name', + 'tax_rate' => 1, + 'weight' => 1000, + 'brand' => 'none', + 'slug' => 'product-name', + 'invoicing_unit' => 'PCE', + 'sell_unit' => 'PCE', + 'range_id' => $rangeId, + 'picture_alt' => '', + 'picture_title' => '', + 'picture_large_alt' => '', + 'picture_large_title' => '', + 'description' => '', + 'status' => 1, + 'price' => new Money(100, new Currency('EUR')), + ]); + + $id = new ProductId(UuidHelper::fromString($uuid)); + + $repo = new EloquentProductRepository(); + + // WHEN + $result = $repo->find($id); + + // THEN + expect($result)->toBeInstanceOf(DomainProduct::class); + }); + + it('returns null if product by id is not found', function () { + // GIVEN + $id = new ProductId(UuidHelper::v7()); + + $repo = new EloquentProductRepository(); + + // WHEN + $result = $repo->find($id); + + // THEN + expect($result)->toBeNull(); + }); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php index d8c6c75a..7cbb58d4 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopRepositoryTest.php @@ -14,182 +14,184 @@ use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Support\Facades\DB; use Infrastructure\Adapters\Repositories\EloquentShopRepository; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; -it('finds exception shop for a matricule', function () { - // GIVEN - $shop = Shop::query()->forceCreate([ - 'name' => 'Shop X', - 'address' => 'Addr X', - 'postcode' => '75000', - 'city' => 'Paris', - 'default' => false, - ]); +describe('EloquentShopRepository', function (): void { + it('finds exception shop for a matricule', function () { + // GIVEN + $shop = Shop::query()->forceCreate([ + 'name' => 'Shop X', + 'address' => 'Addr X', + 'postcode' => '75000', + 'city' => 'Paris', + 'default' => false, + ]); - Employee::query()->forceCreate([ - 'matricule' => new Matricule('1234567'), - 'nom' => 'Doe', - 'prenom' => 'John', - 'etablissement' => 'ETAB', - 'site' => 'SITE', - 'service' => '101', - 'code' => new Code('ABCDEFGH'), - ]); - DB::table('shop_employee_exception')->insert([ - 'matricule' => '1234567', - 'shop_id' => $shop->id, - ]); + Employee::query()->forceCreate([ + 'matricule' => new Matricule('1234567'), + 'nom' => 'Doe', + 'prenom' => 'John', + 'etablissement' => 'ETAB', + 'site' => 'SITE', + 'service' => '101', + 'code' => new Code('ABCDEFGH'), + ]); + DB::table('shop_employee_exception')->insert([ + 'matricule' => '1234567', + 'shop_id' => $shop->id, + ]); - $repo = new EloquentShopRepository(); + $repo = new EloquentShopRepository(); - // WHEN - $result = $repo->findExceptionShopFor(new Matricule('1234567')); + // WHEN + $result = $repo->findExceptionShopFor(new Matricule('1234567')); - // THEN - expect($result)->not->toBeNull() - ->and($result?->id->value->toString())->toBe($shop->id); -}); - -it('returns null if exception shop is not found', function () { - // GIVEN - $repo = new EloquentShopRepository(); - - // WHEN - $result = $repo->findExceptionShopFor(new Matricule('9999999')); - - // THEN - expect($result)->toBeNull(); -}); - -it('finds shop for site and service', function () { - // GIVEN - $shop = Shop::query()->forceCreate([ - 'name' => 'Shop Y', - 'address' => 'Addr Y', - 'postcode' => '75000', - 'city' => 'Paris', - 'default' => false, - ]); - - DB::table('shop_employees')->insert([ - 'site_code' => 'PA', - 'service_code' => '101', - 'shop_id' => $shop->id, - ]); - - $repo = new EloquentShopRepository(); - - // WHEN - $result = $repo->findShopForSiteAndService(new ShopperSiteCode('PA'), new ShopperServiceCode('101')); - - // THEN - expect($result)->not->toBeNull() - ->and($result?->id->value->toString())->toBe($shop->id); -}); - -it('finds shop for site and null service', function () { - // GIVEN - $shop = Shop::query()->forceCreate([ - 'name' => 'Shop Z', - 'address' => 'Addr Z', - 'postcode' => '75000', - 'city' => 'Paris', - 'default' => false, - ]); - - DB::table('shop_employees')->insert([ - 'site_code' => 'LY', - 'service_code' => null, - 'shop_id' => $shop->id, - ]); - - $repo = new EloquentShopRepository(); - - // WHEN - $result = $repo->findShopForSiteAndService(new ShopperSiteCode('LY'), null); - - // THEN - expect($result)->not->toBeNull() - ->and($result?->id->value->toString())->toBe($shop->id); -}); - -it('returns null if shop for site and service is not found', function () { - // GIVEN - $repo = new EloquentShopRepository(); - - // WHEN - $result = $repo->findShopForSiteAndService(new ShopperSiteCode('ZZ'), new ShopperServiceCode('999')); - - // THEN - expect($result)->toBeNull(); -}); - -it('finds shop by id', function () { - // GIVEN - $shop = Shop::query()->forceCreate([ - 'name' => 'Shop 1', - 'address' => 'Addr 1', - 'postcode' => '75000', - 'city' => 'Paris', - 'default' => false, - ]); - - $repo = new EloquentShopRepository(); - - // WHEN - $result = $repo->find(new ShopId(Uuid::fromString($shop->id))); - - // THEN - expect($result)->not->toBeNull() - ->and($result?->id->value->toString())->toBe($shop->id); -}); - -it('returns null if shop by id is not found', function () { - // GIVEN - $repo = new EloquentShopRepository(); - - // WHEN - $result = $repo->find(new ShopId(Uuid::uuid7())); - - // THEN - expect($result)->toBeNull(); -}); - -it('retrieves default shop', function () { - // GIVEN - Shop::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'name' => 'Shop 1', - 'address' => 'Addr 1', - 'postcode' => '75000', - 'city' => 'Paris', - 'default' => false, - ]); - $defaultShop = Shop::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'name' => 'Shop Default', - 'address' => 'Addr Default', - 'postcode' => '75000', - 'city' => 'Paris', - 'default' => true, - ]); - - $repo = new EloquentShopRepository(); - - // WHEN - $result = $repo->getDefaultShop(); - - // THEN - expect($result->id->value->toString())->toBe($defaultShop->id); -}); - -it('throws exception if default shop is not found', function () { - // GIVEN - $repo = new EloquentShopRepository(); - - // WHEN - $action = fn () => $repo->getDefaultShop(); - - // THEN - expect($action)->toThrow(ModelNotFoundException::class); + // THEN + expect($result)->not->toBeNull() + ->and($result?->id->value->toString())->toBe($shop->id); + }); + + it('returns null if exception shop is not found', function () { + // GIVEN + $repo = new EloquentShopRepository(); + + // WHEN + $result = $repo->findExceptionShopFor(new Matricule('9999999')); + + // THEN + expect($result)->toBeNull(); + }); + + it('finds shop for site and service', function () { + // GIVEN + $shop = Shop::query()->forceCreate([ + 'name' => 'Shop Y', + 'address' => 'Addr Y', + 'postcode' => '75000', + 'city' => 'Paris', + 'default' => false, + ]); + + DB::table('shop_employees')->insert([ + 'site_code' => 'PA', + 'service_code' => '101', + 'shop_id' => $shop->id, + ]); + + $repo = new EloquentShopRepository(); + + // WHEN + $result = $repo->findShopForSiteAndService(new ShopperSiteCode('PA'), new ShopperServiceCode('101')); + + // THEN + expect($result)->not->toBeNull() + ->and($result?->id->value->toString())->toBe($shop->id); + }); + + it('finds shop for site and null service', function () { + // GIVEN + $shop = Shop::query()->forceCreate([ + 'name' => 'Shop Z', + 'address' => 'Addr Z', + 'postcode' => '75000', + 'city' => 'Paris', + 'default' => false, + ]); + + DB::table('shop_employees')->insert([ + 'site_code' => 'LY', + 'service_code' => null, + 'shop_id' => $shop->id, + ]); + + $repo = new EloquentShopRepository(); + + // WHEN + $result = $repo->findShopForSiteAndService(new ShopperSiteCode('LY'), null); + + // THEN + expect($result)->not->toBeNull() + ->and($result?->id->value->toString())->toBe($shop->id); + }); + + it('returns null if shop for site and service is not found', function () { + // GIVEN + $repo = new EloquentShopRepository(); + + // WHEN + $result = $repo->findShopForSiteAndService(new ShopperSiteCode('ZZ'), new ShopperServiceCode('999')); + + // THEN + expect($result)->toBeNull(); + }); + + it('finds shop by id', function () { + // GIVEN + $shop = Shop::query()->forceCreate([ + 'name' => 'Shop 1', + 'address' => 'Addr 1', + 'postcode' => '75000', + 'city' => 'Paris', + 'default' => false, + ]); + + $repo = new EloquentShopRepository(); + + // WHEN + $result = $repo->find(new ShopId(UuidHelper::fromString($shop->id))); + + // THEN + expect($result)->not->toBeNull() + ->and($result?->id->value->toString())->toBe($shop->id); + }); + + it('returns null if shop by id is not found', function () { + // GIVEN + $repo = new EloquentShopRepository(); + + // WHEN + $result = $repo->find(new ShopId(UuidHelper::v7())); + + // THEN + expect($result)->toBeNull(); + }); + + it('retrieves default shop', function () { + // GIVEN + Shop::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'name' => 'Shop 1', + 'address' => 'Addr 1', + 'postcode' => '75000', + 'city' => 'Paris', + 'default' => false, + ]); + $defaultShop = Shop::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'name' => 'Shop Default', + 'address' => 'Addr Default', + 'postcode' => '75000', + 'city' => 'Paris', + 'default' => true, + ]); + + $repo = new EloquentShopRepository(); + + // WHEN + $result = $repo->getDefaultShop(); + + // THEN + expect($result->id->value->toString())->toBe($defaultShop->id); + }); + + it('throws exception if default shop is not found', function () { + // GIVEN + $repo = new EloquentShopRepository(); + + // WHEN + $action = fn () => $repo->getDefaultShop(); + + // THEN + expect($action)->toThrow(ModelNotFoundException::class); + }); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php index b4fa6011..b98a438c 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentShopperRepositoryTest.php @@ -16,164 +16,166 @@ use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Infrastructure\Adapters\Repositories\EloquentShopperRepository; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; -it('retrieves shopper by id', function () { - // GIVEN - $uuid = Uuid::uuid7()->toString(); +describe('EloquentShopperRepository', function (): void { + it('retrieves shopper by id', function () { + // GIVEN + $uuid = UuidHelper::v7()->toString(); - Customer::query()->forceCreate([ - 'id' => $uuid, - 'email' => new Email('test@example.com'), - 'hashcode' => Uuid::uuid4()->toString(), - ]); + Customer::query()->forceCreate([ + 'id' => $uuid, + 'email' => new Email('test@example.com'), + 'hashcode' => UuidHelper::v4()->toString(), + ]); - Employee::query()->forceCreate([ - 'customer_id' => $uuid, - 'matricule' => new Matricule('1234567'), - 'nom' => 'Doe', - 'prenom' => 'John', - 'etablissement' => 'ETAB', - 'site' => 'SITE', - 'service' => '101', - 'code' => new Code('ABCDEFGH'), - ]); + Employee::query()->forceCreate([ + 'customer_id' => $uuid, + 'matricule' => new Matricule('1234567'), + 'nom' => 'Doe', + 'prenom' => 'John', + 'etablissement' => 'ETAB', + 'site' => 'SITE', + 'service' => '101', + 'code' => new Code('ABCDEFGH'), + ]); - $repo = new EloquentShopperRepository(); + $repo = new EloquentShopperRepository(); - // WHEN - $result = $repo->find(new ShopperId(Uuid::fromString($uuid))); + // WHEN + $result = $repo->find(new ShopperId(UuidHelper::fromString($uuid))); - // THEN - expect($result)->toBeInstanceOf(Shopper::class) - ->and($result?->email->value)->toBe('test@example.com'); -}); - -it('returns null if shopper not found by id', function () { - // GIVEN - $repo = new EloquentShopperRepository(); - - // WHEN - $result = $repo->find(new ShopperId(Uuid::uuid7())); - - // THEN - expect($result)->toBeNull(); -}); - -it('returns null if customer exists but has no employee', function () { - // GIVEN - $uuid = Uuid::uuid7()->toString(); - - Customer::query()->forceCreate([ - 'id' => $uuid, - 'email' => new Email('test@example.com'), - 'hashcode' => Uuid::uuid4()->toString(), - ]); - - $repo = new EloquentShopperRepository(); - - // WHEN - $result = $repo->find(new ShopperId(Uuid::fromString($uuid))); - - // THEN - expect($result)->toBeNull(); -}); - -it('retrieves shopper by id or fails', function () { - // GIVEN - $uuid = Uuid::uuid7()->toString(); - - Customer::query()->forceCreate([ - 'id' => $uuid, - 'email' => new Email('test@example.com'), - 'hashcode' => Uuid::uuid4()->toString(), - ]); - - Employee::query()->forceCreate([ - 'customer_id' => $uuid, - 'matricule' => new Matricule('1234569'), - 'nom' => 'Doe', - 'prenom' => 'John', - 'etablissement' => 'ETAB', - 'site' => 'SITE', - 'service' => '101', - 'code' => new Code('ABCDEFGH'), - ]); - - $repo = new EloquentShopperRepository(); - - // WHEN - $result = $repo->getByIdOrFail(new ShopperId(Uuid::fromString($uuid))); - - // THEN - expect($result->id()->value->toString())->toBe($uuid) - ->and($result->matricule->value)->toBe('1234569'); -}); - -it('throws exception if shopper not found in getByIdOrFail', function () { - // GIVEN - $repo = new EloquentShopperRepository(); - $id = Uuid::uuid7(); - - // WHEN - $action = fn () => $repo->getByIdOrFail(new ShopperId($id)); - - // THEN - expect($action)->toThrow(\DomainException::class, "Shopper with id '{$id->toString()}' not found or is not linked to any employee."); -}); - -it('persists updates to both customer and associated employee', function () { - // GIVEN - $uuid = Uuid::uuid7()->toString(); - $shopperId = new ShopperId(Uuid::fromString($uuid)); - - Customer::query()->forceCreate([ - 'id' => $uuid, - 'email' => new Email('before@example.com'), - 'hashcode' => Uuid::uuid4()->toString(), - ]); - - Employee::query()->forceCreate([ - 'customer_id' => $uuid, - 'matricule' => new Matricule('1234567'), - 'nom' => 'Doe', - 'prenom' => 'John', - 'start_date' => '2026-01-01', - 'end_date' => null, - 'etablissement' => 'ETAB01', - 'site' => 'SITE', - 'service' => '101', - 'code' => new Code('ABCDEFGH'), - ]); - - $repo = new EloquentShopperRepository(); - $updatedShopper = new Shopper( - id: $shopperId, - email: new Email('after@example.com'), - matricule: new Matricule('7654321'), - nom: 'Martin', - prenom: 'Claire', - startDate: CarbonImmutable::parse('2026-02-01'), - endDate: CarbonImmutable::parse('2026-12-31'), - etablissement: new ShopperEstablishmentCode('ETAB02'), - site: new ShopperSiteCode('PA'), - service: new ShopperServiceCode('202'), - ); - - // WHEN - $repo->persist($updatedShopper); - - // THEN - $reloaded = $repo->find($shopperId); - - expect($reloaded)->toBeInstanceOf(Shopper::class) - ->and($reloaded?->email->value)->toBe('after@example.com') - ->and($reloaded?->matricule->value)->toBe('7654321') - ->and($reloaded?->nom)->toBe('Martin') - ->and($reloaded?->prenom)->toBe('Claire') - ->and($reloaded?->startDate->format('Y-m-d'))->toBe('2026-02-01') - ->and($reloaded?->endDate?->format('Y-m-d'))->toBe('2026-12-31') - ->and($reloaded?->etablissement->value)->toBe('ETAB02') - ->and($reloaded?->site->value)->toBe('PA') - ->and($reloaded?->service->value)->toBe('202'); + // THEN + expect($result)->toBeInstanceOf(Shopper::class) + ->and($result?->email->value)->toBe('test@example.com'); + }); + + it('returns null if shopper not found by id', function () { + // GIVEN + $repo = new EloquentShopperRepository(); + + // WHEN + $result = $repo->find(new ShopperId(UuidHelper::v7())); + + // THEN + expect($result)->toBeNull(); + }); + + it('returns null if customer exists but has no employee', function () { + // GIVEN + $uuid = UuidHelper::v7()->toString(); + + Customer::query()->forceCreate([ + 'id' => $uuid, + 'email' => new Email('test@example.com'), + 'hashcode' => UuidHelper::v4()->toString(), + ]); + + $repo = new EloquentShopperRepository(); + + // WHEN + $result = $repo->find(new ShopperId(UuidHelper::fromString($uuid))); + + // THEN + expect($result)->toBeNull(); + }); + + it('retrieves shopper by id or fails', function () { + // GIVEN + $uuid = UuidHelper::v7()->toString(); + + Customer::query()->forceCreate([ + 'id' => $uuid, + 'email' => new Email('test@example.com'), + 'hashcode' => UuidHelper::v4()->toString(), + ]); + + Employee::query()->forceCreate([ + 'customer_id' => $uuid, + 'matricule' => new Matricule('1234569'), + 'nom' => 'Doe', + 'prenom' => 'John', + 'etablissement' => 'ETAB', + 'site' => 'SITE', + 'service' => '101', + 'code' => new Code('ABCDEFGH'), + ]); + + $repo = new EloquentShopperRepository(); + + // WHEN + $result = $repo->getByIdOrFail(new ShopperId(UuidHelper::fromString($uuid))); + + // THEN + expect($result->id()->value->toString())->toBe($uuid) + ->and($result->matricule->value)->toBe('1234569'); + }); + + it('throws exception if shopper not found in getByIdOrFail', function () { + // GIVEN + $repo = new EloquentShopperRepository(); + $id = UuidHelper::v7(); + + // WHEN + $action = fn () => $repo->getByIdOrFail(new ShopperId($id)); + + // THEN + expect($action)->toThrow(\DomainException::class, "Shopper with id '{$id->toString()}' not found or is not linked to any employee."); + }); + + it('persists updates to both customer and associated employee', function () { + // GIVEN + $uuid = UuidHelper::v7()->toString(); + $shopperId = new ShopperId(UuidHelper::fromString($uuid)); + + Customer::query()->forceCreate([ + 'id' => $uuid, + 'email' => new Email('before@example.com'), + 'hashcode' => UuidHelper::v4()->toString(), + ]); + + Employee::query()->forceCreate([ + 'customer_id' => $uuid, + 'matricule' => new Matricule('1234567'), + 'nom' => 'Doe', + 'prenom' => 'John', + 'start_date' => '2026-01-01', + 'end_date' => null, + 'etablissement' => 'ETAB01', + 'site' => 'SITE', + 'service' => '101', + 'code' => new Code('ABCDEFGH'), + ]); + + $repo = new EloquentShopperRepository(); + $updatedShopper = new Shopper( + id: $shopperId, + email: new Email('after@example.com'), + matricule: new Matricule('7654321'), + nom: 'Martin', + prenom: 'Claire', + startDate: CarbonImmutable::parse('2026-02-01'), + endDate: CarbonImmutable::parse('2026-12-31'), + etablissement: new ShopperEstablishmentCode('ETAB02'), + site: new ShopperSiteCode('PA'), + service: new ShopperServiceCode('202'), + ); + + // WHEN + $repo->persist($updatedShopper); + + // THEN + $reloaded = $repo->find($shopperId); + + expect($reloaded)->toBeInstanceOf(Shopper::class) + ->and($reloaded?->email->value)->toBe('after@example.com') + ->and($reloaded?->matricule->value)->toBe('7654321') + ->and($reloaded?->nom)->toBe('Martin') + ->and($reloaded?->prenom)->toBe('Claire') + ->and($reloaded?->startDate->format('Y-m-d'))->toBe('2026-02-01') + ->and($reloaded?->endDate?->format('Y-m-d'))->toBe('2026-12-31') + ->and($reloaded?->etablissement->value)->toBe('ETAB02') + ->and($reloaded?->site->value)->toBe('PA') + ->and($reloaded?->service->value)->toBe('202'); + }); }); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php index f70bb985..27527893 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php @@ -19,7 +19,7 @@ use Infrastructure\Adapters\Repositories\SessionBasketRepository; use Infrastructure\Adapters\Serializers\BasketSerializer; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('SessionBasketRepository', function () { @@ -34,7 +34,7 @@ describe('SessionBasketRepository', function () { it('returns null when session is empty', function () { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); // WHEN $basket = getRepository()->find($basketId); @@ -45,7 +45,7 @@ describe('SessionBasketRepository', function () { it('can save a basket into the session and retrieve it identically', function (BasketProduct $product) { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId, [$product->id->value->toString() => $product]); $repository = getRepository(); @@ -78,7 +78,7 @@ describe('SessionBasketRepository', function () { ->and($retrievedProduct->options)->toBe($product->options); })->with([ 'Full product' => fn () => new BasketProduct( - id: new ProductId(Uuid::uuid7()), + id: new ProductId(UuidHelper::v7()), name: 'Poulet Rôti', qty: 2, unitPriceHt: new Money(1200, new Currency('EUR')), @@ -97,7 +97,7 @@ describe('SessionBasketRepository', function () { options: ['cut' => 'halves'] ), 'Minimal product without optional fields' => fn () => new BasketProduct( - id: new ProductId(Uuid::uuid7()), + id: new ProductId(UuidHelper::v7()), name: 'Pâtes', qty: 1, unitPriceHt: new Money(200, new Currency('EUR')), @@ -120,7 +120,7 @@ describe('SessionBasketRepository', function () { it('can destroy the basket from the session', function () { // GIVEN $repository = getRepository(); - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId, []); $repository->persist($basket); diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php index d4eaa838..c34daa12 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php @@ -16,7 +16,7 @@ use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\StatefulGuard; use Infrastructure\Adapters\Services\AppCustomerAuthService; use Mockery; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('AppCustomerAuthService', function (): void { @@ -65,7 +65,7 @@ describe('AppCustomerAuthService', function (): void { $guard = Mockery::spy(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); $customer = new Customer(); - $customer->id = (string) Uuid::uuid7(); + $customer->id = (string) UuidHelper::v7(); $service = new AppCustomerAuthService($guard, $crmService); @@ -251,7 +251,7 @@ describe('AppCustomerAuthService', function (): void { $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); $customer = new Customer(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $customer->hashcode = $hashcode; // DO NOT MOCK CrmCustomer @@ -289,7 +289,7 @@ describe('AppCustomerAuthService', function (): void { $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); $customer = new Customer(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $customer->hashcode = $hashcode; $crmService->shouldReceive('getCustomerFromHashCode')->with($customer->hashcode)->andReturn(null); @@ -308,7 +308,7 @@ describe('AppCustomerAuthService', function (): void { $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); $customer = new Customer(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $customer->hashcode = $hashcode; $crmCustomer = new CrmCustomer( @@ -349,7 +349,7 @@ describe('AppCustomerAuthService', function (): void { $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); $customer = new Customer(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $customer->hashcode = $hashcode; $crmService->shouldReceive('getCustomerFromHashCode')->with($customer->hashcode)->andReturn(null); @@ -368,7 +368,7 @@ describe('AppCustomerAuthService', function (): void { $guard = Mockery::mock(StatefulGuard::class); $crmService = Mockery::mock(CrmService::class); $customer = new Customer(); - $hashcode = new CrmHashcode(Uuid::uuid4()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $customer->hashcode = $hashcode; $exception = new CrmServiceException('Crm Error'); diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/AppSessionServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/AppSessionServiceTest.php index 495d1a8b..d95aff3b 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/AppSessionServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/AppSessionServiceTest.php @@ -6,7 +6,6 @@ namespace Tests\Integration\WithApp\Infra\Adapters\Services; use Illuminate\Support\Facades\Session; use Infrastructure\Adapters\Services\AppSessionService; -use Ramsey\Uuid\Uuid; use Shared\Helpers\UuidHelper; describe('AppSessionService', function (): void { @@ -43,7 +42,7 @@ describe('AppSessionService', function (): void { it('hydrates an existing UUID string already stored in Session under the configured key', function (): void { // GIVEN $sessionKey = 'test_session_id'; - $existingUuid = Uuid::uuid7()->toString(); + $existingUuid = UuidHelper::v7()->toString(); Session::put($sessionKey, $existingUuid); $service = new AppSessionService($sessionKey); diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/DatabaseTunnelAttemptTrackerServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/DatabaseTunnelAttemptTrackerServiceTest.php index 0d857e0f..cc15035a 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/DatabaseTunnelAttemptTrackerServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/DatabaseTunnelAttemptTrackerServiceTest.php @@ -27,7 +27,7 @@ use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Session; use Infrastructure\Adapters\Services\DatabaseTunnelAttemptTrackerService; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; covers(DatabaseTunnelAttemptTrackerService::class); @@ -46,11 +46,11 @@ describe('DatabaseTunnelAttemptTrackerService', function (): void { /** @var Customer $customer */ $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('attempt-reuse@example.com'), ]); - $shopperId = new ShopperId(Uuid::fromString($customer->id)); + $shopperId = new ShopperId(UuidHelper::fromString($customer->id)); // WHEN $tracker->recordEntry($shopperId); @@ -82,16 +82,16 @@ describe('DatabaseTunnelAttemptTrackerService', function (): void { /** @var Customer $customer */ $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('attempt-convert@example.com'), ]); - $shopperId = new ShopperId(Uuid::fromString($customer->id)); + $shopperId = new ShopperId(UuidHelper::fromString($customer->id)); - $orderId = Uuid::uuid7()->toString(); + $orderId = UuidHelper::v7()->toString(); Order::query()->forceCreate([ 'id' => $orderId, - 'reference' => new OrderReference(Uuid::uuid7()), + 'reference' => new OrderReference(UuidHelper::v7()), 'status' => OrderStatus::VALIDATED->value, 'total' => Money::EUR(1500), 'employee' => new OrderEmployee( @@ -108,7 +108,7 @@ describe('DatabaseTunnelAttemptTrackerService', function (): void { $tracker->recordEntry($shopperId); // WHEN - $tracker->markConverted(new OrderId(Uuid::fromString($orderId))); + $tracker->markConverted(new OrderId(UuidHelper::fromString($orderId))); // THEN expect($session->has('order_tunnel_attempt_id'))->toBeFalse(); @@ -131,14 +131,14 @@ describe('DatabaseTunnelAttemptTrackerService', function (): void { /** @var Customer $customer */ $customer = Customer::query()->forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('attempt-clear@example.com'), ]); - $tracker->recordEntry(new ShopperId(Uuid::fromString($customer->id))); + $tracker->recordEntry(new ShopperId(UuidHelper::fromString($customer->id))); // WHEN - $listener->handle(new BasketRemoved(new BasketId(Uuid::uuid7()))); + $listener->handle(new BasketRemoved(new BasketId(UuidHelper::v7()))); // THEN expect($session->has('order_tunnel_attempt_id'))->toBeFalse() diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php index 89aac542..4c41a9f8 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php @@ -10,102 +10,104 @@ use Domain\Enums\OrderStatus; use Domain\Models\ValueObjects\Matricule; use Illuminate\Support\Facades\DB; use Infrastructure\Adapters\Services\EloquentEmployeeStatisticsService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; -it('retrieves the weekly order total for a given employee', function () { - // GIVEN - $shop = Shop::factory()->create(); +describe('EloquentEmployeeStatisticsService', function (): void { + it('retrieves the weekly order total for a given employee', function () { + // GIVEN + $shop = Shop::factory()->create(); - DB::table('orders')->insert([ - 'id' => '018e4567-e89b-72d3-a456-426614174000', - 'shop_id' => $shop->id, - 'reference' => Uuid::uuid7()->toString(), - 'employee' => json_encode([ - 'matricule' => '1234567', - 'firstname' => 'Jean', - 'lastname' => 'Dupont', - 'facility' => 'Main Facility', - 'site' => 'HQ', - 'service' => 'IT', - ]), - 'delivery_address' => '{}', - 'pickup_day' => '2023-01-05', - 'status' => OrderStatus::VALIDATED->value, - 'total' => 1500, // 15.00 EUR - ]); + DB::table('orders')->insert([ + 'id' => '018e4567-e89b-72d3-a456-426614174000', + 'shop_id' => $shop->id, + 'reference' => UuidHelper::v7()->toString(), + 'employee' => json_encode([ + 'matricule' => '1234567', + 'firstname' => 'Jean', + 'lastname' => 'Dupont', + 'facility' => 'Main Facility', + 'site' => 'HQ', + 'service' => 'IT', + ]), + 'delivery_address' => '{}', + 'pickup_day' => '2023-01-05', + 'status' => OrderStatus::VALIDATED->value, + 'total' => 1500, // 15.00 EUR + ]); - $service = new EloquentEmployeeStatisticsService(); - $start = CarbonImmutable::parse('2023-01-01'); - $end = CarbonImmutable::parse('2023-01-07'); + $service = new EloquentEmployeeStatisticsService(); + $start = CarbonImmutable::parse('2023-01-01'); + $end = CarbonImmutable::parse('2023-01-07'); - // WHEN - $result = $service->getWeeklyTotalForEmployee(new Matricule('1234567'), $start, $end); + // WHEN + $result = $service->getWeeklyTotalForEmployee(new Matricule('1234567'), $start, $end); - // THEN - expect($result->getAmount())->toBe('1500') - ->and($result->getCurrency()->getCode())->toBe('EUR'); -}); - -it('includes VALIDATED and PENDING orders and excludes WAITING, FAILED, and CANCELED orders in weekly total', function (): void { - // GIVEN - $shop = Shop::factory()->create(); - - $baseRow = [ - 'shop_id' => $shop->id, - 'employee' => json_encode([ - 'matricule' => '1234567', - 'firstname' => 'Jean', - 'lastname' => 'Dupont', - 'facility' => 'Main Facility', - 'site' => 'HQ', - 'service' => 'IT', - ]), - 'delivery_address' => '{}', - 'pickup_day' => '2023-01-05', - ]; - - DB::table('orders')->insert([ - array_merge($baseRow, [ - 'id' => Uuid::uuid7()->toString(), - 'reference' => Uuid::uuid7()->toString(), - 'status' => OrderStatus::VALIDATED->value, - 'total' => 1000, - ]), - array_merge($baseRow, [ - 'id' => Uuid::uuid7()->toString(), - 'reference' => Uuid::uuid7()->toString(), - 'status' => OrderStatus::PENDING->value, - 'total' => 2500, - ]), - array_merge($baseRow, [ - 'id' => Uuid::uuid7()->toString(), - 'reference' => Uuid::uuid7()->toString(), - 'status' => OrderStatus::WAITING->value, - 'total' => 4000, - ]), - array_merge($baseRow, [ - 'id' => Uuid::uuid7()->toString(), - 'reference' => Uuid::uuid7()->toString(), - 'status' => OrderStatus::FAILED->value, - 'total' => 5000, - ]), - array_merge($baseRow, [ - 'id' => Uuid::uuid7()->toString(), - 'reference' => Uuid::uuid7()->toString(), - 'status' => OrderStatus::CANCELED->value, - 'total' => 9000, - ]), - ]); - - $service = new EloquentEmployeeStatisticsService(); - - // WHEN - $result = $service->getWeeklyTotalForEmployee( - new Matricule('1234567'), - CarbonImmutable::parse('2023-01-01'), - CarbonImmutable::parse('2023-01-07') - ); - - // THEN - expect($result->getAmount())->toBe('3500'); + // THEN + expect($result->getAmount())->toBe('1500') + ->and($result->getCurrency()->getCode())->toBe('EUR'); + }); + + it('includes VALIDATED and PENDING orders and excludes WAITING, FAILED, and CANCELED orders in weekly total', function (): void { + // GIVEN + $shop = Shop::factory()->create(); + + $baseRow = [ + 'shop_id' => $shop->id, + 'employee' => json_encode([ + 'matricule' => '1234567', + 'firstname' => 'Jean', + 'lastname' => 'Dupont', + 'facility' => 'Main Facility', + 'site' => 'HQ', + 'service' => 'IT', + ]), + 'delivery_address' => '{}', + 'pickup_day' => '2023-01-05', + ]; + + DB::table('orders')->insert([ + array_merge($baseRow, [ + 'id' => UuidHelper::v7()->toString(), + 'reference' => UuidHelper::v7()->toString(), + 'status' => OrderStatus::VALIDATED->value, + 'total' => 1000, + ]), + array_merge($baseRow, [ + 'id' => UuidHelper::v7()->toString(), + 'reference' => UuidHelper::v7()->toString(), + 'status' => OrderStatus::PENDING->value, + 'total' => 2500, + ]), + array_merge($baseRow, [ + 'id' => UuidHelper::v7()->toString(), + 'reference' => UuidHelper::v7()->toString(), + 'status' => OrderStatus::WAITING->value, + 'total' => 4000, + ]), + array_merge($baseRow, [ + 'id' => UuidHelper::v7()->toString(), + 'reference' => UuidHelper::v7()->toString(), + 'status' => OrderStatus::FAILED->value, + 'total' => 5000, + ]), + array_merge($baseRow, [ + 'id' => UuidHelper::v7()->toString(), + 'reference' => UuidHelper::v7()->toString(), + 'status' => OrderStatus::CANCELED->value, + 'total' => 9000, + ]), + ]); + + $service = new EloquentEmployeeStatisticsService(); + + // WHEN + $result = $service->getWeeklyTotalForEmployee( + new Matricule('1234567'), + CarbonImmutable::parse('2023-01-01'), + CarbonImmutable::parse('2023-01-07') + ); + + // THEN + expect($result->getAmount())->toBe('3500'); + }); }); diff --git a/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php b/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php index ad9ab7d3..be4eadf6 100644 --- a/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php +++ b/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php @@ -14,12 +14,12 @@ use Domain\Models\ValueObjects\Entities\ShopId; use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Models\ValueObjects\PickupTimeSlot; use Domain\Services\OrderTunnelService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('ApplyPickTimeSlot', function (): void { it('applies time slot to order builder via OrderTunnelService', function (): void { // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); + $shopperId = new ShopperId(UuidHelper::v7()); $timeslot = CarbonImmutable::parse('2026-10-15'); $input = new ApplyPickTimeSlotInput( shopperId: $shopperId, @@ -28,7 +28,7 @@ describe('ApplyPickTimeSlot', function (): void { $builder = \Mockery::mock(OrderBuilderWithBasket::class); $shop = new Shop( - id: new ShopId(Uuid::uuid7()), + id: new ShopId(UuidHelper::v7()), name: 'Shop 1', address: '1 rue Test', postcode: '75001', @@ -66,7 +66,7 @@ describe('ApplyPickTimeSlot', function (): void { it('returns unavailable output when no time slot matches', function (): void { // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); + $shopperId = new ShopperId(UuidHelper::v7()); $timeslot = CarbonImmutable::parse('2026-10-15'); $input = new ApplyPickTimeSlotInput( shopperId: $shopperId, @@ -75,7 +75,7 @@ describe('ApplyPickTimeSlot', function (): void { $builder = \Mockery::mock(OrderBuilderWithBasket::class); $shop = new Shop( - id: new ShopId(Uuid::uuid7()), + id: new ShopId(UuidHelper::v7()), name: 'Shop 1', address: '1 rue Test', postcode: '75001', diff --git a/tests/Unit/App/Cqs/Actions/Orders/CancelOrderTest.php b/tests/Unit/App/Cqs/Actions/Orders/CancelOrderTest.php index 3786e299..03c99c59 100644 --- a/tests/Unit/App/Cqs/Actions/Orders/CancelOrderTest.php +++ b/tests/Unit/App/Cqs/Actions/Orders/CancelOrderTest.php @@ -10,12 +10,12 @@ use App\Cqs\Actions\Orders\CancelOrderOutput; use App\Models\Order; use Domain\Models\ValueObjects\Entities\OrderId; use Domain\Services\OrderService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('CancelOrder', function (): void { it('cancels the order and returns CANCELLED when OrderService succeeds', function (): void { // GIVEN - $orderId = new OrderId(Uuid::uuid7()); + $orderId = new OrderId(UuidHelper::v7()); $order = new Order(); $order->id = $orderId->value->toString(); @@ -35,7 +35,7 @@ describe('CancelOrder', function (): void { it('returns NOT_FOUND when OrderService throws DomainException', function (): void { // GIVEN - $orderId = new OrderId(Uuid::uuid7()); + $orderId = new OrderId(UuidHelper::v7()); $order = new Order(); $order->id = $orderId->value->toString(); diff --git a/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php index dc13eebd..7517aba5 100644 --- a/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php +++ b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -44,18 +44,18 @@ use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Ports\Repositories\BasketRepository; use Domain\Services\OrderTunnelService; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('PlacePendingOrder', function (): void { it('places a pending order and returns id and reference via OrderTunnelService', function (): void { // GIVEN $input = new PlacePendingOrderInput(); - $orderId = new OrderId(Uuid::uuid7()); - $orderReference = new OrderReference(Uuid::uuid7()); + $orderId = new OrderId(UuidHelper::v7()); + $orderReference = new OrderReference(UuidHelper::v7()); $builder = \Mockery::mock(OrderBuilderCompleted::class); $order = new Order( id: $orderId, - shopId: new ShopId(Uuid::uuid7()), + shopId: new ShopId(UuidHelper::v7()), reference: $orderReference, employee: new OrderEmployee( matricule: new Matricule('1234567'), @@ -163,7 +163,7 @@ describe('PlacePendingOrder', function (): void { // GIVEN $input = new PlacePendingOrderInput(); $builder = \Mockery::mock(OrderBuilderCompleted::class); - $refreshedBasket = new Basket(new BasketId(Uuid::uuid7()), []); + $refreshedBasket = new Basket(new BasketId(UuidHelper::v7()), []); /** @var \Mockery\MockInterface&OrderTunnelService $orderTunnelService */ $orderTunnelService = \Mockery::mock(OrderTunnelService::class); $orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder); @@ -191,7 +191,7 @@ describe('PlacePendingOrder', function (): void { it('builds shopper lock key and returns LOCK_TIMEOUT output on lock timeout', function (): void { // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); + $shopperId = new ShopperId(UuidHelper::v7()); $input = new PlacePendingOrderInput(shopperId: $shopperId); /** @var \Mockery\MockInterface&OrderTunnelService $orderTunnelService */ $orderTunnelService = \Mockery::mock(OrderTunnelService::class); @@ -213,7 +213,7 @@ describe('PlacePendingOrder', function (): void { describe('ExportOrderToRegate, ConfirmPlacedOrder and FailPendingOrder', function (): void { it('exports order via OrderTunnelService and handles lock timeout', function (): void { // GIVEN - $orderId = new OrderId(Uuid::uuid7()); + $orderId = new OrderId(UuidHelper::v7()); $input = new ExportOrderToRegateInput($orderId); /** @var \Mockery\MockInterface&OrderTunnelService $orderTunnelService */ @@ -233,11 +233,11 @@ describe('ExportOrderToRegate, ConfirmPlacedOrder and FailPendingOrder', functio it('confirms a placed order and fails a pending order', function (): void { // GIVEN - $orderId = new OrderId(Uuid::uuid7()); + $orderId = new OrderId(UuidHelper::v7()); $order = new Order( id: $orderId, - shopId: new ShopId(Uuid::uuid7()), - reference: new OrderReference(Uuid::uuid7()), + shopId: new ShopId(UuidHelper::v7()), + reference: new OrderReference(UuidHelper::v7()), employee: new OrderEmployee( matricule: new Matricule('1234567'), firstname: 'Jean', diff --git a/tests/Unit/App/Cqs/Actions/ProductIncos/AssociateProductIncoInputTest.php b/tests/Unit/App/Cqs/Actions/ProductIncos/AssociateProductIncoInputTest.php index 9729cd7f..447273d8 100644 --- a/tests/Unit/App/Cqs/Actions/ProductIncos/AssociateProductIncoInputTest.php +++ b/tests/Unit/App/Cqs/Actions/ProductIncos/AssociateProductIncoInputTest.php @@ -6,12 +6,12 @@ namespace Tests\Unit\App\Cqs\Actions\ProductIncos; use App\Cqs\Actions\ProductIncos\AssociateProductIncoInput; use Domain\Models\ValueObjects\Entities\ProductId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('AssociateProductIncoInput', function (): void { it('creates input successfully with valid parameters', function (): void { // GIVEN - $productId = new ProductId(Uuid::uuid7()); + $productId = new ProductId(UuidHelper::v7()); $noArt = 27996; // WHEN @@ -24,7 +24,7 @@ describe('AssociateProductIncoInput', function (): void { it('throws when no_art is less than 1', function (): void { // GIVEN - $productId = new ProductId(Uuid::uuid7()); + $productId = new ProductId(UuidHelper::v7()); $noArt = 0; // WHEN & THEN diff --git a/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php index 4acaf9d9..23e88b06 100644 --- a/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php +++ b/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php @@ -10,12 +10,12 @@ use Domain\Enums\OrderTunnelStep; use Domain\Models\Entities\Basket; use Domain\Models\ValueObjects\Entities\BasketId; use Domain\Services\BasketService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('GetBasketSummaryQuery', function (): void { it('returns basket summary output with step REVIEW and basket', function (): void { // GIVEN - $basket = new Basket(new BasketId(Uuid::uuid7())); + $basket = new Basket(new BasketId(UuidHelper::v7())); $basketService = \Mockery::mock(BasketService::class); $basketService->shouldReceive('getBasket') ->once() diff --git a/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php index 49302843..f013ac16 100644 --- a/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php +++ b/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php @@ -14,14 +14,14 @@ use Domain\Models\ValueObjects\Entities\BasketId; use Domain\Models\ValueObjects\Entities\ShopId; use Domain\Ports\Repositories\ShopRepository; use Domain\Services\OrderTunnelService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; describe('GetOrderConfirmationQuery', function (): void { it('returns order confirmation output with step, basket, builder and shop', function (): void { // GIVEN - $shopId = new ShopId(Uuid::uuid7()); - $basket = new Basket(new BasketId(Uuid::uuid7())); + $shopId = new ShopId(UuidHelper::v7()); + $basket = new Basket(new BasketId(UuidHelper::v7())); $builder = \Mockery::mock(OrderBuilderCompleted::class); $builder->shouldReceive('getBasket')->once()->andReturn($basket); $builder->shouldReceive('getShopId')->once()->andReturn($shopId); @@ -60,8 +60,8 @@ describe('GetOrderConfirmationQuery', function (): void { it('throws NotFoundHttpException when shop is not found', function (): void { // GIVEN - $shopId = new ShopId(Uuid::uuid7()); - $basket = new Basket(new BasketId(Uuid::uuid7())); + $shopId = new ShopId(UuidHelper::v7()); + $basket = new Basket(new BasketId(UuidHelper::v7())); $builder = \Mockery::mock(OrderBuilderCompleted::class); $builder->shouldReceive('getBasket')->once()->andReturn($basket); $builder->shouldReceive('getShopId')->once()->andReturn($shopId); diff --git a/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php index 87493ad7..013797b4 100644 --- a/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php +++ b/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php @@ -15,16 +15,16 @@ use Domain\Models\ValueObjects\Entities\ShopId; use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Models\ValueObjects\PickupTimeSlot; use Domain\Services\OrderTunnelService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('GetPickTimeSlotQuery', function (): void { it('returns pick time slot output with step BOOKING, shop, mapUrl and timeslots', function (): void { // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); + $shopperId = new ShopperId(UuidHelper::v7()); $input = new GetPickTimeSlotQueryInput($shopperId); $shop = new Shop( - id: new ShopId(Uuid::uuid7()), + id: new ShopId(UuidHelper::v7()), name: 'Shop 1', address: '1 rue Test', postcode: '75001', diff --git a/tests/Unit/App/Dto/ShopDtoTest.php b/tests/Unit/App/Dto/ShopDtoTest.php index d9d89ccf..fe52d65c 100644 --- a/tests/Unit/App/Dto/ShopDtoTest.php +++ b/tests/Unit/App/Dto/ShopDtoTest.php @@ -7,12 +7,12 @@ namespace Tests\Unit\App\Dto; use App\Dto\ShopDto; use Domain\Models\Entities\Shop; use Domain\Models\ValueObjects\Entities\ShopId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('ShopDto', function (): void { it('creates a DTO from domain Shop entity', function (): void { // GIVEN - $uuid = Uuid::uuid7(); + $uuid = UuidHelper::v7(); $shopId = new ShopId($uuid); $domainShop = new Shop( id: $shopId, diff --git a/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php b/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php index 363625cc..972f8c2b 100644 --- a/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php +++ b/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php @@ -26,13 +26,13 @@ use Domain\Ports\Repositories\ProductRepository; use Domain\Ports\Services\SessionService; use Domain\Services\BasketService; use Money\Money; -use Ramsey\Uuid\Uuid; use Shared\DDD\DomainEventDispatcher; +use Shared\Helpers\UuidHelper; describe('EmptyBasketOnOrderPlaced', function (): void { it('empties the basket when an order has been placed', function (): void { // GIVEN - $sessionUuid = Uuid::uuid7(); + $sessionUuid = UuidHelper::v7(); $basket = new Basket(new BasketId($sessionUuid)); /** @var BasketRepository&\Mockery\MockInterface $basketRepository */ @@ -54,8 +54,8 @@ describe('EmptyBasketOnOrderPlaced', function (): void { $listener = new EmptyBasketOnOrderPlaced($basketService); $event = new AnOrderHasBeenPlaced( - orderId: new OrderId(Uuid::uuid7()), - reference: new OrderReference(Uuid::uuid7()), + orderId: new OrderId(UuidHelper::v7()), + reference: new OrderReference(UuidHelper::v7()), totalTtc: Money::EUR(1000), byMatricule: new Matricule('1234567'), employee: new OrderEmployee( diff --git a/tests/Unit/App/Listeners/Orders/InvalidateOrderBuilderOnBasketChangeTest.php b/tests/Unit/App/Listeners/Orders/InvalidateOrderBuilderOnBasketChangeTest.php index 8f5727c3..b23e81ec 100644 --- a/tests/Unit/App/Listeners/Orders/InvalidateOrderBuilderOnBasketChangeTest.php +++ b/tests/Unit/App/Listeners/Orders/InvalidateOrderBuilderOnBasketChangeTest.php @@ -9,7 +9,7 @@ use Domain\Events\BasketHasBeenModified; use Domain\Events\BasketRemoved; use Domain\Models\ValueObjects\Entities\BasketId; use Domain\Ports\Services\OrderBuilderSessionManager; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('InvalidateOrderBuilderOnBasketChange', function (): void { it('clears the order builder session manager when basket is modified', function (): void { @@ -17,7 +17,7 @@ describe('InvalidateOrderBuilderOnBasketChange', function (): void { /** @var OrderBuilderSessionManager&\Mockery\MockInterface $manager */ $manager = \Mockery::spy(OrderBuilderSessionManager::class); $listener = new InvalidateOrderBuilderOnBasketChange($manager); - $event = new BasketHasBeenModified(new BasketId(Uuid::uuid7())); + $event = new BasketHasBeenModified(new BasketId(UuidHelper::v7())); // WHEN $listener->handle($event); @@ -31,7 +31,7 @@ describe('InvalidateOrderBuilderOnBasketChange', function (): void { /** @var OrderBuilderSessionManager&\Mockery\MockInterface $manager */ $manager = \Mockery::spy(OrderBuilderSessionManager::class); $listener = new InvalidateOrderBuilderOnBasketChange($manager); - $event = new BasketRemoved(new BasketId(Uuid::uuid7())); + $event = new BasketRemoved(new BasketId(UuidHelper::v7())); // WHEN $listener->handle($event); diff --git a/tests/Unit/App/Policies/Backend/ProductPolicyTest.php b/tests/Unit/App/Policies/Backend/ProductPolicyTest.php index fed9c41f..16757ddf 100644 --- a/tests/Unit/App/Policies/Backend/ProductPolicyTest.php +++ b/tests/Unit/App/Policies/Backend/ProductPolicyTest.php @@ -16,7 +16,7 @@ use Domain\Models\Entities\Product as DomainProduct; use Domain\Models\ValueObjects\Entities\ProductId; use Domain\Ports\Repositories\ProductRepository; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('ProductPolicy', function () { function getProductPolicy(?ProductRepository $repo = null): ProductPolicy @@ -29,7 +29,7 @@ describe('ProductPolicy', function () { function createDomainProduct(bool $status = true): DomainProduct { return new DomainProduct( - new ProductId(Uuid::uuid7()), + new ProductId(UuidHelper::v7()), Money::EUR(100), TaxRate::TVA_20, null, @@ -254,7 +254,7 @@ describe('ProductPolicy', function () { test('viewPublished returns false when product not found in domain repo', function () { // GIVEN $product = \Mockery::mock(Product::class); - $productId = new ProductId(Uuid::uuid7()); + $productId = new ProductId(UuidHelper::v7()); $product->shouldReceive('getId')->andReturn($productId); $repo = \Mockery::mock(ProductRepository::class); @@ -271,7 +271,7 @@ describe('ProductPolicy', function () { test('viewPublished returns true when product found and is published', function () { // GIVEN $product = \Mockery::mock(Product::class); - $productId = new ProductId(Uuid::uuid7()); + $productId = new ProductId(UuidHelper::v7()); $product->shouldReceive('getId')->andReturn($productId); $domainProduct = createDomainProduct(status: true); @@ -290,7 +290,7 @@ describe('ProductPolicy', function () { test('viewPublished returns false when product found and is not published', function () { // GIVEN $product = \Mockery::mock(Product::class); - $productId = new ProductId(Uuid::uuid7()); + $productId = new ProductId(UuidHelper::v7()); $product->shouldReceive('getId')->andReturn($productId); $domainProduct = createDomainProduct(status: false); diff --git a/tests/Unit/App/Policies/Frontend/BasketPolicyTest.php b/tests/Unit/App/Policies/Frontend/BasketPolicyTest.php index 1c9db103..d0e0ebe4 100644 --- a/tests/Unit/App/Policies/Frontend/BasketPolicyTest.php +++ b/tests/Unit/App/Policies/Frontend/BasketPolicyTest.php @@ -14,7 +14,7 @@ use Domain\Models\ValueObjects\BasketProduct; use Domain\Models\ValueObjects\DiscountRate; use Domain\Models\ValueObjects\Entities\ProductId; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; covers(BasketPolicy::class); @@ -22,7 +22,7 @@ function createDummyBasketProductDto(bool $isPublished = true): BasketProductDto { return new BasketProductDto( product: new BasketProduct( - new ProductId(Uuid::uuid7()), + new ProductId(UuidHelper::v7()), 'Dummy', 1, Money::EUR(1000), diff --git a/tests/Unit/Domain/Builders/OrderBuilderTest.php b/tests/Unit/Domain/Builders/OrderBuilderTest.php index 246146c3..c0e7a9d8 100644 --- a/tests/Unit/Domain/Builders/OrderBuilderTest.php +++ b/tests/Unit/Domain/Builders/OrderBuilderTest.php @@ -14,14 +14,14 @@ use Domain\Models\ValueObjects\Entities\BasketId; use Domain\Models\ValueObjects\Entities\ShopId; use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Models\ValueObjects\PickupTimeSlot; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('OrderBuilder', function (): void { it('initializes from basket as an immutable BasketOrderBuilder', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); - $customerId = new ShopperId(Uuid::uuid7()); + $customerId = new ShopperId(UuidHelper::v7()); // WHEN $builder = OrderBuilder::fromBasket($basket, $customerId); @@ -37,10 +37,10 @@ describe('OrderBuilder', function (): void { it('returns a new immutable CompletedOrderBuilder when applying a timeslot', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); - $customerId = new ShopperId(Uuid::uuid7()); - $shopId = new ShopId(Uuid::uuid7()); + $customerId = new ShopperId(UuidHelper::v7()); + $shopId = new ShopId(UuidHelper::v7()); $timeSlot = new PickupTimeSlot(new \DateTimeImmutable(), new \DateInterval('PT1H')); $builder = OrderBuilder::fromBasket($basket, $customerId); @@ -63,11 +63,11 @@ describe('OrderBuilder', function (): void { it('returns a new immutable CompletedOrderBuilder when updating the timeslot', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); - $customerId = new ShopperId(Uuid::uuid7()); - $firstShop = new ShopId(Uuid::uuid7()); - $secondShop = new ShopId(Uuid::uuid7()); + $customerId = new ShopperId(UuidHelper::v7()); + $firstShop = new ShopId(UuidHelper::v7()); + $secondShop = new ShopId(UuidHelper::v7()); $firstSlot = new PickupTimeSlot(new \DateTimeImmutable('+1 day'), new \DateInterval('PT1H')); $secondSlot = new PickupTimeSlot(new \DateTimeImmutable('+2 days'), new \DateInterval('PT1H')); $firstStep = OrderBuilder::fromBasket($basket, $customerId)->withPickupTimeSlot($firstShop, $firstSlot); diff --git a/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php b/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php index d0ef4c7a..3a4bd084 100644 --- a/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php +++ b/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php @@ -18,14 +18,14 @@ use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('AnOrderHasBeenPlaced', function () { it('creates an event when valid', function () { // GIVEN - $uuid = Uuid::uuid7(); + $uuid = UuidHelper::v7(); $orderId = new OrderId($uuid); - $reference = new OrderReference(Uuid::uuid7()); + $reference = new OrderReference(UuidHelper::v7()); $totalTtc = new Money(1000, new Currency('EUR')); $matricule = new Matricule('1234567'); $employee = new OrderEmployee( @@ -52,9 +52,9 @@ describe('AnOrderHasBeenPlaced', function () { it('throws exception if lines are empty', function () { // GIVEN - $uuid = Uuid::uuid7(); + $uuid = UuidHelper::v7(); $orderId = new OrderId($uuid); - $reference = new OrderReference(Uuid::uuid7()); + $reference = new OrderReference(UuidHelper::v7()); $totalTtc = new Money(1000, new Currency('EUR')); $matricule = new Matricule('1234567'); $employee = new OrderEmployee( diff --git a/tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php b/tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php index e0f0be0e..81bd38ee 100644 --- a/tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php +++ b/tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php @@ -6,12 +6,12 @@ namespace Tests\Unit\Domain\Events; use Domain\Events\BasketHasBeenModified; use Domain\Models\ValueObjects\Entities\BasketId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('BasketHasBeenModified', function (): void { it('stores the basket id and implements Event', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); // WHEN $event = new BasketHasBeenModified($basketId); diff --git a/tests/Unit/Domain/Events/BasketRemovedTest.php b/tests/Unit/Domain/Events/BasketRemovedTest.php index 6fbdde8c..1d783442 100644 --- a/tests/Unit/Domain/Events/BasketRemovedTest.php +++ b/tests/Unit/Domain/Events/BasketRemovedTest.php @@ -6,12 +6,12 @@ namespace Tests\Unit\Domain\Events; use Domain\Events\BasketRemoved; use Domain\Models\ValueObjects\Entities\BasketId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('BasketRemoved', function (): void { it('stores the basket id and implements Event', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); // WHEN $event = new BasketRemoved($basketId); diff --git a/tests/Unit/Domain/Events/DtoTest.php b/tests/Unit/Domain/Events/DtoTest.php index e23a3791..e3962677 100644 --- a/tests/Unit/Domain/Events/DtoTest.php +++ b/tests/Unit/Domain/Events/DtoTest.php @@ -19,7 +19,7 @@ use Domain\Models\ValueObjects\OrderLineProduct; use Domain\Models\ValueObjects\ProductWeight; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('OrderPlacedLine', function () { it('creates OrderPlacedLine correctly', function () { @@ -54,7 +54,7 @@ describe('OrderPlacedLine', function () { // GIVEN $product = new OrderLineProduct( incoId: new IncoId(42), - originalId: new ProductId(Uuid::uuid7()), + originalId: new ProductId(UuidHelper::v7()), name: 'Poulet rôti', weight: new ProductWeight(1000, false), brand: ProductBrand::none, diff --git a/tests/Unit/Domain/Models/Entities/BasketTest.php b/tests/Unit/Domain/Models/Entities/BasketTest.php index fdb4f57c..d99a5daf 100644 --- a/tests/Unit/Domain/Models/Entities/BasketTest.php +++ b/tests/Unit/Domain/Models/Entities/BasketTest.php @@ -14,7 +14,7 @@ use Domain\Models\ValueObjects\Entities\BasketId; use Domain\Models\ValueObjects\Entities\ProductId; use Domain\Models\ValueObjects\IncoId; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('Basket and BasketProduct', function (): void { @@ -28,7 +28,7 @@ describe('Basket and BasketProduct', function (): void { function getNewBasketProduct(array $overrides = []): BasketProduct { return new BasketProduct( - id: $overrides['id'] ?? new ProductId(Uuid::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')), + id: $overrides['id'] ?? new ProductId(UuidHelper::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')), name: 'Poulet Rôti', qty: $overrides['qty'] ?? 2, unitPriceHt: Money::EUR(1000), @@ -50,7 +50,7 @@ describe('Basket and BasketProduct', function (): void { it('can instantiate a basket product with all new typed properties', function (): void { // GIVEN - $productId = new ProductId(Uuid::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')); + $productId = new ProductId(UuidHelper::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')); $brand = ProductBrand::marie; $orderUnit = OrderUnit::PCE; $price = Money::EUR(1000); @@ -100,9 +100,9 @@ describe('Basket and BasketProduct', function (): void { it('can clone a basket product with new quantity and keep properties', function (): void { // GIVEN - $productId = new ProductId(Uuid::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')); + $productId = new ProductId(UuidHelper::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')); $item = getNewBasketProduct(['id' => $productId, 'qty' => 2]); - $basketId = new BasketId(Uuid::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')); + $basketId = new BasketId(UuidHelper::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')); $basket = new Basket($basketId); // WHEN @@ -133,7 +133,7 @@ describe('Basket and BasketProduct', function (): void { describe('Basket additional coverage', function (): void { it('throws if item is not BasketProduct', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); // WHEN $action = fn () => (new \ReflectionClass(Basket::class))->newInstance($basketId, ['not-an-item']); // THEN @@ -142,7 +142,7 @@ describe('Basket additional coverage', function (): void { it('returns id', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); // WHEN $id = $basket->id(); @@ -152,9 +152,9 @@ describe('Basket additional coverage', function (): void { it('removes item completely if quantity is greater or equal', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); - $productId = new ProductId(Uuid::uuid7()); + $productId = new ProductId(UuidHelper::v7()); $item = getNewBasketProduct(['id' => $productId, 'qty' => 2]); $basket->addOrUpdate($item); @@ -168,9 +168,9 @@ describe('Basket additional coverage', function (): void { it('decreases quantity when removing', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); - $productId = new ProductId(Uuid::uuid7()); + $productId = new ProductId(UuidHelper::v7()); $item = getNewBasketProduct(['id' => $productId, 'qty' => 5]); $basket->addOrUpdate($item); @@ -184,9 +184,9 @@ describe('Basket additional coverage', function (): void { it('throws when removing less than 1', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); - $productId = new ProductId(Uuid::uuid7()); + $productId = new ProductId(UuidHelper::v7()); // WHEN $action = fn () => $basket->remove($productId, 0); @@ -196,9 +196,9 @@ describe('Basket additional coverage', function (): void { it('throws when removing non-existing item', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); - $productId = new ProductId(Uuid::uuid7()); + $productId = new ProductId(UuidHelper::v7()); // WHEN $action = fn () => $basket->remove($productId, 1); @@ -208,9 +208,9 @@ describe('Basket additional coverage', function (): void { it('removes line directly', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); - $productId = new ProductId(Uuid::uuid7()); + $productId = new ProductId(UuidHelper::v7()); $item = getNewBasketProduct(['id' => $productId, 'qty' => 5]); $basket->addOrUpdate($item); @@ -224,9 +224,9 @@ describe('Basket additional coverage', function (): void { it('throws when removeLine on non-existing item', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); - $productId = new ProductId(Uuid::uuid7()); + $productId = new ProductId(UuidHelper::v7()); // WHEN $action = fn () => $basket->removeLine($productId); @@ -236,9 +236,9 @@ describe('Basket additional coverage', function (): void { it('computes totals', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); - $productId = new ProductId(Uuid::uuid7()); + $productId = new ProductId(UuidHelper::v7()); $item = getNewBasketProduct(['id' => $productId, 'qty' => 1]); $basket->addOrUpdate($item); diff --git a/tests/Unit/Domain/Models/Entities/OrderTest.php b/tests/Unit/Domain/Models/Entities/OrderTest.php index 90906637..690a1f04 100644 --- a/tests/Unit/Domain/Models/Entities/OrderTest.php +++ b/tests/Unit/Domain/Models/Entities/OrderTest.php @@ -35,7 +35,7 @@ use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; /** @@ -55,7 +55,7 @@ function makeOrderLine(array $overrides = []): OrderLine { $product = new OrderLineProduct( incoId: new IncoId(1), - originalId: new ProductId(Uuid::uuid7()), + originalId: new ProductId(UuidHelper::v7()), name: $overrides['productName'] ?? 'Poulet Rôti', weight: new ProductWeight(1600, false), brand: ProductBrand::none, @@ -95,10 +95,10 @@ function makeOrderLine(array $overrides = []): OrderLine function makeOrder(array $overrides = []): Order { return new Order( - id: $overrides['id'] ?? new OrderId(Uuid::uuid7()), - shopId: $overrides['shopId'] ?? new ShopId(Uuid::uuid7()), + id: $overrides['id'] ?? new OrderId(UuidHelper::v7()), + shopId: $overrides['shopId'] ?? new ShopId(UuidHelper::v7()), reference: $overrides['reference'] ?? new OrderReference( - Uuid::uuid7() + UuidHelper::v7() ), employee: $overrides['employee'] ?? new OrderEmployee( matricule: new Matricule('1234567'), @@ -261,11 +261,11 @@ describe('Order - id', function (): void { describe('Order - fromBasket factory', function (): void { it('creates an order from a basket with all lines mapped', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); $basketProduct = new BasketProduct( - id: new ProductId(Uuid::uuid7()), + id: new ProductId(UuidHelper::v7()), name: 'Poulet Rôti', qty: 2, unitPriceHt: Money::EUR(1000), @@ -284,15 +284,15 @@ describe('Order - fromBasket factory', function (): void { ); $basket->addOrUpdate($basketProduct); - $orderId = new OrderId(Uuid::uuid7()); - $reference = new OrderReference(Uuid::uuid7()); + $orderId = new OrderId(UuidHelper::v7()); + $reference = new OrderReference(UuidHelper::v7()); $pickupTimeSlot = new PickupTimeSlot( new \DateTimeImmutable('+1 day 10:00'), new \DateInterval('PT10M') ); $shopper = new Shopper( - id: new ShopperId(Uuid::uuid7()), + id: new ShopperId(UuidHelper::v7()), email: new Email('jean.dupont@example.com'), matricule: new Matricule('1234567'), nom: 'Dupont', @@ -305,7 +305,7 @@ describe('Order - fromBasket factory', function (): void { ); $shop = new Shop( - id: new ShopId(Uuid::uuid7()), + id: new ShopId(UuidHelper::v7()), name: 'Cocotte Lyon', address: '12 rue de la Paix', postcode: '69001', @@ -330,9 +330,9 @@ describe('Order - fromBasket factory', function (): void { it('creates an order in PENDING status via pendingFromBasket and validates it to VALIDATED', function (): void { // GIVEN - $basket = new Basket(new BasketId(Uuid::uuid7()), [ + $basket = new Basket(new BasketId(UuidHelper::v7()), [ new BasketProduct( - id: new ProductId(Uuid::uuid7()), + id: new ProductId(UuidHelper::v7()), name: 'Poulet Rôti', qty: 1, unitPriceHt: Money::EUR(1000), @@ -351,7 +351,7 @@ describe('Order - fromBasket factory', function (): void { ), ]); $shopper = new Shopper( - id: new ShopperId(Uuid::uuid7()), + id: new ShopperId(UuidHelper::v7()), email: new Email('jean.dupont@example.com'), matricule: new Matricule('1234567'), nom: 'Dupont', @@ -363,7 +363,7 @@ describe('Order - fromBasket factory', function (): void { service: new ShopperServiceCode('101') ); $shop = new Shop( - id: new ShopId(Uuid::uuid7()), + id: new ShopId(UuidHelper::v7()), name: 'Cocotte Lyon', address: '12 rue de la Paix', postcode: '69001', @@ -373,8 +373,8 @@ describe('Order - fromBasket factory', function (): void { // WHEN $order = Order::pendingFromBasket( - new OrderId(Uuid::uuid7()), - new OrderReference(Uuid::uuid7()), + new OrderId(UuidHelper::v7()), + new OrderReference(UuidHelper::v7()), $basket, new PickupTimeSlot(new \DateTimeImmutable('+1 day 10:00'), new \DateInterval('PT10M')), $shopper, diff --git a/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php b/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php index cdbb4b77..a0de477f 100644 --- a/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php +++ b/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php @@ -9,7 +9,7 @@ use Carbon\CarbonImmutable; use Domain\Enums\RepeatFrequency; use Domain\Models\Entities\PickupExceptionOnDate; use Domain\Models\ValueObjects\Entities\PickupExceptionId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; beforeEach(function (): void { $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); @@ -25,7 +25,7 @@ afterEach(function (): void { describe('PickupExceptionOnDate', function (): void { it('can instantiate correctly', function (): void { // GIVEN - $id = new PickupExceptionId(Uuid::uuid7()); + $id = new PickupExceptionId(UuidHelper::v7()); $date = CarbonImmutable::now(); $label = 'Férié'; $repeatable = true; @@ -58,7 +58,7 @@ describe('PickupExceptionOnDate', function (): void { $mondayDate = CarbonImmutable::parse('2025-01-06'); // 2025-01-06 is Monday $fridayException = new PickupExceptionOnDate( - new PickupExceptionId(Uuid::uuid7()), + new PickupExceptionId(UuidHelper::v7()), $fridayDate, 'Friday holiday', false, @@ -67,7 +67,7 @@ describe('PickupExceptionOnDate', function (): void { ); $mondayException = new PickupExceptionOnDate( - new PickupExceptionId(Uuid::uuid7()), + new PickupExceptionId(UuidHelper::v7()), $mondayDate, 'Monday holiday', false, diff --git a/tests/Unit/Domain/Models/Entities/ProductTest.php b/tests/Unit/Domain/Models/Entities/ProductTest.php index ce8d49de..3660b975 100644 --- a/tests/Unit/Domain/Models/Entities/ProductTest.php +++ b/tests/Unit/Domain/Models/Entities/ProductTest.php @@ -14,7 +14,7 @@ use Domain\Models\ValueObjects\DiscountValue; use Domain\Models\ValueObjects\Entities\ProductId; use Domain\Models\ValueObjects\ProductWeight; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; function makeProduct( ?Money $price = null, @@ -29,7 +29,7 @@ function makeProduct( bool $hasInco = true ): Product { return new Product( - id: new ProductId(Uuid::uuid7()), + id: new ProductId(UuidHelper::v7()), price: $price ?? Money::EUR(1000), tax_rate: $taxRate, product_weight: $weight, @@ -57,7 +57,7 @@ afterEach(function (): void { describe('Product', function (): void { it('can instantiate correctly', function (): void { // GIVEN - $id = new ProductId(Uuid::uuid7()); + $id = new ProductId(UuidHelper::v7()); $price = Money::EUR(1000); $taxRate = TaxRate::TVA_5_5; $weight = new ProductWeight(500, false); diff --git a/tests/Unit/Domain/Models/Entities/ShopTest.php b/tests/Unit/Domain/Models/Entities/ShopTest.php index 55407ed5..4562562f 100644 --- a/tests/Unit/Domain/Models/Entities/ShopTest.php +++ b/tests/Unit/Domain/Models/Entities/ShopTest.php @@ -6,12 +6,12 @@ namespace Tests\Unit\Domain\Models\Entities; use Domain\Models\Entities\Shop; use Domain\Models\ValueObjects\Entities\ShopId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('Shop', function (): void { it('can instantiate correctly', function (): void { // GIVEN - $id = new ShopId(Uuid::uuid7()); + $id = new ShopId(UuidHelper::v7()); $name = 'Boutique'; $address = '123 Rue de Paris'; $postcode = '75001'; @@ -49,7 +49,7 @@ describe('Shop', function (): void { it('throws exception if name is empty', function (): void { // GIVEN - $id = new ShopId(Uuid::uuid7()); + $id = new ShopId(UuidHelper::v7()); // WHEN $action = fn () => new Shop($id, '', 'Address', '12345', 'City'); @@ -60,7 +60,7 @@ describe('Shop', function (): void { it('throws exception if address is empty', function (): void { // GIVEN - $id = new ShopId(Uuid::uuid7()); + $id = new ShopId(UuidHelper::v7()); // WHEN $action = fn () => new Shop($id, 'Name', '', '12345', 'City'); @@ -71,7 +71,7 @@ describe('Shop', function (): void { it('throws exception if postcode is empty', function (): void { // GIVEN - $id = new ShopId(Uuid::uuid7()); + $id = new ShopId(UuidHelper::v7()); // WHEN $action = fn () => new Shop($id, 'Name', 'Address', '', 'City'); @@ -82,7 +82,7 @@ describe('Shop', function (): void { it('throws exception if city is empty', function (): void { // GIVEN - $id = new ShopId(Uuid::uuid7()); + $id = new ShopId(UuidHelper::v7()); // WHEN $action = fn () => new Shop($id, 'Name', 'Address', '12345', ''); diff --git a/tests/Unit/Domain/Models/Entities/ShopperTest.php b/tests/Unit/Domain/Models/Entities/ShopperTest.php index e561bd85..d021dc5a 100644 --- a/tests/Unit/Domain/Models/Entities/ShopperTest.php +++ b/tests/Unit/Domain/Models/Entities/ShopperTest.php @@ -12,12 +12,12 @@ use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('Shopper', function (): void { it('can instantiate correctly and check active status (active)', function (): void { // GIVEN - $id = new ShopperId(Uuid::uuid7()); + $id = new ShopperId(UuidHelper::v7()); $email = new Email('test@example.com'); $matricule = new Matricule('1234567'); $startDate = CarbonImmutable::now()->subDay(); @@ -60,7 +60,7 @@ describe('Shopper', function (): void { // WHEN $entity = new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@example.com'), new Matricule('1234567'), 'Nom', @@ -82,7 +82,7 @@ describe('Shopper', function (): void { // WHEN $entity = new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@example.com'), new Matricule('1234567'), 'Nom', @@ -104,7 +104,7 @@ describe('Shopper', function (): void { // WHEN $entity = new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@example.com'), new Matricule('1234567'), 'Nom', @@ -127,7 +127,7 @@ describe('Shopper', function (): void { // WHEN $entity = new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@example.com'), new Matricule('1234567'), 'Nom', @@ -151,7 +151,7 @@ describe('Shopper', function (): void { try { // WHEN $entity = new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@example.com'), new Matricule('1234567'), 'Nom', @@ -178,7 +178,7 @@ describe('Shopper', function (): void { try { // WHEN $entity = new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@example.com'), new Matricule('1234567'), 'Nom', @@ -203,7 +203,7 @@ describe('Shopper', function (): void { try { $entity = new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@example.com'), new Matricule('1234567'), 'Nom', @@ -228,7 +228,7 @@ describe('Shopper', function (): void { try { $entity = new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@example.com'), new Matricule('1234567'), 'Nom', @@ -250,7 +250,7 @@ describe('Shopper', function (): void { it('throws exception if nom is empty', function (): void { // WHEN $action = fn () => new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@example.com'), new Matricule('1234567'), '', @@ -269,7 +269,7 @@ describe('Shopper', function (): void { it('throws exception if prenom is empty', function (): void { // WHEN $action = fn () => new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@example.com'), new Matricule('1234567'), 'Nom', diff --git a/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php b/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php index cb871fe1..84662577 100644 --- a/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/BasketProductTest.php @@ -12,7 +12,7 @@ use Domain\Models\ValueObjects\DiscountRate; use Domain\Models\ValueObjects\Entities\ProductId; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('BasketProduct', function () { @@ -36,7 +36,7 @@ describe('BasketProduct', function () { function getNewProduct(array $overrides = []): BasketProduct { return new BasketProduct( - id: new ProductId(Uuid::uuid7()), + id: new ProductId(UuidHelper::v7()), name: $overrides['name'] ?? 'Product Name', qty: $overrides['qty'] ?? 1, unitPriceHt: $overrides['unitPriceHt'] ?? getMoney(100), @@ -59,7 +59,7 @@ describe('BasketProduct', function () { it('can instantiate', function () { // GIVEN - $id = new ProductId(Uuid::uuid7()); + $id = new ProductId(UuidHelper::v7()); $name = 'Product Name'; $qty = 2; $unitPriceHt = getMoney(100); diff --git a/tests/Unit/Domain/Models/ValueObjects/ContactFormDataTest.php b/tests/Unit/Domain/Models/ValueObjects/ContactFormDataTest.php index dba19bb9..b047edab 100644 --- a/tests/Unit/Domain/Models/ValueObjects/ContactFormDataTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/ContactFormDataTest.php @@ -6,7 +6,7 @@ namespace Tests\Unit\Domain\Models\ValueObjects; use Domain\Models\ValueObjects\ContactFormData; use Domain\Models\ValueObjects\OrderReference; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('ContactFormData', function () { @@ -41,7 +41,7 @@ describe('ContactFormData', function () { $email = 'john@example.com'; $subject = 'Inquiry'; $message = 'This is a message.'; - $orderRef = new OrderReference(Uuid::uuid7()); + $orderRef = new OrderReference(UuidHelper::v7()); $file = null; // WHEN diff --git a/tests/Unit/Domain/Models/ValueObjects/EditablePickupExceptionForShopTest.php b/tests/Unit/Domain/Models/ValueObjects/EditablePickupExceptionForShopTest.php index aeecf155..b80cc4c4 100644 --- a/tests/Unit/Domain/Models/ValueObjects/EditablePickupExceptionForShopTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/EditablePickupExceptionForShopTest.php @@ -10,7 +10,7 @@ use Domain\Enums\RepeatFrequency; use Domain\Models\Entities\PickupExceptionOnDate; use Domain\Models\ValueObjects\EditablePickupExceptionForShop; use Domain\Models\ValueObjects\Entities\PickupExceptionId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; beforeEach(function (): void { $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); @@ -27,7 +27,7 @@ describe('EditablePickupExceptionForShop', function (): void { it('can instantiate and clones the exception', function (): void { // GIVEN $exception = new PickupExceptionOnDate( - new PickupExceptionId(Uuid::uuid7()), + new PickupExceptionId(UuidHelper::v7()), CarbonImmutable::now(), 'Label', true, diff --git a/tests/Unit/Domain/Models/ValueObjects/Entities/BasketIdTest.php b/tests/Unit/Domain/Models/ValueObjects/Entities/BasketIdTest.php index 636ec9fa..a2eab978 100644 --- a/tests/Unit/Domain/Models/ValueObjects/Entities/BasketIdTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/Entities/BasketIdTest.php @@ -5,12 +5,12 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\ValueObjects\Entities; use Domain\Models\ValueObjects\Entities\BasketId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('BasketId', function (): void { it('can be instantiated with a Uuid', function (): void { // GIVEN - $uuid = Uuid::uuid7(); + $uuid = UuidHelper::v7(); // WHEN $id = new BasketId($uuid); // THEN @@ -19,7 +19,7 @@ describe('BasketId', function (): void { it('throws exception with non v7 uuid', function (): void { // GIVEN - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); // WHEN $action = fn () => new BasketId($uuid); // THEN diff --git a/tests/Unit/Domain/Models/ValueObjects/Entities/OrderIdTest.php b/tests/Unit/Domain/Models/ValueObjects/Entities/OrderIdTest.php index f041a985..a3dc6aa6 100644 --- a/tests/Unit/Domain/Models/ValueObjects/Entities/OrderIdTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/Entities/OrderIdTest.php @@ -5,12 +5,12 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\ValueObjects\Entities; use Domain\Models\ValueObjects\Entities\OrderId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('OrderId', function (): void { it('can be instantiated with uuid v7', function (): void { // GIVEN - $uuid = Uuid::uuid7(); + $uuid = UuidHelper::v7(); // WHEN $id = new OrderId($uuid); // THEN @@ -19,7 +19,7 @@ describe('OrderId', function (): void { it('throws exception with non v7 uuid', function (): void { // GIVEN - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); // WHEN $action = fn () => new OrderId($uuid); // THEN diff --git a/tests/Unit/Domain/Models/ValueObjects/Entities/PickupExceptionIdTest.php b/tests/Unit/Domain/Models/ValueObjects/Entities/PickupExceptionIdTest.php index 22198a86..b90e7cda 100644 --- a/tests/Unit/Domain/Models/ValueObjects/Entities/PickupExceptionIdTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/Entities/PickupExceptionIdTest.php @@ -5,12 +5,12 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\ValueObjects\Entities; use Domain\Models\ValueObjects\Entities\PickupExceptionId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('PickupExceptionId', function (): void { it('can be instantiated with uuid', function (): void { // GIVEN - $uuid = Uuid::uuid7(); + $uuid = UuidHelper::v7(); // WHEN $id = new PickupExceptionId($uuid); // THEN @@ -19,7 +19,7 @@ describe('PickupExceptionId', function (): void { it('throws exception with non v7 uuid', function (): void { // GIVEN - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); // WHEN $action = fn () => new PickupExceptionId($uuid); // THEN diff --git a/tests/Unit/Domain/Models/ValueObjects/Entities/ProductIdTest.php b/tests/Unit/Domain/Models/ValueObjects/Entities/ProductIdTest.php index 038fe1c4..210f0c1c 100644 --- a/tests/Unit/Domain/Models/ValueObjects/Entities/ProductIdTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/Entities/ProductIdTest.php @@ -5,12 +5,12 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\ValueObjects\Entities; use Domain\Models\ValueObjects\Entities\ProductId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('ProductId', function (): void { it('can be instantiated with uuid v7', function (): void { // GIVEN - $uuid = Uuid::uuid7(); + $uuid = UuidHelper::v7(); // WHEN $id = new ProductId($uuid); // THEN @@ -19,7 +19,7 @@ describe('ProductId', function (): void { it('throws exception with non v7 uuid', function (): void { // GIVEN - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); // WHEN $action = fn () => new ProductId($uuid); // THEN diff --git a/tests/Unit/Domain/Models/ValueObjects/Entities/ShopIdTest.php b/tests/Unit/Domain/Models/ValueObjects/Entities/ShopIdTest.php index bf78dcf3..760ec452 100644 --- a/tests/Unit/Domain/Models/ValueObjects/Entities/ShopIdTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/Entities/ShopIdTest.php @@ -5,12 +5,12 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\ValueObjects\Entities; use Domain\Models\ValueObjects\Entities\ShopId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('ShopId', function (): void { it('can be instantiated with uuid', function (): void { // GIVEN - $uuid = Uuid::uuid7(); + $uuid = UuidHelper::v7(); // WHEN $id = new ShopId($uuid); // THEN @@ -19,7 +19,7 @@ describe('ShopId', function (): void { it('throws exception with non v7 uuid', function (): void { // GIVEN - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); // WHEN $action = fn () => new ShopId($uuid); // THEN diff --git a/tests/Unit/Domain/Models/ValueObjects/Entities/ShopperIdTest.php b/tests/Unit/Domain/Models/ValueObjects/Entities/ShopperIdTest.php index 46e8a2d9..2cdf257e 100644 --- a/tests/Unit/Domain/Models/ValueObjects/Entities/ShopperIdTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/Entities/ShopperIdTest.php @@ -5,12 +5,12 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\ValueObjects\Entities; use Domain\Models\ValueObjects\Entities\ShopperId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('ShopperId', function (): void { it('can be instantiated with uuid v7', function (): void { // GIVEN - $uuid = Uuid::uuid7(); + $uuid = UuidHelper::v7(); // WHEN $id = new ShopperId($uuid); // THEN @@ -19,7 +19,7 @@ describe('ShopperId', function (): void { it('throws exception with non v7 uuid', function (): void { // GIVEN - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); // WHEN $action = fn () => new ShopperId($uuid); // THEN diff --git a/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php b/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php index 3d262ae6..a414ee18 100644 --- a/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php @@ -12,14 +12,14 @@ use Domain\Models\ValueObjects\IncoId; use Domain\Models\ValueObjects\OrderLineProduct; use Domain\Models\ValueObjects\ProductWeight; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('OrderLineProduct', function (): void { it('can instantiate correctly', function (): void { // GIVEN $incoId = new IncoId(123); - $productId = new ProductId(Uuid::uuid7()); + $productId = new ProductId(UuidHelper::v7()); $weight = new ProductWeight(500, false); $product = new OrderLineProduct( @@ -56,7 +56,7 @@ describe('OrderLineProduct', function (): void { // WHEN $action = fn () => new OrderLineProduct( new IncoId(1), - new ProductId(Uuid::uuid7()), + new ProductId(UuidHelper::v7()), '', new ProductWeight(1, false), ProductBrand::marie, @@ -75,7 +75,7 @@ describe('OrderLineProduct', function (): void { // WHEN $action = fn () => new OrderLineProduct( new IncoId(1), - new ProductId(Uuid::uuid7()), + new ProductId(UuidHelper::v7()), 'Name', new ProductWeight(1, false), ProductBrand::marie, @@ -94,7 +94,7 @@ describe('OrderLineProduct', function (): void { // WHEN $action = fn () => new OrderLineProduct( new IncoId(1), - new ProductId(Uuid::uuid7()), + new ProductId(UuidHelper::v7()), 'Name', new ProductWeight(1, false), ProductBrand::marie, @@ -113,7 +113,7 @@ describe('OrderLineProduct', function (): void { // WHEN $action = fn () => new OrderLineProduct( new IncoId(1), - new ProductId(Uuid::uuid7()), + new ProductId(UuidHelper::v7()), 'Name', new ProductWeight(1, false), ProductBrand::marie, @@ -132,7 +132,7 @@ describe('OrderLineProduct', function (): void { // WHEN $action = fn () => new OrderLineProduct( new IncoId(1), - new ProductId(Uuid::uuid7()), + new ProductId(UuidHelper::v7()), 'Name', new ProductWeight(1, false), ProductBrand::marie, @@ -151,7 +151,7 @@ describe('OrderLineProduct', function (): void { // WHEN $action = fn () => new OrderLineProduct( new IncoId(1), - new ProductId(Uuid::uuid7()), + new ProductId(UuidHelper::v7()), 'Name', new ProductWeight(1, false), ProductBrand::marie, diff --git a/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php b/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php index be8082be..e18c659b 100644 --- a/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php @@ -13,14 +13,14 @@ use Domain\Models\ValueObjects\OrderLine; use Domain\Models\ValueObjects\OrderLineProduct; use Domain\Models\ValueObjects\ProductWeight; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('OrderLine', function (): void { function getNewOrderLineProduct(): OrderLineProduct { return new OrderLineProduct( incoId: new IncoId(1), - originalId: new ProductId(Uuid::uuid7()), + originalId: new ProductId(UuidHelper::v7()), name: 'poulet blanc', weight: new ProductWeight(200, false), brand: ProductBrand::loue, diff --git a/tests/Unit/Domain/Models/ValueObjects/OrderReferenceTest.php b/tests/Unit/Domain/Models/ValueObjects/OrderReferenceTest.php index bfb0eb79..fca35822 100644 --- a/tests/Unit/Domain/Models/ValueObjects/OrderReferenceTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/OrderReferenceTest.php @@ -5,7 +5,6 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\ValueObjects; use Domain\Models\ValueObjects\OrderReference; -use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; use Shared\Helpers\UuidHelper; @@ -17,7 +16,7 @@ describe('OrderReference', function () { it('can instantiate with a valid UUID v7', function () { // GIVEN - $uuidV7 = Uuid::uuid7(); + $uuidV7 = UuidHelper::v7(); // WHEN $vo = getNewOrderReference($uuidV7); @@ -29,7 +28,7 @@ describe('OrderReference', function () { it('can instantiate from a valid base-58 UUID v7 string', function () { // GIVEN - $uuidV7 = Uuid::uuid7(); + $uuidV7 = UuidHelper::v7(); $base58 = UuidHelper::toBase58($uuidV7); // WHEN @@ -42,7 +41,7 @@ describe('OrderReference', function () { it('can instantiate from a valid UUID v7 string via fromString', function () { // GIVEN - $uuidV7 = Uuid::uuid7(); + $uuidV7 = UuidHelper::v7(); $uuidString = $uuidV7->toString(); // WHEN @@ -55,7 +54,7 @@ describe('OrderReference', function () { it('can instantiate from a valid base-58 string via fromString', function () { // GIVEN - $uuidV7 = Uuid::uuid7(); + $uuidV7 = UuidHelper::v7(); $base58 = UuidHelper::toBase58($uuidV7); // WHEN @@ -68,7 +67,7 @@ describe('OrderReference', function () { it('throws exception if provided UUID is not v7', function () { // GIVEN - $uuidV4 = Uuid::uuid4(); + $uuidV4 = UuidHelper::v4(); // WHEN $action = fn () => getNewOrderReference($uuidV4); @@ -90,7 +89,7 @@ describe('OrderReference', function () { it('throws exception if base-58 string is not from a UUID v7', function () { // GIVEN - $uuidV4 = Uuid::uuid4(); + $uuidV4 = UuidHelper::v4(); $base58 = UuidHelper::toBase58($uuidV4); // WHEN diff --git a/tests/Unit/Domain/Models/ValueObjects/SessionIdTest.php b/tests/Unit/Domain/Models/ValueObjects/SessionIdTest.php index 45774709..659d560c 100644 --- a/tests/Unit/Domain/Models/ValueObjects/SessionIdTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/SessionIdTest.php @@ -5,12 +5,12 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\ValueObjects; use Domain\Models\ValueObjects\SessionId; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; describe('SessionId', function (): void { it('can be instantiated with a valid uuid', function (): void { // GIVEN - $uuid = Uuid::uuid7(); + $uuid = UuidHelper::v7(); // WHEN $id = new SessionId($uuid); // THEN @@ -19,7 +19,7 @@ describe('SessionId', function (): void { it('throws exception with non v7 uuid', function (): void { // GIVEN - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); // WHEN $action = fn () => new SessionId($uuid); // THEN diff --git a/tests/Unit/Domain/Models/ValueObjects/ShopPickupOverrideTest.php b/tests/Unit/Domain/Models/ValueObjects/ShopPickupOverrideTest.php index 5ba7c9fe..bcbb9894 100644 --- a/tests/Unit/Domain/Models/ValueObjects/ShopPickupOverrideTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/ShopPickupOverrideTest.php @@ -10,7 +10,7 @@ use Domain\Enums\RepeatFrequency; use Domain\Models\Entities\PickupExceptionOnDate; use Domain\Models\ValueObjects\Entities\PickupExceptionId; use Domain\Models\ValueObjects\ShopPickupOverride; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; beforeEach(function (): void { $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); @@ -27,7 +27,7 @@ describe('ShopPickupOverride', function (): void { it('can instantiate correctly', function (): void { // GIVEN $exception = new PickupExceptionOnDate( - new PickupExceptionId(Uuid::uuid7()), + new PickupExceptionId(UuidHelper::v7()), CarbonImmutable::now(), 'Label', true, @@ -54,7 +54,7 @@ describe('ShopPickupOverride', function (): void { it('throws exception if orderDeadlineAt is not strictly before replacementDate', function (): void { // GIVEN $exception = new PickupExceptionOnDate( - new PickupExceptionId(Uuid::uuid7()), + new PickupExceptionId(UuidHelper::v7()), CarbonImmutable::now(), 'Label', true, @@ -79,7 +79,7 @@ describe('ShopPickupOverride', function (): void { it('correctly handles replacement and deadlines', function (): void { // GIVEN $exception = new PickupExceptionOnDate( - new PickupExceptionId(Uuid::uuid7()), + new PickupExceptionId(UuidHelper::v7()), CarbonImmutable::parse('2025-05-01'), 'Labour Day', false, diff --git a/tests/Unit/Domain/Services/BasketServiceTest.php b/tests/Unit/Domain/Services/BasketServiceTest.php index 8ec78b91..79859e5a 100644 --- a/tests/Unit/Domain/Services/BasketServiceTest.php +++ b/tests/Unit/Domain/Services/BasketServiceTest.php @@ -22,15 +22,15 @@ use Domain\Ports\Services\SessionService; use Domain\Services\BasketService; use Mockery; use Money\Money; -use Ramsey\Uuid\Uuid; use Shared\DDD\DomainEventDispatcher; +use Shared\Helpers\UuidHelper; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; /** @param array{id?: ProductId, qty?: int, unitPriceHt?: Money, unitDiscount?: Money} $overrides */ function makeBasketProduct(array $overrides = []): BasketProduct { return new BasketProduct( - id: $overrides['id'] ?? new ProductId(Uuid::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')), + id: $overrides['id'] ?? new ProductId(UuidHelper::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')), name: 'Poulet Rôti', qty: $overrides['qty'] ?? 1, unitPriceHt: $overrides['unitPriceHt'] ?? Money::EUR(1000), @@ -52,14 +52,14 @@ function makeBasketProduct(array $overrides = []): BasketProduct describe('BasketService', function (): void { it('adds a new product to the basket and dispatches BasketHasBeenModified', function (): void { // GIVEN - $productId = new ProductId(Uuid::uuid7()); + $productId = new ProductId(UuidHelper::v7()); $qty = 2; - $basket = new Basket(new BasketId(Uuid::uuid7())); + $basket = new Basket(new BasketId(UuidHelper::v7())); $basketProduct = makeBasketProduct(['id' => $productId, 'qty' => $qty]); $basketRepository = Mockery::mock(BasketRepository::class); $sessionService = Mockery::mock(SessionService::class); - $sessionService->shouldReceive('get')->andReturn(new SessionId(Uuid::uuid7()))->byDefault(); + $sessionService->shouldReceive('get')->andReturn(new SessionId(UuidHelper::v7()))->byDefault(); $basketRepository->shouldReceive('find')->once()->andReturn($basket); $basketRepository->shouldReceive('persist')->once()->with(Mockery::on(function (Basket $b) use ($productId) { return $b->has($productId) && $b->countItems() === 2; @@ -84,13 +84,13 @@ describe('BasketService', function (): void { it('removes a quantity from the basket and dispatches BasketHasBeenModified', function (): void { // GIVEN - $productId = new ProductId(Uuid::uuid7()); - $basket = new Basket(new BasketId(Uuid::uuid7())); + $productId = new ProductId(UuidHelper::v7()); + $basket = new Basket(new BasketId(UuidHelper::v7())); $basket->addOrUpdate(makeBasketProduct(['id' => $productId, 'qty' => 3])); $basketRepository = Mockery::mock(BasketRepository::class); $sessionService = Mockery::mock(SessionService::class); - $sessionService->shouldReceive('get')->andReturn(new SessionId(Uuid::uuid7()))->byDefault(); + $sessionService->shouldReceive('get')->andReturn(new SessionId(UuidHelper::v7()))->byDefault(); $basketRepository->shouldReceive('find')->once()->andReturn($basket); $basketRepository->shouldReceive('persist')->once()->with(Mockery::on(function (Basket $b) use ($productId) { $items = $b->items(); @@ -117,13 +117,13 @@ describe('BasketService', function (): void { it('removes the entire line when quantity to remove equals current quantity', function (): void { // GIVEN - $productId = new ProductId(Uuid::uuid7()); - $basket = new Basket(new BasketId(Uuid::uuid7())); + $productId = new ProductId(UuidHelper::v7()); + $basket = new Basket(new BasketId(UuidHelper::v7())); $basket->addOrUpdate(makeBasketProduct(['id' => $productId, 'qty' => 3])); $basketRepository = Mockery::mock(BasketRepository::class); $sessionService = Mockery::mock(SessionService::class); - $sessionService->shouldReceive('get')->andReturn(new SessionId(Uuid::uuid7()))->byDefault(); + $sessionService->shouldReceive('get')->andReturn(new SessionId(UuidHelper::v7()))->byDefault(); $basketRepository->shouldReceive('find')->once()->andReturn($basket); $basketRepository->shouldReceive('persist')->once()->with(Mockery::on(function (Basket $b) use ($productId) { return ! $b->has($productId); @@ -147,13 +147,13 @@ describe('BasketService', function (): void { it('removes an entire line directly via removeLine and dispatches BasketHasBeenModified', function (): void { // GIVEN - $productId = new ProductId(Uuid::uuid7()); - $basket = new Basket(new BasketId(Uuid::uuid7())); + $productId = new ProductId(UuidHelper::v7()); + $basket = new Basket(new BasketId(UuidHelper::v7())); $basket->addOrUpdate(makeBasketProduct(['id' => $productId, 'qty' => 5])); $basketRepository = Mockery::mock(BasketRepository::class); $sessionService = Mockery::mock(SessionService::class); - $sessionService->shouldReceive('get')->andReturn(new SessionId(Uuid::uuid7()))->byDefault(); + $sessionService->shouldReceive('get')->andReturn(new SessionId(UuidHelper::v7()))->byDefault(); $basketRepository->shouldReceive('find')->once()->andReturn($basket); $basketRepository->shouldReceive('persist')->once()->with(Mockery::on(function (Basket $b) use ($productId) { return ! $b->has($productId); @@ -177,13 +177,13 @@ describe('BasketService', function (): void { it('empties the basket by destroying it from repository and dispatches BasketRemoved', function (): void { // GIVEN - $basket = new Basket(new BasketId(Uuid::uuid7())); + $basket = new Basket(new BasketId(UuidHelper::v7())); /** @var BasketRepository&\Mockery\MockInterface $basketRepository */ $basketRepository = Mockery::spy(BasketRepository::class); $basketRepository->allows('find')->andReturn($basket); $sessionService = Mockery::mock(SessionService::class); - $sessionService->shouldReceive('get')->andReturn(new SessionId(Uuid::uuid7()))->byDefault(); + $sessionService->shouldReceive('get')->andReturn(new SessionId(UuidHelper::v7()))->byDefault(); $productRepository = Mockery::mock(ProductRepository::class); @@ -204,10 +204,10 @@ describe('BasketService', function (): void { it('gets the basket from repository without dispatching events', function (): void { // GIVEN - $basket = new Basket(new BasketId(Uuid::uuid7())); + $basket = new Basket(new BasketId(UuidHelper::v7())); $basketRepository = Mockery::mock(BasketRepository::class); $sessionService = Mockery::mock(SessionService::class); - $sessionService->shouldReceive('get')->andReturn(new SessionId(Uuid::uuid7()))->byDefault(); + $sessionService->shouldReceive('get')->andReturn(new SessionId(UuidHelper::v7()))->byDefault(); $basketRepository->shouldReceive('find')->once()->andReturn($basket); $productRepository = Mockery::mock(ProductRepository::class); @@ -226,7 +226,7 @@ describe('BasketService', function (): void { it('returns a new basket if not found in repository', function (): void { // GIVEN - $sessionId = new SessionId(Uuid::uuid7()); + $sessionId = new SessionId(UuidHelper::v7()); $basketRepository = Mockery::mock(BasketRepository::class); $sessionService = Mockery::mock(SessionService::class); $sessionService->shouldReceive('get')->andReturn($sessionId)->byDefault(); @@ -249,7 +249,7 @@ describe('BasketService', function (): void { it('reports whether the basket has items', function (): void { // GIVEN - $sessionId = new SessionId(Uuid::uuid7()); + $sessionId = new SessionId(UuidHelper::v7()); $nonEmpty = new Basket(new BasketId($sessionId->value), [makeBasketProduct()]); $empty = new Basket(new BasketId($sessionId->value), []); $basketRepo = Mockery::mock(BasketRepository::class); diff --git a/tests/Unit/Domain/Services/OrderServiceTest.php b/tests/Unit/Domain/Services/OrderServiceTest.php index a19ada33..58089baa 100644 --- a/tests/Unit/Domain/Services/OrderServiceTest.php +++ b/tests/Unit/Domain/Services/OrderServiceTest.php @@ -38,7 +38,6 @@ use Domain\Ports\Repositories\OrderRepository; use Domain\Services\OrderService; use Mockery; use Money\Money; -use Ramsey\Uuid\Uuid; use Shared\Helpers\UuidHelper; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; @@ -56,12 +55,12 @@ afterEach(function (): void { describe('Order Cancellation', function () { it('cancels a validated order successfully', function () { // GIVEN - $orderId = new OrderId(Uuid::uuid7()); + $orderId = new OrderId(UuidHelper::v7()); $order = new Order( id: $orderId, - shopId: new ShopId(Uuid::uuid7()), - reference: new OrderReference(Uuid::uuid7()), + shopId: new ShopId(UuidHelper::v7()), + reference: new OrderReference(UuidHelper::v7()), employee: new OrderEmployee( new Matricule('1234567'), 'Jean', @@ -87,7 +86,7 @@ describe('Order Cancellation', function () { new OrderLine( product: new OrderLineProduct( incoId: new IncoId(45), - originalId: new ProductId(Uuid::uuid7()), + originalId: new ProductId(UuidHelper::v7()), name: 'Poulet Rôti', weight: new ProductWeight(1200, false), brand: ProductBrand::marie, @@ -125,7 +124,7 @@ describe('Order Cancellation', function () { it('throws exception if order not found', function () { // GIVEN - $orderId = new OrderId(Uuid::uuid7()); + $orderId = new OrderId(UuidHelper::v7()); /** @var OrderRepository|\Mockery\MockInterface $repository */ $repository = Mockery::mock(OrderRepository::class); @@ -142,13 +141,13 @@ describe('Order Cancellation', function () { it('validates and fails pending orders using findForUpdate', function () { // GIVEN - $pendingId = new OrderId(Uuid::uuid7()); - $failedId = new OrderId(Uuid::uuid7()); + $pendingId = new OrderId(UuidHelper::v7()); + $failedId = new OrderId(UuidHelper::v7()); $makeOrderWithStatus = static fn (OrderId $id, OrderStatus $status): Order => new Order( id: $id, - shopId: new ShopId(Uuid::uuid7()), - reference: new OrderReference(Uuid::uuid7()), + shopId: new ShopId(UuidHelper::v7()), + reference: new OrderReference(UuidHelper::v7()), employee: new OrderEmployee( new Matricule('1234567'), 'Jean', @@ -174,7 +173,7 @@ describe('Order Cancellation', function () { new OrderLine( product: new OrderLineProduct( incoId: new IncoId(45), - originalId: new ProductId(Uuid::uuid7()), + originalId: new ProductId(UuidHelper::v7()), name: 'Poulet Rôti', weight: new ProductWeight(1200, false), brand: ProductBrand::marie, @@ -221,11 +220,11 @@ describe('Order Cancellation', function () { describe('Order Creation', function () { it('creates an order from a basket correctly', function () { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); $basketProduct = new BasketProduct( - id: new ProductId(Uuid::uuid7()), + id: new ProductId(UuidHelper::v7()), name: 'Poulet Rôti', qty: 2, unitPriceHt: Money::EUR(1000), @@ -250,7 +249,7 @@ describe('Order Creation', function () { ); $shopper = new Shopper( - id: new ShopperId(Uuid::uuid7()), + id: new ShopperId(UuidHelper::v7()), email: new Email('jean.dupont@example.com'), matricule: new Matricule('1234567'), nom: 'Dupont', @@ -263,7 +262,7 @@ describe('Order Creation', function () { ); $shop = new Shop( - id: new ShopId(Uuid::uuid7()), + id: new ShopId(UuidHelper::v7()), name: 'Cocotte Lyon', address: '12 rue de la Paix', postcode: '69001', @@ -330,11 +329,11 @@ describe('Order Creation', function () { it('throws exception if basket product has no incoId', function () { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); $basketProduct = new BasketProduct( - id: new ProductId(Uuid::uuid7()), + id: new ProductId(UuidHelper::v7()), name: 'Poulet Rôti', qty: 2, unitPriceHt: Money::EUR(1000), @@ -355,7 +354,7 @@ describe('Order Creation', function () { $pickupTimeSlot = new PickupTimeSlot(new \DateTimeImmutable(), new \DateInterval('PT10M')); $shopper = new Shopper( - id: new ShopperId(Uuid::uuid7()), + id: new ShopperId(UuidHelper::v7()), email: new Email('a@a.com'), matricule: new Matricule('1234567'), nom: 'A', @@ -367,7 +366,7 @@ describe('Order Creation', function () { service: new ShopperServiceCode('101') ); $shop = new Shop( - id: new ShopId(Uuid::uuid7()), + id: new ShopId(UuidHelper::v7()), name: 'S', address: 'A', postcode: 'P', diff --git a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php index 360c6b3d..d4b97612 100644 --- a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php +++ b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php @@ -55,15 +55,15 @@ use Domain\Services\PickupSchedulingService; use Domain\Services\ShopperService; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; use Shared\DDD\DomainEventDispatcher; +use Shared\Helpers\UuidHelper; function createTestBasket(int $qty = 0): Basket { $items = []; if ($qty > 0) { - $productId = new ProductId(Uuid::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')); + $productId = new ProductId(UuidHelper::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')); $basketProduct = new BasketProduct( id: $productId, name: 'Test Product', @@ -85,7 +85,7 @@ function createTestBasket(int $qty = 0): Basket $items[(string) $productId->value] = $basketProduct; } - $basketId = new BasketId(Uuid::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')); + $basketId = new BasketId(UuidHelper::fromString('019e9e37-f2a1-74ef-b9c2-66d222470128')); return new Basket($basketId, $items); } @@ -96,11 +96,11 @@ function createTestBasket(int $qty = 0): Basket function createTestBuilder(bool $completed = false): OrderBuilderWithBasket { $basket = createTestBasket(1); - $shopperId = new ShopperId(Uuid::uuid7()); + $shopperId = new ShopperId(UuidHelper::v7()); $builder = OrderBuilder::fromBasket($basket, $shopperId); if ($completed) { - $shopId = new ShopId(Uuid::uuid7()); + $shopId = new ShopId(UuidHelper::v7()); $nextFriday = CarbonImmutable::now('Europe/Paris')->next(WeekDay::Friday->value)->addWeek()->startOfDay(); $timeSlot = new PickupTimeSlot($nextFriday, new \DateInterval('PT1H')); @@ -224,7 +224,7 @@ describe('OrderTunnelService', function (): void { it('denies access to BOOKING step when builder has an empty basket', function (): void { // GIVEN - $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(Uuid::uuid7())); + $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(UuidHelper::v7())); $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn($builder); @@ -291,10 +291,11 @@ describe('OrderTunnelService', function (): void { it('denies access to CONFIRMATION step when builder has an empty basket', function (): void { // GIVEN - $shopId = new ShopId(Uuid::uuid7()); + $shopId = new ShopId(UuidHelper::v7()); $nextFriday = CarbonImmutable::now('Europe/Paris')->next(WeekDay::Friday->value)->addWeek()->startOfDay(); $timeSlot = new PickupTimeSlot($nextFriday, new \DateInterval('PT1H')); - $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(Uuid::uuid7()))->withPickupTimeSlot($shopId, $timeSlot); + $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(UuidHelper::v7())) + ->withPickupTimeSlot($shopId, $timeSlot); $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn($builder); @@ -327,7 +328,7 @@ describe('OrderTunnelService', function (): void { it('gets shop for customer successfully', function (): void { // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); + $shopperId = new ShopperId(UuidHelper::v7()); $shopper = new Shopper( id: $shopperId, email: new Email('test@test.com'), @@ -341,7 +342,7 @@ describe('OrderTunnelService', function (): void { service: new ShopperServiceCode('101') ); - $shopId = new ShopId(Uuid::uuid7()); + $shopId = new ShopId(UuidHelper::v7()); $shop = new Shop( id: $shopId, name: 'Shop', @@ -373,7 +374,7 @@ describe('OrderTunnelService', function (): void { it('throws exception when get shop for customer fails', function (): void { // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); + $shopperId = new ShopperId(UuidHelper::v7()); $shopperRepo = \Mockery::mock(ShopperRepository::class); $shopperRepo->shouldReceive('find')->with($shopperId)->andReturn(null); @@ -387,7 +388,7 @@ describe('OrderTunnelService', function (): void { it('gets available time slots', function (): void { // GIVEN - $shopId = new ShopId(Uuid::uuid7()); + $shopId = new ShopId(UuidHelper::v7()); $shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris'); $pickupExceptionRepo = \Mockery::mock(PickupExceptionRepository::class); @@ -405,7 +406,7 @@ describe('OrderTunnelService', function (): void { it('initializes order from basket', function (): void { // GIVEN $basket = createTestBasket(1); - $customerId = new ShopperId(Uuid::uuid7()); + $customerId = new ShopperId(UuidHelper::v7()); /** @var OrderBuilderSessionManager&\Mockery\MockInterface $orderBuilderRepo */ $orderBuilderRepo = \Mockery::spy(OrderBuilderSessionManager::class); @@ -449,7 +450,7 @@ describe('OrderTunnelService', function (): void { it('throws exception in getBuilderFromBasketOrFail when builder has an empty basket', function (): void { // GIVEN - $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(Uuid::uuid7())); + $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(UuidHelper::v7())); $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepo->shouldReceive('get')->once()->andReturn($builder); @@ -493,10 +494,10 @@ describe('OrderTunnelService', function (): void { it('throws exception in getBuilderCompletedOrFail when builder has an empty basket', function (): void { // GIVEN - $shopId = new ShopId(Uuid::uuid7()); + $shopId = new ShopId(UuidHelper::v7()); $nextFriday = CarbonImmutable::now('Europe/Paris')->next(WeekDay::Friday->value)->addWeek()->startOfDay(); $timeSlot = new PickupTimeSlot($nextFriday, new \DateInterval('PT1H')); - $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(Uuid::uuid7()))->withPickupTimeSlot($shopId, $timeSlot); + $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(UuidHelper::v7()))->withPickupTimeSlot($shopId, $timeSlot); $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepo->shouldReceive('get')->once()->andReturn($builder); @@ -513,7 +514,7 @@ describe('OrderTunnelService', function (): void { it('applies time slot', function (): void { // GIVEN $builder = createTestBuilder(completed: false); - $shop = new Shop(new ShopId(Uuid::uuid7()), 'Shop', 'Address', '75000', 'Paris'); + $shop = new Shop(new ShopId(UuidHelper::v7()), 'Shop', 'Address', '75000', 'Paris'); $selectedDate = CarbonImmutable::parse('2025-01-01'); $ts1 = new PickupTimeSlot($selectedDate, new \DateInterval('PT1H')); $ts2 = new PickupTimeSlot(CarbonImmutable::parse('2025-01-02'), new \DateInterval('PT1H')); @@ -534,7 +535,7 @@ describe('OrderTunnelService', function (): void { it('returns null if no matching time slot', function (): void { // GIVEN $builder = createTestBuilder(completed: false); - $shop = new Shop(new ShopId(Uuid::uuid7()), 'Shop', 'Address', '75000', 'Paris'); + $shop = new Shop(new ShopId(UuidHelper::v7()), 'Shop', 'Address', '75000', 'Paris'); $selectedDate = CarbonImmutable::parse('2025-01-01'); $ts1 = new PickupTimeSlot(CarbonImmutable::parse('2025-01-02'), new \DateInterval('PT1H')); $availableSlots = [$ts1]; @@ -765,8 +766,8 @@ describe('OrderTunnelService', function (): void { it('throws ExpiredPickupTimeSlotException when finalizing order with an expired or unavailable pickup time slot', function (): void { // GIVEN $basket = createTestBasket(1); - $shopperId = new ShopperId(Uuid::uuid7()); - $shopId = new ShopId(Uuid::uuid7()); + $shopperId = new ShopperId(UuidHelper::v7()); + $shopId = new ShopId(UuidHelper::v7()); $expiredSlot = new PickupTimeSlot(CarbonImmutable::parse('2025-01-01'), new \DateInterval('PT1H')); $builder = OrderBuilder::fromBasket($basket, $shopperId)->withPickupTimeSlot($shopId, $expiredSlot); @@ -984,10 +985,10 @@ describe('OrderTunnelService', function (): void { it('exports, confirms and fails a pending order across split steps', function (): void { // GIVEN - $shopId = new ShopId(Uuid::uuid7()); + $shopId = new ShopId(UuidHelper::v7()); $shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris'); $shopper = new Shopper( - id: new ShopperId(Uuid::uuid7()), + id: new ShopperId(UuidHelper::v7()), email: new Email('split@test.com'), matricule: new Matricule('1234567'), nom: 'Doe', @@ -1000,16 +1001,16 @@ describe('OrderTunnelService', function (): void { ); $basket = createTestBasket(1); $orderToOk = Order::pendingFromBasket( - new OrderId(Uuid::uuid7()), - new OrderReference(Uuid::uuid7()), + new OrderId(UuidHelper::v7()), + new OrderReference(UuidHelper::v7()), $basket, new PickupTimeSlot(CarbonImmutable::now()->next('Friday'), new \DateInterval('PT1H')), $shopper, $shop ); $orderToKo = Order::pendingFromBasket( - new OrderId(Uuid::uuid7()), - new OrderReference(Uuid::uuid7()), + new OrderId(UuidHelper::v7()), + new OrderReference(UuidHelper::v7()), $basket, new PickupTimeSlot(CarbonImmutable::now()->next('Friday'), new \DateInterval('PT1H')), $shopper, @@ -1050,7 +1051,7 @@ describe('OrderTunnelService', function (): void { it('records a tunnel attempt when initializing from basket', function (): void { // GIVEN $basket = createTestBasket(1); - $customerId = new ShopperId(Uuid::uuid7()); + $customerId = new ShopperId(UuidHelper::v7()); $recorded = false; $orderBuilderSessionManager = \Mockery::mock(OrderBuilderSessionManager::class); @@ -1078,10 +1079,10 @@ describe('OrderTunnelService', function (): void { it('marks the tunnel attempt converted when confirming a placed order', function (): void { // GIVEN - $shopId = new ShopId(Uuid::uuid7()); + $shopId = new ShopId(UuidHelper::v7()); $shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris'); $shopper = new Shopper( - id: new ShopperId(Uuid::uuid7()), + id: new ShopperId(UuidHelper::v7()), email: new Email('convert@test.com'), matricule: new Matricule('1234567'), nom: 'Doe', @@ -1094,8 +1095,8 @@ describe('OrderTunnelService', function (): void { ); $basket = createTestBasket(1); $order = Order::pendingFromBasket( - new OrderId(Uuid::uuid7()), - new OrderReference(Uuid::uuid7()), + new OrderId(UuidHelper::v7()), + new OrderReference(UuidHelper::v7()), $basket, new PickupTimeSlot(CarbonImmutable::now()->next('Friday'), new \DateInterval('PT1H')), $shopper, diff --git a/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php b/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php index 9996f64e..db191a6b 100644 --- a/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php +++ b/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php @@ -16,12 +16,12 @@ use Domain\Models\ValueObjects\PickupWindow; use Domain\Models\ValueObjects\ShopPickupOverride; use Domain\Ports\Repositories\PickupExceptionRepository; use Domain\Services\PickupSchedulingService; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; function createTestShop(int $id = 1): Shop { return new Shop( - id: new ShopId(Uuid::uuid7()), + id: new ShopId(UuidHelper::v7()), name: 'Test Shop', address: '1 rue de Paris', postcode: '75000', @@ -314,7 +314,7 @@ describe('Pickup Scheduling Service', function (): void { $now = CarbonImmutable::parse('2026-05-04 10:00:00'); $exception1 = new PickupExceptionOnDate( - id: new PickupExceptionId(Uuid::uuid7()), + id: new PickupExceptionId(UuidHelper::v7()), date: CarbonImmutable::parse('2026-05-08'), // Friday label: 'Test 1', repeatable: false, @@ -323,7 +323,7 @@ describe('Pickup Scheduling Service', function (): void { ); $exception2 = new PickupExceptionOnDate( - id: new PickupExceptionId(Uuid::uuid7()), + id: new PickupExceptionId(UuidHelper::v7()), date: CarbonImmutable::parse('2026-05-09'), // Saturday label: 'Test 2', repeatable: false, @@ -528,7 +528,7 @@ function createExceptionPivot(string $date, ?string $replacementDate = null, ?st static $idCounter = 1; $pickupSchedulingService = new PickupSchedulingService(\Mockery::mock(PickupExceptionRepository::class)); $exception = new PickupExceptionOnDate( - id: new PickupExceptionId(Uuid::uuid7()), + id: new PickupExceptionId(UuidHelper::v7()), date: CarbonImmutable::parse($date, $pickupSchedulingService->getCutoffTimezone()), label: 'Test Exception', repeatable: false, diff --git a/tests/Unit/Domain/Services/ShopperServiceTest.php b/tests/Unit/Domain/Services/ShopperServiceTest.php index 87901734..26b5b6b0 100644 --- a/tests/Unit/Domain/Services/ShopperServiceTest.php +++ b/tests/Unit/Domain/Services/ShopperServiceTest.php @@ -19,7 +19,7 @@ use Domain\Ports\Repositories\ShopperRepository; use Domain\Ports\Repositories\ShopRepository; use Domain\Services\ShopperService; use Mockery; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; beforeEach(function (): void { $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); @@ -40,7 +40,7 @@ describe('ShopperService', function (): void { $shopperRepo = Mockery::mock(ShopperRepository::class); $service = new ShopperService($shopRepo, $shopperRepo); - $id = new ShopperId(Uuid::uuid7()); + $id = new ShopperId(UuidHelper::v7()); $shopper = new Shopper( $id, new Email('test@test.com'), @@ -69,7 +69,7 @@ describe('ShopperService', function (): void { $service = new ShopperService($shopRepo, $shopperRepo); $shopper = new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@test.com'), new Matricule('1234567'), 'Nom', @@ -82,7 +82,7 @@ describe('ShopperService', function (): void { ); $shop = new Shop( - new ShopId(Uuid::uuid7()), + new ShopId(UuidHelper::v7()), 'Shop', 'Addr', '00000', @@ -104,7 +104,7 @@ describe('ShopperService', function (): void { $service = new ShopperService($shopRepo, $shopperRepo); $shopper = new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@test.com'), new Matricule('1234567'), 'Nom', @@ -116,7 +116,7 @@ describe('ShopperService', function (): void { new ShopperServiceCode('101') ); - $shop = new Shop(new ShopId(Uuid::uuid7()), 'Shop', 'Addr', '00000', 'City'); + $shop = new Shop(new ShopId(UuidHelper::v7()), 'Shop', 'Addr', '00000', 'City'); $shopRepo->shouldReceive('findExceptionShopFor')->once()->with($shopper->matricule)->andReturn(null); $shopRepo->shouldReceive('findShopForSiteAndService')->once()->with($shopper->site, $shopper->service)->andReturn($shop); @@ -134,7 +134,7 @@ describe('ShopperService', function (): void { $service = new ShopperService($shopRepo, $shopperRepo); $shopper = new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@test.com'), new Matricule('1234567'), 'Nom', @@ -146,7 +146,7 @@ describe('ShopperService', function (): void { new ShopperServiceCode('101') ); - $shop = new Shop(new ShopId(Uuid::uuid7()), 'Shop', 'Addr', '00000', 'City'); + $shop = new Shop(new ShopId(UuidHelper::v7()), 'Shop', 'Addr', '00000', 'City'); $shopRepo->shouldReceive('findExceptionShopFor')->once()->with($shopper->matricule)->andReturn(null); $shopRepo->shouldReceive('findShopForSiteAndService')->once()->with($shopper->site, $shopper->service)->andReturn(null); $shopRepo->shouldReceive('findShopForSiteAndService')->once()->with($shopper->site, null)->andReturn($shop); @@ -165,7 +165,7 @@ describe('ShopperService', function (): void { $service = new ShopperService($shopRepo, $shopperRepo); $shopper = new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@test.com'), new Matricule('1234567'), 'Nom', @@ -177,7 +177,7 @@ describe('ShopperService', function (): void { new ShopperServiceCode('101') ); - $shop = new Shop(new ShopId(Uuid::uuid7()), 'Shop', 'Addr', '00000', 'City'); + $shop = new Shop(new ShopId(UuidHelper::v7()), 'Shop', 'Addr', '00000', 'City'); $shopRepo->shouldReceive('findExceptionShopFor')->once()->with($shopper->matricule)->andReturn(null); $shopRepo->shouldReceive('findShopForSiteAndService')->once()->with($shopper->site, $shopper->service)->andReturn(null); $shopRepo->shouldReceive('findShopForSiteAndService')->once()->with($shopper->site, null)->andReturn(null); @@ -196,7 +196,7 @@ describe('ShopperService', function (): void { $shopperRepo = Mockery::mock(ShopperRepository::class); $service = new ShopperService($shopRepo, $shopperRepo); - $id = new ShopperId(Uuid::uuid7()); + $id = new ShopperId(UuidHelper::v7()); $shopperRepo->shouldReceive('find')->once()->with($id)->andReturn(null); // WHEN @@ -212,7 +212,7 @@ describe('ShopperService', function (): void { $shopperRepo = Mockery::mock(ShopperRepository::class); $service = new ShopperService($shopRepo, $shopperRepo); - $id = new ShopperId(Uuid::uuid7()); + $id = new ShopperId(UuidHelper::v7()); $shopper = new Shopper( $id, new Email('test@test.com'), @@ -227,7 +227,7 @@ describe('ShopperService', function (): void { ); $shop = new Shop( - new ShopId(Uuid::uuid7()), + new ShopId(UuidHelper::v7()), 'Shop', 'Addr', '00000', @@ -249,7 +249,7 @@ describe('ShopperService', function (): void { $shopperRepo = Mockery::mock(ShopperRepository::class); $service = new ShopperService($shopRepo, $shopperRepo); - $id = new ShopperId(Uuid::uuid7()); + $id = new ShopperId(UuidHelper::v7()); $shopperRepo->shouldReceive('find')->once()->with($id)->andReturn(null); // WHEN @@ -265,7 +265,7 @@ describe('ShopperService', function (): void { $shopperRepo = Mockery::mock(ShopperRepository::class); $service = new ShopperService($shopRepo, $shopperRepo); - $id = new ShopperId(Uuid::uuid7()); + $id = new ShopperId(UuidHelper::v7()); $shopper = new Shopper( $id, new Email('test@test.com'), diff --git a/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php b/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php index f71ef3db..b7dcebd8 100644 --- a/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php +++ b/tests/Unit/Infra/Adapters/Serializers/BasketSerializerTest.php @@ -16,192 +16,194 @@ use Domain\Models\ValueObjects\IncoId; use Infrastructure\Adapters\Serializers\BasketSerializer; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Uwil\Storage\Lib\ValueObjects\StorageFilePath; -it('serializes and deserializes basket correctly', function () { - // GIVEN - $serializer = new BasketSerializer(); +describe('BasketSerializer', function (): void { + it('serializes and deserializes basket correctly', function () { + // GIVEN + $serializer = new BasketSerializer(); - $basketIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); - $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); + $basketIdStr = UuidHelper::v7()->toString(); + $productIdStr = UuidHelper::v7()->toString(); - $basketProduct = new BasketProduct( - id: new ProductId(Uuid::fromString($productIdStr)), - name: 'Product 1', - qty: 2, - unitPriceHt: new Money(1000, new Currency('EUR')), - unitDiscount: new Money(100, new Currency('EUR')), - taxRate: TaxRate::TVA_20, - weightGrams: 500, - brand: ProductBrand::loue, - incoId: new IncoId(12345), - orderUnit: OrderUnit::PCE, - slug: 'product-1', - picture: new StorageFilePath('pic.png'), - description: 'desc', - weightVariable: true, - discountRate: DiscountRate::fromRatio(0.1), - priceKgTtc: new Money(2000, new Currency('EUR')), - options: ['color' => 'red'] - ); + $basketProduct = new BasketProduct( + id: new ProductId(UuidHelper::fromString($productIdStr)), + name: 'Product 1', + qty: 2, + unitPriceHt: new Money(1000, new Currency('EUR')), + unitDiscount: new Money(100, new Currency('EUR')), + taxRate: TaxRate::TVA_20, + weightGrams: 500, + brand: ProductBrand::loue, + incoId: new IncoId(12345), + orderUnit: OrderUnit::PCE, + slug: 'product-1', + picture: new StorageFilePath('pic.png'), + description: 'desc', + weightVariable: true, + discountRate: DiscountRate::fromRatio(0.1), + priceKgTtc: new Money(2000, new Currency('EUR')), + options: ['color' => 'red'] + ); - $basket = new Basket( - id: new BasketId(Uuid::fromString($basketIdStr)), - items: [$productIdStr => $basketProduct] - ); + $basket = new Basket( + id: new BasketId(UuidHelper::fromString($basketIdStr)), + items: [$productIdStr => $basketProduct] + ); - // WHEN - $array = $serializer->toArray($basket); - $json = json_encode($array, JSON_THROW_ON_ERROR); - /** @var array{id: string, items: array>} $array */ - $array = json_decode($json, true, 512, JSON_THROW_ON_ERROR); - $deserializedBasket = $serializer->fromArray($array); + // WHEN + $array = $serializer->toArray($basket); + $json = json_encode($array, JSON_THROW_ON_ERROR); + /** @var array{id: string, items: array>} $array */ + $array = json_decode($json, true, 512, JSON_THROW_ON_ERROR); + $deserializedBasket = $serializer->fromArray($array); - // THEN - expect($array['id'])->toBe($basketIdStr) - ->and($array['items'][0]['id'])->toBe($productIdStr) - ->and($array['items'][0]['name'])->toBe('Product 1') - ->and($array['items'][0]['taxRate'])->toBe(TaxRate::TVA_20->value) - ->and($deserializedBasket->id->value->toString())->toBe($basketIdStr) - ->and($deserializedBasket->items())->toHaveCount(1) - ->and($deserializedBasket->items()[$productIdStr]->name)->toBe('Product 1') - ->and($deserializedBasket->items()[$productIdStr]->weightVariable)->toBeTrue() - ->and($deserializedBasket->items()[$productIdStr]->options)->toBe(['color' => 'red']) - ->and($array['items'][0]['discountRateBp'])->toBe(1000) - ->and($deserializedBasket->items()[$productIdStr]->discountRate->basisPoints())->toBe(1000); -}); + // THEN + expect($array['id'])->toBe($basketIdStr) + ->and($array['items'][0]['id'])->toBe($productIdStr) + ->and($array['items'][0]['name'])->toBe('Product 1') + ->and($array['items'][0]['taxRate'])->toBe(TaxRate::TVA_20->value) + ->and($deserializedBasket->id->value->toString())->toBe($basketIdStr) + ->and($deserializedBasket->items())->toHaveCount(1) + ->and($deserializedBasket->items()[$productIdStr]->name)->toBe('Product 1') + ->and($deserializedBasket->items()[$productIdStr]->weightVariable)->toBeTrue() + ->and($deserializedBasket->items()[$productIdStr]->options)->toBe(['color' => 'red']) + ->and($array['items'][0]['discountRateBp'])->toBe(1000) + ->and($deserializedBasket->items()[$productIdStr]->discountRate->basisPoints())->toBe(1000); + }); -it('hydrates the discount rate from the legacy float ratio stored in older sessions', function (float $legacyRatio, int $expectedBasisPoints) { - // GIVEN - $serializer = new BasketSerializer(); - $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); - $data = [ - 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), - 'items' => [ - [ - 'id' => $productIdStr, - 'name' => 'Test', - 'qty' => 1, - 'unitPriceHt' => ['amount' => 1000, 'currency' => 'EUR'], - 'unitDiscount' => ['amount' => 100, 'currency' => 'EUR'], - 'taxRate' => TaxRate::TVA_20->value, - 'weightGrams' => 500, - 'orderUnit' => OrderUnit::PCE->value, - 'slug' => 'test', - 'weightVariable' => false, - 'discountRate' => $legacyRatio, - 'priceKgTtc' => ['amount' => 2000, 'currency' => 'EUR'], + it('hydrates the discount rate from the legacy float ratio stored in older sessions', function (float $legacyRatio, int $expectedBasisPoints) { + // GIVEN + $serializer = new BasketSerializer(); + $productIdStr = UuidHelper::v7()->toString(); + $data = [ + 'id' => UuidHelper::v7()->toString(), + 'items' => [ + [ + 'id' => $productIdStr, + 'name' => 'Test', + 'qty' => 1, + 'unitPriceHt' => ['amount' => 1000, 'currency' => 'EUR'], + 'unitDiscount' => ['amount' => 100, 'currency' => 'EUR'], + 'taxRate' => TaxRate::TVA_20->value, + 'weightGrams' => 500, + 'orderUnit' => OrderUnit::PCE->value, + 'slug' => 'test', + 'weightVariable' => false, + 'discountRate' => $legacyRatio, + 'priceKgTtc' => ['amount' => 2000, 'currency' => 'EUR'], + ], ], - ], - ]; + ]; - // WHEN - $basket = $serializer->fromArray($data); + // WHEN + $basket = $serializer->fromArray($data); - // THEN - expect($basket->items()[$productIdStr]->discountRate->basisPoints())->toBe($expectedBasisPoints); -})->with([ - 'regular ratio' => [0.15, 1500], - 'no discount' => [0.0, 0], - 'out of range value is clamped' => [20.0, 10000], -]); + // THEN + expect($basket->items()[$productIdStr]->discountRate->basisPoints())->toBe($expectedBasisPoints); + })->with([ + 'regular ratio' => [0.15, 1500], + 'no discount' => [0.0, 0], + 'out of range value is clamped' => [20.0, 10000], + ]); -it('throws exception if currency is missing during deserialization', function () { - // GIVEN - $serializer = new BasketSerializer(); - $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); - $data = [ - 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), - 'items' => [ - [ - 'id' => $productIdStr, - 'name' => 'Test', - 'qty' => 1, - 'unitPriceHt' => ['amount' => 1000, 'currency' => ''], - 'unitDiscount' => ['amount' => 100, 'currency' => 'EUR'], - 'taxRate' => TaxRate::TVA_20->value, - 'weightGrams' => 500, - 'orderUnit' => OrderUnit::PCE->value, - 'slug' => 'test', - 'weightVariable' => false, - 'priceKgTtc' => ['amount' => 2000, 'currency' => 'EUR'], + it('throws exception if currency is missing during deserialization', function () { + // GIVEN + $serializer = new BasketSerializer(); + $productIdStr = UuidHelper::v7()->toString(); + $data = [ + 'id' => UuidHelper::v7()->toString(), + 'items' => [ + [ + 'id' => $productIdStr, + 'name' => 'Test', + 'qty' => 1, + 'unitPriceHt' => ['amount' => 1000, 'currency' => ''], + 'unitDiscount' => ['amount' => 100, 'currency' => 'EUR'], + 'taxRate' => TaxRate::TVA_20->value, + 'weightGrams' => 500, + 'orderUnit' => OrderUnit::PCE->value, + 'slug' => 'test', + 'weightVariable' => false, + 'priceKgTtc' => ['amount' => 2000, 'currency' => 'EUR'], + ], ], - ], - ]; + ]; - // WHEN - $action = fn () => $serializer->fromArray($data); + // WHEN + $action = fn () => $serializer->fromArray($data); - // THEN - expect($action)->toThrow( - \DomainException::class, - 'Currency is required for unitPriceHt of item with id ' . $productIdStr - ); -}); + // THEN + expect($action)->toThrow( + \DomainException::class, + 'Currency is required for unitPriceHt of item with id ' . $productIdStr + ); + }); -it('throws exception if currency is missing for unitDiscount', function () { - // GIVEN - $serializer = new BasketSerializer(); - $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); - $data = [ - 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), - 'items' => [ - [ - 'id' => $productIdStr, - 'name' => 'Test', - 'qty' => 1, - 'unitPriceHt' => ['amount' => 1000, 'currency' => 'EUR'], - 'unitDiscount' => ['amount' => 100, 'currency' => ''], - 'taxRate' => TaxRate::TVA_20->value, - 'weightGrams' => 500, - 'orderUnit' => OrderUnit::PCE->value, - 'slug' => 'test', - 'weightVariable' => false, - 'priceKgTtc' => ['amount' => 2000, 'currency' => 'EUR'], + it('throws exception if currency is missing for unitDiscount', function () { + // GIVEN + $serializer = new BasketSerializer(); + $productIdStr = UuidHelper::v7()->toString(); + $data = [ + 'id' => UuidHelper::v7()->toString(), + 'items' => [ + [ + 'id' => $productIdStr, + 'name' => 'Test', + 'qty' => 1, + 'unitPriceHt' => ['amount' => 1000, 'currency' => 'EUR'], + 'unitDiscount' => ['amount' => 100, 'currency' => ''], + 'taxRate' => TaxRate::TVA_20->value, + 'weightGrams' => 500, + 'orderUnit' => OrderUnit::PCE->value, + 'slug' => 'test', + 'weightVariable' => false, + 'priceKgTtc' => ['amount' => 2000, 'currency' => 'EUR'], + ], ], - ], - ]; + ]; - // WHEN - $action = fn () => $serializer->fromArray($data); + // WHEN + $action = fn () => $serializer->fromArray($data); - // THEN - expect($action)->toThrow( - \DomainException::class, - 'Currency is required for unitDiscount of item with id ' . $productIdStr - ); -}); + // THEN + expect($action)->toThrow( + \DomainException::class, + 'Currency is required for unitDiscount of item with id ' . $productIdStr + ); + }); -it('throws exception if currency is missing for priceKgTtc', function () { - // GIVEN - $serializer = new BasketSerializer(); - $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); - $data = [ - 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), - 'items' => [ - [ - 'id' => $productIdStr, - 'name' => 'Test', - 'qty' => 1, - 'unitPriceHt' => ['amount' => 1000, 'currency' => 'EUR'], - 'unitDiscount' => ['amount' => 100, 'currency' => 'EUR'], - 'taxRate' => TaxRate::TVA_20->value, - 'weightGrams' => 500, - 'orderUnit' => OrderUnit::PCE->value, - 'slug' => 'test', - 'weightVariable' => false, - 'priceKgTtc' => ['amount' => 2000, 'currency' => ''], + it('throws exception if currency is missing for priceKgTtc', function () { + // GIVEN + $serializer = new BasketSerializer(); + $productIdStr = UuidHelper::v7()->toString(); + $data = [ + 'id' => UuidHelper::v7()->toString(), + 'items' => [ + [ + 'id' => $productIdStr, + 'name' => 'Test', + 'qty' => 1, + 'unitPriceHt' => ['amount' => 1000, 'currency' => 'EUR'], + 'unitDiscount' => ['amount' => 100, 'currency' => 'EUR'], + 'taxRate' => TaxRate::TVA_20->value, + 'weightGrams' => 500, + 'orderUnit' => OrderUnit::PCE->value, + 'slug' => 'test', + 'weightVariable' => false, + 'priceKgTtc' => ['amount' => 2000, 'currency' => ''], + ], ], - ], - ]; + ]; - // WHEN - $action = fn () => $serializer->fromArray($data); + // WHEN + $action = fn () => $serializer->fromArray($data); - // THEN - expect($action)->toThrow( - \DomainException::class, - 'Currency is required for priceKgTtc of item with id ' . $productIdStr - ); + // THEN + expect($action)->toThrow( + \DomainException::class, + 'Currency is required for priceKgTtc of item with id ' . $productIdStr + ); + }); }); From 7ae12f71fe38860052ccc60074b469f5a3890eec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Tue, 17 Nov 2026 12:15:45 +0100 Subject: [PATCH 179/183] test(arch): forbid direct Ramsey\Uuid\Uuid and Symfony\Component\Uid usage --- tests/Architecture/CodingStandardsTest.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/Architecture/CodingStandardsTest.php b/tests/Architecture/CodingStandardsTest.php index 040ab5f4..cf802d14 100644 --- a/tests/Architecture/CodingStandardsTest.php +++ b/tests/Architecture/CodingStandardsTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Tests\Architecture; use Shared\Filesystem\TemporaryFileFactory; +use Shared\Helpers\UuidHelper; use Symfony\Component\Finder\Finder; // Coding standards @@ -61,6 +62,16 @@ arch('all infrastructure source files use strict types') ->expect('Infrastructure') ->toUseStrictTypes(); +arch('Ramsey Uuid factory is encapsulated in UuidHelper') + ->expect('Ramsey\Uuid\Uuid') + ->not->toBeUsed() + ->ignoring([UuidHelper::class]); + +arch('Symfony Uid is encapsulated in UuidHelper') + ->expect('Symfony\Component\Uid') + ->not->toBeUsed() + ->ignoring([UuidHelper::class]); + it('enforces PSR-4 namespaces and bans anti-patterns across tests', function (): void { // GIVEN $testRoot = dirname(__DIR__); @@ -79,6 +90,12 @@ it('enforces PSR-4 namespaces and bans anti-patterns across tests', function (): ->and($contents)->not->toContain('expect(true)->toBeTrue()') ->and($contents)->not->toContain('newInstanceWithoutConstructor') ->and($contents)->not->toContain('Schema::create('); + + if (! str_ends_with($relativePath, 'UuidHelperTest.php')) { + expect($contents)->not->toContain('use Ramsey\\Uuid\\Uuid;') + ->and($contents)->not->toContain('Ramsey\\Uuid\\Uuid::') + ->and($contents)->not->toContain('Symfony\\Component\\Uid'); + } } }); From 0a52798a3e08808fb40d23806f4a5cd7da2a9d97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Tue, 17 Nov 2026 12:32:18 +0100 Subject: [PATCH 180/183] fix(filesystems): correct default disk configuration Ensure the default filesystem disk falls back to 'local' if not set. Set 'serve' option to false for the local disk. --- config/filesystems.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config/filesystems.php b/config/filesystems.php index c25b0fd5..4830bbdc 100644 --- a/config/filesystems.php +++ b/config/filesystems.php @@ -15,7 +15,7 @@ return [ | */ - 'default' => env('FILESYSTEM_DISK', 'local'), + 'default' => env('FILESYSTEM_DISK', 'local') ?: 'local', /* |-------------------------------------------------------------------------- @@ -35,7 +35,7 @@ return [ 'local' => [ 'driver' => 'local', 'root' => storage_path('app/private'), - 'serve' => true, + 'serve' => false, 'throw' => false, 'report' => false, ], From aba49edaeecbd578f7cda8d3520403e965118d97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Tue, 17 Nov 2026 12:32:21 +0100 Subject: [PATCH 181/183] chore(config,tests): disable local disk serving route and freeze time in ShopperTest --- tests/Unit/Domain/Models/Entities/ShopperTest.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/Unit/Domain/Models/Entities/ShopperTest.php b/tests/Unit/Domain/Models/Entities/ShopperTest.php index d021dc5a..f598d3d7 100644 --- a/tests/Unit/Domain/Models/Entities/ShopperTest.php +++ b/tests/Unit/Domain/Models/Entities/ShopperTest.php @@ -15,6 +15,14 @@ use Domain\Models\ValueObjects\ShopperSiteCode; use Shared\Helpers\UuidHelper; describe('Shopper', function (): void { + beforeEach(function (): void { + CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris')); + }); + + afterEach(function (): void { + CarbonImmutable::setTestNow(); + }); + it('can instantiate correctly and check active status (active)', function (): void { // GIVEN $id = new ShopperId(UuidHelper::v7()); From 1894e459079892ee5966da127e7d150251548ec1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Tue, 17 Nov 2026 12:39:18 +0100 Subject: [PATCH 182/183] fix(stats): exclude technical PENDING and FAILED orders from active clients metric --- app/Services/StatsService.php | 6 +- .../WithApp/App/Services/StatsServiceTest.php | 55 +++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/app/Services/StatsService.php b/app/Services/StatsService.php index 03ea91ac..61d19393 100644 --- a/app/Services/StatsService.php +++ b/app/Services/StatsService.php @@ -274,11 +274,15 @@ class StatsService } /** - * Get the number of active clients (ordered in the period). + * Get the number of active clients (ordered in the period, excluding technical PENDING/FAILED states). */ private function getNbActiveClients(CarbonInterface $start, CarbonInterface $end): int { $matricules = Order::query() + ->whereNotIn('status', [ + OrderStatus::PENDING->value, + OrderStatus::FAILED->value, + ]) ->whereCreatedAtBetween($start, $end) ->get(['employee']) ->map(fn (Order $order): string => $order->employee->matricule->value) diff --git a/tests/Integration/WithApp/App/Services/StatsServiceTest.php b/tests/Integration/WithApp/App/Services/StatsServiceTest.php index e9758c92..055d6113 100644 --- a/tests/Integration/WithApp/App/Services/StatsServiceTest.php +++ b/tests/Integration/WithApp/App/Services/StatsServiceTest.php @@ -282,4 +282,59 @@ describe('StatsService', function (): void { ->and($shopStats[StatsShopType::nbCanceledCmd->value]['current'])->toBe(1) ->and($shopStats[StatsShopType::canceledRate->value]['current'])->toBe(80.0); }); + + it('counts VALIDATED, CANCELED and WAITING customers as active while excluding PENDING, FAILED and unconverted attempts', function () use ( + $createEmployee, + $createOrder, + ): void { + // GIVEN + $service = new StatsService(new Currency('EUR')); + $now = CarbonImmutable::now(); + + $createActiveCustomer = function (int $id, string $matricule, string $email) use ($createEmployee): Customer { + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), + 'email' => new Email($email), + ]); + $createEmployee($id, $matricule, $customer); + + return $customer; + }; + + $createActiveCustomer(11, '1000501', 'validated@example.com'); + $createActiveCustomer(12, '1000502', 'canceled@example.com'); + $createActiveCustomer(13, '1000503', 'waiting@example.com'); + $createActiveCustomer(14, '1000504', 'pending@example.com'); + $createActiveCustomer(15, '1000505', 'failed@example.com'); + $attemptOnlyCustomer = $createActiveCustomer(16, '1000506', 'attempt@example.com'); + + // 2 VALIDATED + 1 CANCELED + 1 legacy WAITING => 3 active customers + $createOrder(OrderStatus::VALIDATED, '1000501', $now->subDays(2)); + $createOrder(OrderStatus::VALIDATED, '1000501', $now->subDay()); + $createOrder(OrderStatus::CANCELED, '1000502', $now->subDays(2)); + $createOrder(OrderStatus::WAITING, '1000503', $now->subDays(2)); + + // Technical PENDING / FAILED orders & unconverted tunnel attempts must not inflate active clients + $createOrder(OrderStatus::PENDING, '1000504', $now->subDays(2)); + $createOrder(OrderStatus::FAILED, '1000505', $now->subDays(2)); + OrderTunnelAttempt::query()->forceCreate([ + 'customer_id' => $attemptOnlyCustomer->id, + 'order_id' => null, + 'converted_at' => null, + 'created_at' => $now->subDay()->utc(), + 'updated_at' => $now->subDay()->utc(), + ]); + + // WHEN + $shopStats = $service->getStats( + [StatsShopType::nbActiveClients, StatsShopType::purchaseFrequency], + $now->subDays(5), + $now, + ); + + // THEN: 3 active clients (1000501, 1000502, 1000503), purchaseFrequency = round(2 / 3, 2) = 0.67 + expect($shopStats[StatsShopType::nbActiveClients->value]['current'])->toBe(3) + ->and($shopStats[StatsShopType::purchaseFrequency->value]['current'])->toBe(0.67); + }); }); From 5b7af5e24a1eb6188ffa81e780d41bea6479f593 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Tue, 17 Nov 2026 14:30:37 +0100 Subject: [PATCH 183/183] fix(manifest): remove unused MAIL_SCHEME variable This change eliminates the MAIL_SCHEME variable from the configuration as it is no longer needed. --- manifest.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/manifest.yaml b/manifest.yaml index 18267856..5d7c09cb 100644 --- a/manifest.yaml +++ b/manifest.yaml @@ -43,7 +43,6 @@ data: MAIL_MAILER: "${APP_MAIL_MAILER}" MAIL_PASSWORD: "${APP_MAIL_PASSWORD}" MAIL_PORT: "${APP_MAIL_PORT}" - MAIL_SCHEME: "${APP_MAIL_SCHEME}" MAIL_TO_CONTACT: "${APP_MAIL_TO_CONTACT}" MAIL_TO_REGATE: "${APP_MAIL_TO_REGATE}" MAIL_USERNAME: "${APP_MAIL_USERNAME}"