diff --git a/.env.example b/.env.example index 567a5608..bd4b52de 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,42 @@ DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD= +# BROADCAST, CACHE, QUEUE BROADCAST_DRIVER=log CACHE_STORE=file QUEUE_CONNECTION=sync + +# SESSION SESSION_DRIVER=file SESSION_LIFETIME=120 +SESSION_ENCRYPT=false +SESSION_SECURE_COOKIE=false +SESSION_PATH=/ +SESSION_DOMAIN= +SESSION_CONNECTION= -FILESYSTEM_DISK=local +# 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 +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 +71,10 @@ CRM_ENDPOINT= CRM_TOKEN= CRM_PASSWORD= -# Sentry +# SENTRY SENTRY_LARAVEL_DSN= -# Matomo +# MATOMO MATOMO_SITE_ID= # UWIL ADMIN SECURE @@ -52,13 +83,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/.gitlab-ci.yml b/.gitlab-ci.yml index d3a74b38..fac09cdb 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -79,7 +79,11 @@ 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 artifacts: when: on_failure @@ -253,12 +257,29 @@ tests_laravel: - name: mysql:8.0 alias: mysql before_script: + - 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 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: diff --git a/REGLES METIERS.md b/REGLES METIERS.md index 2fed1147..e268058c 100644 --- a/REGLES METIERS.md +++ b/REGLES METIERS.md @@ -7,12 +7,18 @@ Les règles reposent sur le code de la partie **Domaine**. La sélection du retrait se fait désormais sur une journée complète et non plus par tranches horaires via `PickupSchedulingService`. - **Jour de retrait standard** : Uniquement le **Vendredi** (`PICKUP_DAY = WeekDay::Friday`). -- **Heure de clôture (Cutoff)** : **Lundi à 14h00** de la même semaine (`CUTOFF_DAY = Monday`, `CUTOFF_HOUR = 14`). - - *Comportement* : Une commande validée avant Lundi 14h00 est préparée pour le vendredi en cours. Passé ce délai, le premier jour disponible bascule automatiquement sur le vendredi de la semaine suivante. -- **Gestion des Exceptions** : +- **Heure de clôture (Cutoff)** : **Lundi à 14h00** (`Europe/Paris`) de la même semaine (`CUTOFF_DAY = Monday`, `CUTOFF_HOUR = 14`). + - *Comportement* : Une commande validée avant Lundi 14h00 (`<= 14:00:00 Europe/Paris`) est préparée pour le vendredi en cours. Passé ce délai, `nextPickup()` et `currentCutoff()` basculent automatiquement sur le vendredi et le lundi de la semaine suivante. + - *Lundis fériés* : Si un lundi (`CUTOFF_DAY`) est un jour férié, la prise de commande et le cutoff restent inchangés (seuls les jours de retrait sont affectés par les jours fériés). +- **Fuseaux horaires & Persistance BDD (MySQL)** : + - Toute la logique métier du cutoff et des jours de retrait opère en **`Europe/Paris`**. + - En base de données (`config('app.timezone') = 'UTC'`), toutes les colonnes `datetime`/`timestamp` sont converties et stockées en **UTC** via `App\Casts\UtcDatetimeCast` (et converties côté requêtes BO depuis `client_timezone` via `ConvertsClientDatesToUtc`), puis affichées au fuseau local via `Date::forHumans()` / `Date::toLocalInput()`. + - Les colonnes SQL `DATE` calendaires sans heure (`pickup_exceptions.date`, `replacement_date`, `pickup_day`, `employees.start_date`/`end_date`, `stats.date`) utilisent `App\Casts\CalendarDateCast` afin d'être stockées en `Y-m-d` sans décalage horaire ni perte d'un jour, et affichées via `Date::forHumansDate()`. +- **Gestion des Exceptions & Jours fériés** : - Les fermetures et jours fériés sont gérés via des `ShopPickupException`. - Une exception peut **fermer le retrait**, ou proposer un **jour de remplacement**. Ce jour de remplacement peut posséder sa propre limite de validation (`orderDeadlineAt`). - - Une tâche planifiée `UpsertShopsPickupExceptionsUsingApiForYear` est lancée pour provisionner les jours fériés de l'année pour toutes les boutiques + - Une tâche planifiée `EnsurePublicHolidaysSyncedJob` synchronise les jours fériés de la zone **Métropole** (`calendrier.api.gouv.fr/jours-feries/metropole/:year.json`, hors Alsace-Moselle) pour toutes les boutiques existantes (`UpsertShopsPickupExceptionsForYear`). + - Lors de la création d'une nouvelle boutique (`CreateShop`), les jours fériés déjà synchronisés (`auto_updated = true`, année courante et suivantes) lui sont automatiquement rattachés. ## 2. Limites de Montants @@ -31,3 +37,61 @@ Elle est géré par le service `ProductAvailabilityService`. - Il est éligible INCO (`hasInco = true`). - La date actuelle est supérieure ou égale à `orderable_start` (si défini). - La date actuelle est inférieure à `orderable_end` (si défini). + +## 4. Statut Actif du Salarié + +Elle est vérifiée côté Domaine par `Shopper::isActive()` et côté Eloquent par `Employee::isActive` / `Employee::scopeActive()`. + +- **Fuseau calendaire (`Europe/Paris`)** : + - En base de données, `start_date` et `end_date` sont des colonnes SQL `DATE` (sans heure ni fuseau, chargées via `CalendarDateCast`). + - L'activation et la désactivation sont évaluées par rapport à la date calendaire du jour en **`Europe/Paris`** (`00:00:00 Europe/Paris`), afin d'éviter le décalage nocturne de 1 h à 2 h lié à UTC. + +- **Date de début (`start_date`)** : + + - Le salarié est actif lorsque `start_date` est inférieure ou égale au jour courant en `Europe/Paris` (ou si `start_date` est `null` en base de données). + - Un salarié dont la `start_date` est dans le futur est considéré comme **inactif** jusqu'à la date d'effet (`00:00:00 Europe/Paris` du jour de début). + +- **Date de fin (`end_date`)** : + + - 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. Cycle de Vie, Tunnel de Commande & Annulation (Back-Office) + +### Statuts des commandes (`Domain\Enums\OrderStatus`) +- **`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`. +- 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 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 + +La génération des codes d'accès salariés est gérée par `App\Services\CodeGenerationService` et leur validation à l'inscription par `App\Http\Requests\Fo\Auth\RegisterRequest`. + +- **Génération déterministe du code** : + - Chaque code d'accès (`Code`, longueur `7`) est dérivé de façon déterministe à partir du `matricule` du salarié via `SerialCasterBuilder` (`Code::ALLOWED_CHARACTERS`, `Code::LENGTH`). Il ne s'agit pas d'un secret aléatoire, mais d'un code d'appariement court lié au matricule. +- **Validation à l'inscription (`RegisterRequest`)** : + - L'existence d'un `matricule` non encore associé à un compte client (`employees.customer_id IS NULL`) est validée explicitement (`Rule::exists('employees', 'matricule')->whereNull('customer_id')`), séparément de la règle sur `code` (`Rule::exists('employees', 'code')->where('matricule', ...)->whereNull('customer_id')`). + - Les messages d'erreur distincts entre « matricule inconnu / déjà utilisé » et « code incorrect » sont assumés pour faciliter le support utilisateur, les routes d'authentification étant protégées par un rate limiter (`throttle`). + +## 7. Connexion d'un Compte Non Activé (CRM & `laravel/ui`) + +Elle est gérée par `App\Auth\CrmUserProvider::validateCredentials()` et `App\Http\Controllers\Fo\Auth\LoginController::authenticated()`. + +- **Validation CRM (`CrmService::login()`)** : + - L'API CRM (`Api\V4\CustomerController::authenticate()`) vérifie **d'abord** le mot de passe (`ApiError::authFailed`) avant de vérifier si le compte est activé (`ApiError::customerNotActivated` → `CrmCustomerNotActivatedException`). +- **Alignement sur `laravel/ui` (`VerificationController`)** : + - Conformément au fonctionnement standard de `laravel/ui`, `VerificationController` requiert une session authentifiée (`auth:frontend`) pour accéder aux routes `email/verify`, `email/verify/{id}/{hash}` et `email/resend`. + - Lorsqu'un client saisit le **bon mot de passe** sur un compte non encore activé, `CrmUserProvider::validateCredentials()` intercepte `CrmCustomerNotActivatedException`, renvoie l'e-mail de vérification et retourne `true` afin d'ouvrir la session et de laisser le middleware `verified` (`EnsureCustomerEmailIsVerified`) rediriger vers `fo.auth.verification.notice`. + - En revanche, `LoginController::authenticated()` ne flashe le message `"You are logged in!"` que si l'e-mail du client est déjà vérifié (`AppCustomerAuthService::hasVerifiedEmail()`). diff --git a/app/Attributes/Locked.php b/app/Attributes/Locked.php new file mode 100644 index 00000000..58c3383c --- /dev/null +++ b/app/Attributes/Locked.php @@ -0,0 +1,24 @@ +ttlSeconds, 0); + Assert::greaterThanEq($this->waitSeconds, 0); + + if ($this->key !== null) { + Assert::stringNotEmpty(trim($this->key)); + } + } +} 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 @@ + $model */ @@ -56,7 +49,12 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider #[\Override] public function retrieveByCredentials(array $credentials): ?Authenticatable { - $model = parent::retrieveByCredentials($credentials); + $model = parent::retrieveByCredentials($credentials); + + if ($model === null) { + return null; + } + $result = $this->crmService->getCustomerFromEmail(Arr::string($credentials, 'email')); if ($result instanceof CrmServiceException) { @@ -66,13 +64,7 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider ]); } - $this->crmCustomer = $result; - - if ($this->crmCustomer instanceof CrmCustomer && $model === null) { - $model = $this->createLocalCustomer($this->crmCustomer); - } - - return $this->crmCustomer !== null ? $model : null; + return $result !== null ? $model : null; } /** @@ -88,11 +80,11 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider public function validateCredentials(Authenticatable $model, array $credentials): bool { if ($model::class !== $this->usedModel) { - throw new UnexpectedValueException("Cannot authenticate any thing else than '{$this->usedModel}'"); + throw new \UnexpectedValueException("Cannot authenticate any thing else than '{$this->usedModel}'"); } if (! in_array(MustVerifyEmail::class, \class_implements($model))) { - throw new UnexpectedValueException("Model '{$this->usedModel}' should implement 'MustVerifyEmail'"); + throw new \UnexpectedValueException("Model '{$this->usedModel}' should implement 'MustVerifyEmail'"); } /** @var \Illuminate\Contracts\Auth\Authenticatable&\Illuminate\Contracts\Auth\MustVerifyEmail $model */ $requestEmail = Arr::string($credentials, 'email'); @@ -106,7 +98,11 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider return true; } catch (CrmCustomerNotActivatedException) { - $model->sendEmailVerificationNotification(); + try { + $model->sendEmailVerificationNotification(); + } catch (\Throwable $e) { + report($e); + } return true; } catch (CrmAuthenticationFailedException) { @@ -125,26 +121,4 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider { // No hashing. } - - private function createLocalCustomer(CrmCustomer $crmCustomer): Model & Authenticatable - { - $email = $crmCustomer->email ? - new Email($crmCustomer->email) : - throw new UnexpectedValueException('Email is required ti create a customer'); - - $hashcode = $crmCustomer->hashcode ? - $crmCustomer->hashcode : - throw new UnexpectedValueException('Hashcode is required to create a customer'); - - /** @var \App\Models\Customer&\Illuminate\Contracts\Auth\Authenticatable $model */ - $model = $this->usedModel::query() - ->where('email', $crmCustomer->email) - ->firstOrNew(); - - $model->email = $email; - $model->hashcode = CrmHashcode::fromString($hashcode); - $model->saveOrFail(); - - return $model; - } } diff --git a/app/Casts/CalendarDateCast.php b/app/Casts/CalendarDateCast.php new file mode 100644 index 00000000..ceaae3cc --- /dev/null +++ b/app/Casts/CalendarDateCast.php @@ -0,0 +1,62 @@ + + */ +class CalendarDateCast implements CastsAttributes +{ + public bool $withoutObjectCaching = true; + + /** @param array $attributes */ + #[\Override] + public function get(Model $model, string $key, mixed $value, array $attributes): ?Carbon + { + if ($value === null || $value === '') { + return null; + } + + $dateString = $this->extractDateString($value); + $parsed = Date::createFromFormat('!Y-m-d', $dateString, 'UTC'); + + if (! $parsed instanceof Carbon) { + throw new \InvalidArgumentException("Invalid calendar date value [{$dateString}]."); + } + + return $parsed; + } + + /** @param array $attributes */ + #[\Override] + public function set(Model $model, string $key, mixed $value, array $attributes): ?string + { + if ($value === null || $value === '') { + return null; + } + + return $this->extractDateString($value); + } + + private function extractDateString(mixed $value): string + { + if ($value instanceof \DateTimeInterface) { + return $value->format('Y-m-d'); + } + + if (is_string($value)) { + return Date::parse($value, 'UTC')->format('Y-m-d'); + } + + throw new \InvalidArgumentException('The given value cannot be cast to a calendar date.'); + } +} 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/FilePathCast.php b/app/Casts/FilePathCast.php new file mode 100644 index 00000000..9c090108 --- /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 || $value === '') { + 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 || $value === '') { + 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/Casts/OrderLineProductCast.php b/app/Casts/OrderLineProductCast.php index 916c5e2f..26376096 100644 --- a/app/Casts/OrderLineProductCast.php +++ b/app/Casts/OrderLineProductCast.php @@ -14,8 +14,8 @@ 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; /** * @implements CastsAttributes @@ -44,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'), @@ -58,7 +56,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 +97,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/Casts/UtcDatetimeCast.php b/app/Casts/UtcDatetimeCast.php new file mode 100644 index 00000000..d0cefe90 --- /dev/null +++ b/app/Casts/UtcDatetimeCast.php @@ -0,0 +1,59 @@ + + */ +class UtcDatetimeCast implements CastsAttributes +{ + public bool $withoutObjectCaching = true; + + /** @param array $attributes */ + #[\Override] + public function get(Model $model, string $key, mixed $value, array $attributes): ?Carbon + { + if ($value === null || $value === '') { + return null; + } + + return $this->toUtcCarbon($value); + } + + /** @param array $attributes */ + #[\Override] + public function set(Model $model, string $key, mixed $value, array $attributes): ?string + { + if ($value === null || $value === '') { + return null; + } + + return $this->toUtcCarbon($value)->format($model->getDateFormat()); + } + + private function toUtcCarbon(mixed $value): Carbon + { + if ($value instanceof \DateTimeInterface) { + return Date::instance($value)->setTimezone('UTC'); + } + + if (is_int($value)) { + return Date::createFromTimestamp($value, 'UTC'); + } + + if (is_string($value)) { + return Date::parse($value, 'UTC')->setTimezone('UTC'); + } + + throw new \InvalidArgumentException('The given value cannot be cast to a UTC datetime.'); + } +} diff --git a/app/Console/Commands/MailTest.php b/app/Console/Commands/MailTest.php index d5cc5554..829cb0c8 100644 --- a/app/Console/Commands/MailTest.php +++ b/app/Console/Commands/MailTest.php @@ -7,6 +7,7 @@ namespace App\Console\Commands; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; +use Illuminate\Mail\Message; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Validator; @@ -24,7 +25,7 @@ class MailTest extends Command 'email' => ['required', 'email:rfc,strict'], ])->validate(); - Mail::raw('This is a test mail', function ($message): void { + Mail::raw('This is a test mail', function (Message $message): void { $message->to($this->argument('email')); $message->subject('Test mail'); }); diff --git a/app/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptions.php b/app/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptions.php index 0e5916c6..abb7912a 100644 --- a/app/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptions.php +++ b/app/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptions.php @@ -15,22 +15,27 @@ class UpsertPublicHolydaysOnShopsPickupExceptions extends Command { /** * Execute the console command. - * - * @return void */ - public function handle() + public function handle(): int { $year = $this->argument('year'); - if (is_numeric($year) === false) { + if ($year !== null && is_numeric($year) === false) { $this->error('The year must be a number'); - return; + return self::FAILURE; } $this->info('Fetching hollidays upsert shops exceptions using Api'); - dispatch(new UpsertShopsPickupExceptionsUsingApiForYear(intval($year))); + + $job = $year !== null + ? new UpsertShopsPickupExceptionsUsingApiForYear(intval($year)) + : new UpsertShopsPickupExceptionsUsingApiForYear(); + + dispatch($job); $this->info('Done'); + + return self::SUCCESS; } } diff --git a/app/Console/Commands/UserCreate.php b/app/Console/Commands/UserCreate.php index c2ea690d..a51e935d 100644 --- a/app/Console/Commands/UserCreate.php +++ b/app/Console/Commands/UserCreate.php @@ -4,15 +4,17 @@ declare(strict_types=1); namespace App\Console\Commands; -use App\Models\User; +use App\Contracts\Executor; +use App\Cqs\Actions\Users\CreateUser; +use App\Cqs\Actions\Users\CreateUserInput; use Domain\Enums\UserRole; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; use Illuminate\Support\Arr; -use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rules\Password; +use Webmozart\Assert\Assert; #[Description('creates an admin user upon password entry')] #[Signature('uwil:user:create')] @@ -21,7 +23,7 @@ class UserCreate extends Command /** * Execute the console command. */ - public function handle(): int + public function handle(Executor $executor, CreateUser $action): int { $firstname = $this->askString('What is the firstname?', 'Equipe'); $lastname = $this->askString('What is the lastname?', 'Web'); @@ -29,14 +31,13 @@ class UserCreate extends Command $pwd = $this->askPassword('What is the password?'); $role = $this->askRole(); - $user = new User(); - $user->firstname = $firstname; - $user->lastname = $lastname; - $user->email = $email; - $user->password = Hash::make($pwd); - $user->email_verified_at = now(); - $user->role = $role; - $user->save(); + $executor->execute($action, new CreateUserInput( + firstname: $firstname, + lastname: $lastname, + email: $email, + password: $pwd, + role: $role, + )); $this->info('User created.'); @@ -119,6 +120,9 @@ class UserCreate extends Command multiple: false ) ); + + Assert::string($response[0]); + $role = UserRole::tryFrom( intval(mb_strcut((string) $response[0], 0, 1)) ); diff --git a/app/Contracts/Directories/CustomerDirectory.php b/app/Contracts/Directories/CustomerDirectory.php deleted file mode 100644 index 1c5902d1..00000000 --- a/app/Contracts/Directories/CustomerDirectory.php +++ /dev/null @@ -1,18 +0,0 @@ - */ -interface CustomerDirectory extends Directory -{ - public function find(UuidInterface $id): ?Customer; - - public function getCustomerByEmail(Email $email): ?Customer; -} diff --git a/app/Contracts/Directories/EmployeeDirectory.php b/app/Contracts/Directories/EmployeeDirectory.php deleted file mode 100644 index aac4182b..00000000 --- a/app/Contracts/Directories/EmployeeDirectory.php +++ /dev/null @@ -1,23 +0,0 @@ - */ -interface EmployeeDirectory extends Directory -{ - public function find(int $id): ?Employee; - - public function countActiveEmployees(): int; - - public function countActiveRegisteredEmployees(): int; - - public function countActiveEmployeesWithin(CarbonInterface $start, CarbonInterface $end): int; - - public function countActiveRegisteredEmployeesWithin(CarbonInterface $start, CarbonInterface $end): int; -} diff --git a/app/Contracts/Directories/OrderDirectory.php b/app/Contracts/Directories/OrderDirectory.php deleted file mode 100644 index ed8d2c21..00000000 --- a/app/Contracts/Directories/OrderDirectory.php +++ /dev/null @@ -1,48 +0,0 @@ - */ -interface OrderDirectory extends Directory -{ - public function find(UuidInterface $id): ?Order; - - /** @return \Illuminate\Pagination\LengthAwarePaginator */ - public function getPaginatedOrdersOf( - Customer $customer, - Pagination $pagination, - bool $orderByDate = false - ): PaginationLengthAwarePaginator; - - public function findOf(Customer $customer, UuidInterface $id): ?Order; - - /** @return Collection*/ - public function getValidatedOrders(CarbonInterface $start, CarbonInterface $end): Collection; - - /** @return Collection */ - public function getOrdersByStatus(OrderStatus $status, CarbonInterface $start, CarbonInterface $end): Collection; - - public function getNbActiveClients(CarbonInterface $start, CarbonInterface $end): int; - - public function getNbCmdWith7DayDelay(CarbonInterface $start, CarbonInterface $end): int; - - public function getNbCmdWith14DayDelay(CarbonInterface $start, CarbonInterface $end): int; - - public function getCaHt(CarbonInterface $start, CarbonInterface $end): float; - - public function getCaTtc(CarbonInterface $start, CarbonInterface $end): float; - - public function getTotalQuantity(CarbonInterface $start, CarbonInterface $end): int; -} diff --git a/app/Contracts/Directory.php b/app/Contracts/Directory.php deleted file mode 100644 index d18e5406..00000000 --- a/app/Contracts/Directory.php +++ /dev/null @@ -1,15 +0,0 @@ - - */ -interface EmployeeRepository extends Repository -{ - public function find(UuidInterface $id): ?Employee; - - public function persist(Employee $employee): void; - - public function delete(Employee $employee): void; - - /** @return array */ - public function getAll(): array; - - public function findByMatriculeAndCode(Matricule $matricule, Code $code): ?Employee; - - public function findByMatricule(Matricule $matricule): ?Employee; - - /** - * @param array|Collection $matricules - * @return array - */ - public function getWhereMatriculeIn(array | Collection $matricules): array; - - /** - * @param array|Collection $matricules - * @return array - */ - public function getWithCustomerWhereMatriculeIn(array | Collection $matricules): array; - - /** - * @param array|Collection $excludedMatricules - * @return array - */ - public function getWithCustomerWhereMatriculeNotIn(array | Collection $excludedMatricules): array; - - public function getMostRecentSyncDate(): ?\DateTimeInterface; -} diff --git a/app/Contracts/Repositories/OrderRepository.php b/app/Contracts/Repositories/OrderRepository.php deleted file mode 100644 index 6803ef0a..00000000 --- a/app/Contracts/Repositories/OrderRepository.php +++ /dev/null @@ -1,34 +0,0 @@ - - */ -interface OrderRepository extends Repository -{ - public function find(UuidInterface $id): ?Order; - - public function persist(Order $order): void; - - public function delete(Order $order): void; - - /** @return array */ - public function getAll(): array; - - /** @return array */ - public function getValidatedOrdersForPickupDay(CarbonInterface $pickupDay): array; - - public function hasValidatedOrderForPickupDay(Matricule $matricule, CarbonInterface $pickupDay): bool; - - /** @return array */ - public function getOrdersWithLinesAndShopForPickupDay(CarbonInterface $pickupDay): array; -} diff --git a/app/Contracts/Repositories/UserRepository.php b/app/Contracts/Repositories/UserRepository.php deleted file mode 100644 index 843a46b5..00000000 --- a/app/Contracts/Repositories/UserRepository.php +++ /dev/null @@ -1,20 +0,0 @@ - - */ -interface UserRepository extends Repository -{ - public function find(int $id): ?User; - - public function persist(User $user): void; - - public function delete(User $user): void; -} diff --git a/app/Contracts/Repository.php b/app/Contracts/Repository.php deleted file mode 100644 index 9ac81658..00000000 --- a/app/Contracts/Repository.php +++ /dev/null @@ -1,17 +0,0 @@ - + */ +final class DeleteOldResetTokens implements Action +{ + /** + * @param \App\Contracts\ActionInputEmpty $input + */ + #[\Override] + public function __invoke(ActionInput $input): void + { + Assert::isInstanceOf($input, ActionInputEmpty::class); + + PasswordReset::query() + ->where('created_at', '<=', Date::now()->subDays(7)) + ->forceDelete(); + } +} diff --git a/app/Cqs/Actions/Auth/ResetCustomerPassword.php b/app/Cqs/Actions/Auth/ResetCustomerPassword.php new file mode 100644 index 00000000..bf752fde --- /dev/null +++ b/app/Cqs/Actions/Auth/ResetCustomerPassword.php @@ -0,0 +1,56 @@ + + */ +final class ResetCustomerPassword implements Action +{ + public function __construct( + private readonly ShopperService $shopperService, + private readonly AppCustomerAuthService $authService, + ) { + } + + /** + * @param \App\Cqs\Actions\Auth\ResetCustomerPasswordInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): ResetCustomerPasswordOutput + { + Assert::isInstanceOf($input, ResetCustomerPasswordInput::class); + + $shopper = $this->shopperService->getShopperFor($input->customer->getId()); + + if (! $shopper || ! $shopper->isActive()) { + return ResetCustomerPasswordOutput::notEmployed(); + } + + $result = $this->authService->resetPasswordFor($input->customer, $input->password); + + if ($result instanceof ValidationException) { + return ResetCustomerPasswordOutput::invalidPassword($result->getMessage()); + } + + $input->customer->setRememberToken(Str::random(60)); + $input->customer->saveOrFail(); + + return ResetCustomerPasswordOutput::success( + $this->authService->hasVerifiedEmail($input->customer) + ); + } +} diff --git a/app/Cqs/Actions/Auth/ResetCustomerPasswordInput.php b/app/Cqs/Actions/Auth/ResetCustomerPasswordInput.php new file mode 100644 index 00000000..147f778c --- /dev/null +++ b/app/Cqs/Actions/Auth/ResetCustomerPasswordInput.php @@ -0,0 +1,20 @@ +password); + } +} diff --git a/app/Cqs/Actions/Auth/ResetCustomerPasswordOutput.php b/app/Cqs/Actions/Auth/ResetCustomerPasswordOutput.php new file mode 100644 index 00000000..aa6d23e7 --- /dev/null +++ b/app/Cqs/Actions/Auth/ResetCustomerPasswordOutput.php @@ -0,0 +1,40 @@ +model; - $goUp = $input->direction === SortDirection::Ascending; + $goUp = $input->direction === \SortDirection::Ascending; $currentOrder = $model->getOrder(); $usesSoftDeletes = in_array(SoftDeletes::class, class_uses_recursive($model), true) @@ -44,7 +43,7 @@ final class ChangeModelOrder implements Action /** @var (Model&ModelWithOrder)|null $adjacentModel */ $adjacentModel = $baseQuery ->where('order', $goUp ? '<' : '>', $currentOrder) - ->orderBy('order', $goUp ? SortDirection::Descending : SortDirection::Ascending) + ->orderBy('order', $goUp ? \SortDirection::Descending : \SortDirection::Ascending) ->first(); if ($adjacentModel === null) { diff --git a/app/Cqs/Actions/Common/ChangeModelOrderInput.php b/app/Cqs/Actions/Common/ChangeModelOrderInput.php index 007ce603..4d4470bb 100644 --- a/app/Cqs/Actions/Common/ChangeModelOrderInput.php +++ b/app/Cqs/Actions/Common/ChangeModelOrderInput.php @@ -7,16 +7,12 @@ namespace App\Cqs\Actions\Common; use App\Contracts\ActionInput; use App\Interfaces\ModelWithOrder; use Illuminate\Database\Eloquent\Model; -use SortDirection; -use Webmozart\Assert\Assert; final readonly class ChangeModelOrderInput implements ActionInput { public function __construct( public Model & ModelWithOrder $model, - public SortDirection $direction, + 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/ExecuteMassAction.php b/app/Cqs/Actions/Common/ExecuteMassAction.php index f46042b7..980cef12 100644 --- a/app/Cqs/Actions/Common/ExecuteMassAction.php +++ b/app/Cqs/Actions/Common/ExecuteMassAction.php @@ -45,7 +45,7 @@ final class ExecuteMassAction implements Action break; default: - throw new \UnexpectedValueException('Unsupported mass action type: ' . $input->action->value); + throw new \UnexpectedValueException('Unsupported mass action type: ' . gettype($input->action->value)); } } @@ -88,7 +88,7 @@ final class ExecuteMassAction implements Action break; default: - throw new \UnexpectedValueException('Unsupported mass action type: ' . $input->action->value); + throw new \UnexpectedValueException('Unsupported mass action type: ' . gettype($input->action->value)); } $foundModel->saveOrFail(); 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/app/Cqs/Actions/Contact/SubmitContactForm.php b/app/Cqs/Actions/Contact/SubmitContactForm.php new file mode 100644 index 00000000..4802fef3 --- /dev/null +++ b/app/Cqs/Actions/Contact/SubmitContactForm.php @@ -0,0 +1,86 @@ + + * @implements \App\Contracts\HandlesSuccess< + * \App\Cqs\Actions\Contact\SubmitContactFormInput, + * \Domain\Models\ValueObjects\ContactFormData + * > + * @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Contact\SubmitContactFormInput> + */ +final class SubmitContactForm implements Action, HandlesFailure, HandlesSuccess +{ + use TracksPendingStoragePaths; + + 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); + $this->trackUploadedPath($input, $storedPath); + $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, + ); + } + + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + $this->clearTrackedPaths($input); + } + + #[\Override] + public function onFailure(ActionInput $input, \Throwable $exception): void + { + foreach ($this->pullUploadedPaths($input) as $path) { + if ($this->storageService->fileExistsOnDisk($path, $this->privateS3Disk->disk)) { + $this->storageService->removeFromDisk($path, $this->privateS3Disk->disk); + } + } + } +} diff --git a/app/Cqs/Actions/Contact/SubmitContactFormInput.php b/app/Cqs/Actions/Contact/SubmitContactFormInput.php new file mode 100644 index 00000000..62c1f159 --- /dev/null +++ b/app/Cqs/Actions/Contact/SubmitContactFormInput.php @@ -0,0 +1,29 @@ +lastName)); + Assert::stringNotEmpty(trim($this->firstName)); + Assert::stringNotEmpty(trim($this->email)); + Assert::stringNotEmpty(trim($this->subject)); + Assert::stringNotEmpty(trim($this->message)); + } +} diff --git a/app/Cqs/Actions/Customers/RegisterCustomer.php b/app/Cqs/Actions/Customers/RegisterCustomer.php index fb287d60..2082196b 100644 --- a/app/Cqs/Actions/Customers/RegisterCustomer.php +++ b/app/Cqs/Actions/Customers/RegisterCustomer.php @@ -4,34 +4,78 @@ declare(strict_types=1); namespace App\Cqs\Actions\Customers; +use App\Attributes\Locked; use App\Contracts\Action; use App\Contracts\ActionInput; -use App\Contracts\Repositories\EmployeeRepository; +use App\Contracts\HandlesFailure; +use App\Contracts\HandlesLockTimeout; +use App\Contracts\HandlesSuccess; +use App\Contracts\ProvidesLockKey; +use App\Enums\RegisterCustomerStatus; use App\Exceptions\Crm\CrmCustomerExistsException; use App\Exceptions\CrmServiceException; use App\Models\Customer; +use App\Models\Employee; use App\Services\CrmService; use Domain\Enums\Country; 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; /** - * @implements \App\Contracts\Action<\App\Cqs\Actions\Customers\RegisterCustomerInput, \App\Models\Customer> + * @implements \App\Contracts\Action< + * \App\Cqs\Actions\Customers\RegisterCustomerInput, + * \App\Cqs\Actions\Customers\RegisterCustomerOutput + * > + * @implements \App\Contracts\ProvidesLockKey<\App\Cqs\Actions\Customers\RegisterCustomerInput> + * @implements \App\Contracts\HandlesLockTimeout< + * \App\Cqs\Actions\Customers\RegisterCustomerInput, + * \App\Cqs\Actions\Customers\RegisterCustomerOutput + * > + * @implements \App\Contracts\HandlesSuccess< + * \App\Cqs\Actions\Customers\RegisterCustomerInput, + * \App\Cqs\Actions\Customers\RegisterCustomerOutput + * > + * @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Customers\RegisterCustomerInput> */ -final class RegisterCustomer implements Action +#[Locked(ttlSeconds: 30, waitSeconds: 10)] +final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeout, HandlesSuccess, ProvidesLockKey { + /** @var array */ + private array $createdCrmCustomers = []; + public function __construct( private readonly AppCustomerAuthService $authService, private readonly CrmService $crmService, - private readonly EmployeeRepository $employeeRepository, ) { } + /** + * @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input + */ + #[\Override] + public function lockKey(ActionInput $input): string + { + Assert::isInstanceOf($input, RegisterCustomerInput::class); + + return "customer:register:employee:{$input->matricule->value}"; + } + + /** + * @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input + */ + #[\Override] + public function onLockTimeout(ActionInput $input): RegisterCustomerOutput + { + Assert::isInstanceOf($input, RegisterCustomerInput::class); + + return RegisterCustomerOutput::lockTimeout(); + } + /** * @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input * @@ -40,27 +84,39 @@ final class RegisterCustomer implements Action * @throws ModelNotFoundException */ #[\Override] - public function __invoke(ActionInput $input): Customer + public function __invoke(ActionInput $input): RegisterCustomerOutput { Assert::isInstanceOf($input, RegisterCustomerInput::class); + $inputKey = spl_object_id($input); + unset($this->createdCrmCustomers[$inputKey]); + + $employee = Employee::query() + ->where('matricule', $input->matricule->value) + ->where('code', $input->code->value) + ->lockForUpdate() + ->first(); + + if (! $employee) { + throw new ModelNotFoundException('Employee not found'); + } + + if ($employee->customer_id !== null) { + return RegisterCustomerOutput::employeeAlreadyRegistered(); + } + + if (! $employee->is_active) { + return RegisterCustomerOutput::employeeInactive(); + } + // * Persist and associate Customer + Employee $customer = new Customer([ 'email' => $input->email, ]); // * Temp hashcode to satisfy constraint - $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->saveOrFail(); - $employee = $this->employeeRepository->findByMatriculeAndCode( - $input->matricule, - $input->code - ); - - if (! $employee) { - throw new ModelNotFoundException('Employee not found'); - } - $employee->customer()->associate($customer); $employee->saveOrFail(); @@ -84,21 +140,6 @@ final class RegisterCustomer implements Action try { $result = $this->crmService->persist($crmCustomer); - - if (! $result->hashcode) { - throw new \UnexpectedValueException( - 'CRM did not return a hashcode for the created customer' - ); - } - - $customer->hashcode = CrmHashcode::fromString($result->hashcode); - $customer->saveOrFail(); - - $customer->sendEmailVerificationNotification(); - - $this->authService->logIn($customer); - - return $customer; } catch (CrmCustomerExistsException) { throw ValidationException::withMessages([ 'error' => trans('An account is already associated with this email address'), @@ -109,5 +150,70 @@ final class RegisterCustomer implements Action 'error' => trans('An error has occurred. Please try again later'), ]); } + + if (! $result->hashcode) { + throw new \UnexpectedValueException( + 'CRM did not return a hashcode for the created customer' + ); + } + + $crmHashcode = CrmHashcode::fromString($result->hashcode); + $this->createdCrmCustomers[$inputKey] = [ + 'hashcode' => $crmHashcode, + 'email' => $input->email, + ]; + + $customer->hashcode = $crmHashcode; + $customer->saveOrFail(); + + return RegisterCustomerOutput::success($customer); + } + + /** + * @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input + * @param \App\Cqs\Actions\Customers\RegisterCustomerOutput $result + */ + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + Assert::isInstanceOf($input, RegisterCustomerInput::class); + Assert::isInstanceOf($result, RegisterCustomerOutput::class); + + unset($this->createdCrmCustomers[spl_object_id($input)]); + + if ($result->status !== RegisterCustomerStatus::SUCCESS || ! $result->customer instanceof Customer) { + return; + } + + $this->authService->logIn($result->customer); + + try { + $result->customer->sendEmailVerificationNotification(); + } catch (\Throwable $e) { + report($e); + } + } + + /** + * @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input + */ + #[\Override] + public function onFailure(ActionInput $input, \Throwable $exception): void + { + Assert::isInstanceOf($input, RegisterCustomerInput::class); + + $inputKey = spl_object_id($input); + $createdCrm = $this->createdCrmCustomers[$inputKey] ?? null; + unset($this->createdCrmCustomers[$inputKey]); + + if ($createdCrm === null) { + return; + } + + try { + $this->crmService->deleteByHashcode($createdCrm['hashcode'], $createdCrm['email']); + } catch (\Throwable $e) { + report($e); + } } } diff --git a/app/Cqs/Actions/Customers/RegisterCustomerOutput.php b/app/Cqs/Actions/Customers/RegisterCustomerOutput.php new file mode 100644 index 00000000..ea5cfae6 --- /dev/null +++ b/app/Cqs/Actions/Customers/RegisterCustomerOutput.php @@ -0,0 +1,47 @@ + + */ +final class UpdateCustomerLastLogin implements Action +{ + /** + * @param \App\Cqs\Actions\Customers\UpdateCustomerLastLoginInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): Customer + { + Assert::isInstanceOf($input, UpdateCustomerLastLoginInput::class); + + $customer = $input->customer; + $customer->last_login_at = Date::now(); + $customer->saveOrFail(); + + return $customer; + } +} diff --git a/app/Cqs/Actions/Customers/UpdateCustomerLastLoginInput.php b/app/Cqs/Actions/Customers/UpdateCustomerLastLoginInput.php new file mode 100644 index 00000000..92655315 --- /dev/null +++ b/app/Cqs/Actions/Customers/UpdateCustomerLastLoginInput.php @@ -0,0 +1,16 @@ + */ +#[WithoutTransaction] final class SynchronizeEmployeesWithArcadiaApi implements Action { public function __construct( - private readonly EmployeeRepository $employeeRepository, private readonly EmployeeSyncService $syncService ) { } /** @param \App\Contracts\ActionInputEmpty $input */ + #[\Override] public function __invoke(ActionInput $input): void { Assert::isAOf($input, ActionInputEmpty::class); - $wasLastSyncedAt = $this->employeeRepository->getMostRecentSyncDate(); - - $this->syncService->synchronize($wasLastSyncedAt); + $this->syncService->synchronize(); } } diff --git a/app/Cqs/Actions/Orders/ApplyPickTimeSlot.php b/app/Cqs/Actions/Orders/ApplyPickTimeSlot.php index 5b18bb24..bc47667e 100644 --- a/app/Cqs/Actions/Orders/ApplyPickTimeSlot.php +++ b/app/Cqs/Actions/Orders/ApplyPickTimeSlot.php @@ -6,12 +6,14 @@ namespace App\Cqs\Actions\Orders; use App\Contracts\Action; use App\Contracts\ActionInput; -use Domain\Models\ValueObjects\PickupTimeSlot; use Domain\Services\OrderTunnelService; use Webmozart\Assert\Assert; /** - * @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\ApplyPickTimeSlotInput, ?\Domain\Models\ValueObjects\PickupTimeSlot> + * @implements \App\Contracts\Action< + * \App\Cqs\Actions\Orders\ApplyPickTimeSlotInput, + * \App\Cqs\Actions\Orders\ApplyPickTimeSlotOutput + * > */ final class ApplyPickTimeSlot implements Action { @@ -24,7 +26,7 @@ final class ApplyPickTimeSlot implements Action * @param \App\Cqs\Actions\Orders\ApplyPickTimeSlotInput $input */ #[\Override] - public function __invoke(ActionInput $input): ?PickupTimeSlot + public function __invoke(ActionInput $input): ApplyPickTimeSlotOutput { Assert::isInstanceOf($input, ApplyPickTimeSlotInput::class); @@ -32,11 +34,15 @@ final class ApplyPickTimeSlot implements Action $shop = $this->orderTunnelService->getShopForCustomer($input->shopperId); $timeSlots = $this->orderTunnelService->getAvailableTimeSlots($shop); - return $this->orderTunnelService->applyTimeSlot( + $timeSlot = $this->orderTunnelService->applyTimeSlot( $builder, $shop, $input->timeslot, $timeSlots ); + + return $timeSlot !== null + ? ApplyPickTimeSlotOutput::matched($timeSlot) + : ApplyPickTimeSlotOutput::unavailable(); } } diff --git a/app/Cqs/Actions/Orders/ApplyPickTimeSlotOutput.php b/app/Cqs/Actions/Orders/ApplyPickTimeSlotOutput.php new file mode 100644 index 00000000..05ca22ff --- /dev/null +++ b/app/Cqs/Actions/Orders/ApplyPickTimeSlotOutput.php @@ -0,0 +1,32 @@ + + * @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\CancelOrderInput, \App\Cqs\Actions\Orders\CancelOrderOutput> */ final class CancelOrder implements Action { public function __construct( - private readonly DomainOrderService $domainOrderService, + private readonly OrderService $orderService, ) { } @@ -23,10 +23,16 @@ final class CancelOrder implements Action * @param \App\Cqs\Actions\Orders\CancelOrderInput $input */ #[\Override] - public function __invoke(ActionInput $input): void + public function __invoke(ActionInput $input): CancelOrderOutput { Assert::isInstanceOf($input, CancelOrderInput::class); - $this->domainOrderService->cancelOrder($input->order->getId()); + try { + $this->orderService->cancelOrder($input->order->getId()); + } catch (\DomainException) { + return CancelOrderOutput::NOT_FOUND; + } + + return CancelOrderOutput::CANCELLED; } } diff --git a/app/Cqs/Actions/Orders/CancelOrderOutput.php b/app/Cqs/Actions/Orders/CancelOrderOutput.php new file mode 100644 index 00000000..b002273e --- /dev/null +++ b/app/Cqs/Actions/Orders/CancelOrderOutput.php @@ -0,0 +1,11 @@ + + */ +final class ClaimTodayOrderReminder implements Action +{ + /** + * @param \App\Cqs\Actions\Orders\ClaimTodayOrderReminderInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): bool + { + Assert::isInstanceOf($input, ClaimTodayOrderReminderInput::class); + + $updated = Order::query() + ->where('id', $input->orderId->value->toString()) + ->where('status', OrderStatus::VALIDATED->value) + ->whereNull('reminded_at') + ->update(['reminded_at' => $input->remindedAt]); + + return $updated > 0; + } +} diff --git a/app/Cqs/Actions/Orders/ClaimTodayOrderReminderInput.php b/app/Cqs/Actions/Orders/ClaimTodayOrderReminderInput.php new file mode 100644 index 00000000..9d21868d --- /dev/null +++ b/app/Cqs/Actions/Orders/ClaimTodayOrderReminderInput.php @@ -0,0 +1,18 @@ + + */ +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 @@ + + */ +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/FailPendingOrderInput.php b/app/Cqs/Actions/Orders/FailPendingOrderInput.php new file mode 100644 index 00000000..55342ccb --- /dev/null +++ b/app/Cqs/Actions/Orders/FailPendingOrderInput.php @@ -0,0 +1,16 @@ + + */ +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/Actions/Orders/FinalizeOrder.php b/app/Cqs/Actions/Orders/FinalizeOrder.php deleted file mode 100644 index df65eb30..00000000 --- a/app/Cqs/Actions/Orders/FinalizeOrder.php +++ /dev/null @@ -1,36 +0,0 @@ - - */ -final class FinalizeOrder implements Action -{ - public function __construct( - private readonly OrderTunnelService $orderTunnelService, - ) { - } - - /** - * @param \App\Cqs\Actions\Orders\FinalizeOrderInput $input - */ - #[\Override] - public function __invoke(ActionInput $input): OrderReference - { - Assert::isInstanceOf($input, FinalizeOrderInput::class); - - $builder = $this->orderTunnelService->getBuilderCompletedOrFail(); - $order = $this->orderTunnelService->finalizeOrder($builder); - - return $order->reference; - } -} diff --git a/app/Cqs/Actions/Orders/PlacePendingOrder.php b/app/Cqs/Actions/Orders/PlacePendingOrder.php new file mode 100644 index 00000000..6a6976cb --- /dev/null +++ b/app/Cqs/Actions/Orders/PlacePendingOrder.php @@ -0,0 +1,100 @@ + + * @implements \App\Contracts\ProvidesLockKey<\App\Cqs\Actions\Orders\PlacePendingOrderInput> + * @implements \App\Contracts\HandlesLockTimeout< + * \App\Cqs\Actions\Orders\PlacePendingOrderInput, + * \App\Cqs\Actions\Orders\PlacePendingOrderOutput + * > + */ +#[Locked(ttlSeconds: 30, waitSeconds: 10)] +final class PlacePendingOrder implements Action, HandlesLockTimeout, ProvidesLockKey +{ + public function __construct( + private readonly OrderTunnelService $orderTunnelService, + private readonly BasketRepository $basketRepository, + ) { + } + + /** + * @param \App\Cqs\Actions\Orders\PlacePendingOrderInput $input + */ + #[\Override] + public function lockKey(ActionInput $input): string + { + Assert::isInstanceOf($input, PlacePendingOrderInput::class); + + $shopperId = $input->shopperId ?? $this->orderTunnelService->getBuilderCompletedOrFail()->getShopperId(); + + return "order:finalize:shopper:{$shopperId->value}"; + } + + /** + * @param \App\Cqs\Actions\Orders\PlacePendingOrderInput $input + */ + #[\Override] + public function onLockTimeout(ActionInput $input): PlacePendingOrderOutput + { + Assert::isInstanceOf($input, PlacePendingOrderInput::class); + + return PlacePendingOrderOutput::lockTimeout(); + } + + /** + * @param \App\Cqs\Actions\Orders\PlacePendingOrderInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): PlacePendingOrderOutput + { + Assert::isInstanceOf($input, PlacePendingOrderInput::class); + + $builder = $this->orderTunnelService->getBuilderCompletedOrFail(); + + try { + $order = $this->orderTunnelService->placePendingOrder($builder); + } catch (BasketPriceChangedException $e) { + $this->basketRepository->persist($e->refreshedBasket); + + return PlacePendingOrderOutput::basketPriceChanged($e->getMessage()); + } catch ( + ExpiredPickupTimeSlotException + | InactiveShopperException + | UnorderableProductException + | OrderLimitExceededException + | WeeklyLimitExceededException $e + ) { + return match (true) { + $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 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/PlacePendingOrderOutput.php b/app/Cqs/Actions/Orders/PlacePendingOrderOutput.php new file mode 100644 index 00000000..bb0d61f9 --- /dev/null +++ b/app/Cqs/Actions/Orders/PlacePendingOrderOutput.php @@ -0,0 +1,84 @@ + + */ +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 @@ + + */ +final class UpsertShopsPickupExceptionsForYear implements Action +{ + /** + * @param \App\Cqs\Actions\PickupExceptions\UpsertShopsPickupExceptionsForYearInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): void + { + Assert::isInstanceOf($input, UpsertShopsPickupExceptionsForYearInput::class); + + if ($input->holidays === []) { + return; + } + + foreach ($input->holidays as $holiday) { + $exception = PickupException::query() + ->firstOrNew([ + 'date' => $holiday->date->format('Y-m-d'), + 'label' => $holiday->label, + ]); + $exception->fill([ + 'date' => $holiday->date->format('Y-m-d'), + 'repeatable' => true, + 'repeat_frequency' => RepeatFrequency::YEARLY, + ]); + $exception->setAttribute('auto_updated', true); + $exception->saveOrFail(); + } + + $repeatables = PickupException::query() + ->whereYear('date', $input->year) + ->whereIn('label', array_map( + fn (PublicHolidayDto $holiday): string => $holiday->label, + $input->holidays + )) + ->get(); + + Shop::query()->get() + ->each(fn (Shop $shop) => $shop->pickupExceptions() + ->syncWithoutDetaching($repeatables)); + } +} diff --git a/app/Cqs/Actions/PickupExceptions/UpsertShopsPickupExceptionsForYearInput.php b/app/Cqs/Actions/PickupExceptions/UpsertShopsPickupExceptionsForYearInput.php new file mode 100644 index 00000000..ee1f0f19 --- /dev/null +++ b/app/Cqs/Actions/PickupExceptions/UpsertShopsPickupExceptionsForYearInput.php @@ -0,0 +1,23 @@ + $holidays + */ + public function __construct( + public int $year, + public array $holidays, + ) { + Assert::greaterThanEq($this->year, 2026); + Assert::allIsInstanceOf($this->holidays, PublicHolidayDto::class); + } +} diff --git a/app/Cqs/Actions/ProductIncos/AssociateProductInco.php b/app/Cqs/Actions/ProductIncos/AssociateProductInco.php index 4a31d27d..f2f56526 100644 --- a/app/Cqs/Actions/ProductIncos/AssociateProductInco.php +++ b/app/Cqs/Actions/ProductIncos/AssociateProductInco.php @@ -11,7 +11,10 @@ use App\Services\ArcadiaIncoService; use Webmozart\Assert\Assert; /** - * @implements \App\Contracts\Action<\App\Cqs\Actions\ProductIncos\AssociateProductIncoInput, \App\Models\ProductInco> + * @implements \App\Contracts\Action< + * \App\Cqs\Actions\ProductIncos\AssociateProductIncoInput, + * \App\Cqs\Actions\ProductIncos\AssociateProductIncoOutput + * > */ final class AssociateProductInco implements Action { @@ -24,36 +27,34 @@ final class AssociateProductInco implements Action * @param \App\Cqs\Actions\ProductIncos\AssociateProductIncoInput $input */ #[\Override] - public function __invoke(ActionInput $input): ProductInco + public function __invoke(ActionInput $input): AssociateProductIncoOutput { Assert::isInstanceOf($input, AssociateProductIncoInput::class); - $incoData = $this->arcadiaIncoService->fetchInco($input->no_art); - - if ($incoData === null) { - throw new \RuntimeException(sprintf('INCO sheet #%d was not found on Arcadia API.', $input->no_art)); + try { + $incoData = $this->arcadiaIncoService->fetchInco($input->no_art); + } catch (\RuntimeException $e) { + return AssociateProductIncoOutput::apiError($e->getMessage()); } + if ($incoData === null) { + return AssociateProductIncoOutput::notFoundOnArcadia($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->no_art = $incoData->noArt; - $inco->ingredients = $incoData->ingredients; - $inco->preparation = $incoData->preparation; - $inco->servings = $incoData->servings; - $inco->allergens = $incoData->allergens; - $inco->selling_argument = $incoData->sellingArgument; - $inco->nutriscore = $incoData->nutriscore; - $inco->nutriscore_args = $incoData->nutriscoreArgs; - $inco->nutrition = $incoData->nutrition; - + $inco = new ProductInco(); + $inco->product_id = $productId; + $inco->no_art = $incoData->noArt; + $inco->hydrateFromArcadiaDto($incoData); $inco->saveOrFail(); - return $inco; + return AssociateProductIncoOutput::success($inco); } } 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/AssociateProductIncoOutput.php b/app/Cqs/Actions/ProductIncos/AssociateProductIncoOutput.php new file mode 100644 index 00000000..293a8aba --- /dev/null +++ b/app/Cqs/Actions/ProductIncos/AssociateProductIncoOutput.php @@ -0,0 +1,42 @@ + + * @implements \App\Contracts\Action< + * \App\Cqs\Actions\ProductIncos\SyncProductIncoInput, + * \App\Cqs\Actions\ProductIncos\SyncProductIncoOutput + * > */ final class SyncProductInco implements Action { @@ -24,31 +27,31 @@ final class SyncProductInco implements Action * @param \App\Cqs\Actions\ProductIncos\SyncProductIncoInput $input */ #[\Override] - public function __invoke(ActionInput $input): ProductInco + public function __invoke(ActionInput $input): SyncProductIncoOutput { 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.'); + return SyncProductIncoOutput::notAssociated(); + } + + try { + $incoData = $this->arcadiaIncoService->fetchInco($inco->no_art); + } catch (\RuntimeException $e) { + return SyncProductIncoOutput::apiError($e->getMessage()); } - $incoData = $this->arcadiaIncoService->fetchInco($inco->no_art); if ($incoData === null) { - throw new \RuntimeException(sprintf('INCO sheet #%d was not found on Arcadia API.', $inco->no_art)); + return SyncProductIncoOutput::notFoundOnArcadia($inco->no_art); } - $inco->ingredients = $incoData->ingredients; - $inco->preparation = $incoData->preparation; - $inco->servings = $incoData->servings; - $inco->allergens = $incoData->allergens; - $inco->selling_argument = $incoData->sellingArgument; - $inco->nutriscore = $incoData->nutriscore; - $inco->nutriscore_args = $incoData->nutriscoreArgs; - $inco->nutrition = $incoData->nutrition; - + $inco->hydrateFromArcadiaDto($incoData); $inco->saveOrFail(); - return $inco; + return SyncProductIncoOutput::success($inco); } } 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/Actions/ProductIncos/SyncProductIncoOutput.php b/app/Cqs/Actions/ProductIncos/SyncProductIncoOutput.php new file mode 100644 index 00000000..55cdf5fb --- /dev/null +++ b/app/Cqs/Actions/ProductIncos/SyncProductIncoOutput.php @@ -0,0 +1,50 @@ + */ +#[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,16 +62,10 @@ final class SynchronizeProductIncosWithArcadiaApi implements Action continue; } - $inco->ingredients = $incoData->ingredients; - $inco->preparation = $incoData->preparation; - $inco->servings = $incoData->servings; - $inco->allergens = $incoData->allergens; - $inco->selling_argument = $incoData->sellingArgument; - $inco->nutriscore = $incoData->nutriscore; - $inco->nutriscore_args = $incoData->nutriscoreArgs; - $inco->nutrition = $incoData->nutrition; - - $inco->saveOrFail(); + DB::transaction(static function () use ($inco, $incoData): void { + $inco->hydrateFromArcadiaDto($incoData); + $inco->saveOrFail(); + }); $updatedCount++; } diff --git a/app/Cqs/Actions/Products/CreateProduct.php b/app/Cqs/Actions/Products/CreateProduct.php index 8cdf4f30..827e1597 100644 --- a/app/Cqs/Actions/Products/CreateProduct.php +++ b/app/Cqs/Actions/Products/CreateProduct.php @@ -6,17 +6,36 @@ namespace App\Cqs\Actions\Products; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Contracts\HandlesFailure; +use App\Contracts\HandlesSuccess; +use App\Lib\PublicS3Disk; use App\Models\Product; use App\Models\Tag; +use App\Services\ImageOptimizerService; +use App\Traits\TracksPendingStoragePaths; +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; /** * @implements \App\Contracts\Action<\App\Cqs\Actions\Products\CreateProductInput, \App\Models\Product> + * @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Products\CreateProductInput, \App\Models\Product> + * @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Products\CreateProductInput> */ -final class CreateProduct implements Action +final class CreateProduct implements Action, HandlesFailure, HandlesSuccess { + use TracksPendingStoragePaths; + + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Products\CreateProductInput $input */ @@ -44,14 +63,18 @@ 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) { + $picturePath = $this->storeFile($input->picture); + $product->picture = $picturePath; + $this->trackUploadedPath($input, $picturePath); } $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) { + $pictureLargePath = $this->storeFile($input->pictureLarge); + $product->picture_large = $pictureLargePath; + $this->trackUploadedPath($input, $pictureLargePath); } $product->picture_large_alt = (string) $input->pictureLargeAlt; $product->picture_large_title = (string) $input->pictureLargeTitle; @@ -106,4 +129,27 @@ final class CreateProduct implements Action $product->products()->sync($syncData); } + + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + $this->clearTrackedPaths($input); + } + + #[\Override] + public function onFailure(ActionInput $input, \Throwable $exception): void + { + foreach ($this->pullUploadedPaths($input) as $path) { + if ($this->storageService->fileExistsOnDisk($path, $this->s3Disk->disk)) { + $this->storageService->removeFromDisk($path, $this->s3Disk->disk); + } + } + } + + 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..39e7927b 100644 --- a/app/Cqs/Actions/Products/DeleteProduct.php +++ b/app/Cqs/Actions/Products/DeleteProduct.php @@ -6,6 +6,7 @@ namespace App\Cqs\Actions\Products; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Models\Product; use Webmozart\Assert\Assert; /** @@ -21,6 +22,15 @@ 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; + } + + // NOTE: Product uses SoftDeletes so it will not be permanently removed from the database. + 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..f36f8431 100644 --- a/app/Cqs/Actions/Products/UpdateProduct.php +++ b/app/Cqs/Actions/Products/UpdateProduct.php @@ -6,17 +6,31 @@ namespace App\Cqs\Actions\Products; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Contracts\HandlesFailure; +use App\Contracts\HandlesSuccess; use App\Models\Product; use App\Models\Tag; +use App\Services\PublicImageStorageService; +use App\Traits\TracksPendingStoragePaths; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Date; use Illuminate\Support\Str; use Webmozart\Assert\Assert; /** * @implements \App\Contracts\Action<\App\Cqs\Actions\Products\UpdateProductInput, \App\Models\Product> + * @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Products\UpdateProductInput, \App\Models\Product> + * @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Products\UpdateProductInput> */ -final class UpdateProduct implements Action +final class UpdateProduct implements Action, HandlesFailure, HandlesSuccess { + use TracksPendingStoragePaths; + + public function __construct( + private readonly PublicImageStorageService $publicImageStorageService, + ) { + } + /** * @param \App\Cqs\Actions\Products\UpdateProductInput $input */ @@ -25,7 +39,13 @@ final class UpdateProduct implements Action { Assert::isInstanceOf($input, UpdateProductInput::class); - $product = $input->product; + $product = Product::query() + ->where('id', $input->productId->value->toString()) + ->firstOrFail(); + $previousPicture = $product->picture; + $previousPictureLarge = $product->picture_large; + $newPicture = null; + $newPictureLarge = null; $product->name = $input->name; $product->short_description = $input->shortDescription; $product->description = $input->description; @@ -44,14 +64,18 @@ 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) { + $newPicture = $this->publicImageStorageService->store($input->picture); + $product->setAttribute('picture', $newPicture); + $this->trackUploadedPath($input, $newPicture); } $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) { + $newPictureLarge = $this->publicImageStorageService->store($input->pictureLarge); + $product->setAttribute('picture_large', $newPictureLarge); + $this->trackUploadedPath($input, $newPictureLarge); } $product->picture_large_alt = (string) $input->pictureLargeAlt; $product->picture_large_title = (string) $input->pictureLargeTitle; @@ -61,9 +85,28 @@ final class UpdateProduct implements Action $this->syncTags($input->tags, $product); $this->syncAssociatedProducts($input->associatedProductsIds, $product); + $this->trackReplacedPath($input, $previousPicture, $newPicture); + $this->trackReplacedPath($input, $previousPictureLarge, $newPictureLarge); + return $product; } + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + foreach ($this->pullObsoletePaths($input) as $path) { + $this->publicImageStorageService->deleteIfExists($path); + } + } + + #[\Override] + public function onFailure(ActionInput $input, \Throwable $exception): void + { + foreach ($this->pullUploadedPaths($input) as $path) { + $this->publicImageStorageService->deleteIfExists($path); + } + } + /** * @param array $tags */ 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..a7a6a3ba 100644 --- a/app/Cqs/Actions/Ranges/CreateRange.php +++ b/app/Cqs/Actions/Ranges/CreateRange.php @@ -6,14 +6,33 @@ namespace App\Cqs\Actions\Ranges; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Contracts\HandlesFailure; +use App\Contracts\HandlesSuccess; +use App\Lib\PublicS3Disk; use App\Models\Range; +use App\Services\ImageOptimizerService; +use App\Traits\TracksPendingStoragePaths; +use Illuminate\Http\UploadedFile; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; /** * @implements \App\Contracts\Action<\App\Cqs\Actions\Ranges\CreateRangeInput, \App\Models\Range> + * @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Ranges\CreateRangeInput, \App\Models\Range> + * @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Ranges\CreateRangeInput> */ -final class CreateRange implements Action +final class CreateRange implements Action, HandlesFailure, HandlesSuccess { + use TracksPendingStoragePaths; + + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Ranges\CreateRangeInput $input */ @@ -30,8 +49,10 @@ final class CreateRange implements Action 'status' => $input->status, ]; - if ($input->picture !== null) { - $attributes['picture'] = $input->picture; + if ($input->picture instanceof UploadedFile) { + $storedPath = $this->storeFile($input->picture); + $attributes['picture'] = $storedPath; + $this->trackUploadedPath($input, $storedPath); } $range = new Range(); @@ -40,4 +61,27 @@ final class CreateRange implements Action return $range; } + + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + $this->clearTrackedPaths($input); + } + + #[\Override] + public function onFailure(ActionInput $input, \Throwable $exception): void + { + foreach ($this->pullUploadedPaths($input) as $path) { + if ($this->storageService->fileExistsOnDisk($path, $this->s3Disk->disk)) { + $this->storageService->removeFromDisk($path, $this->s3Disk->disk); + } + } + } + + 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..b70c1855 100644 --- a/app/Cqs/Actions/Ranges/DeleteRange.php +++ b/app/Cqs/Actions/Ranges/DeleteRange.php @@ -6,13 +6,28 @@ namespace App\Cqs\Actions\Ranges; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Contracts\HandlesFailure; +use App\Contracts\HandlesSuccess; +use App\Lib\PublicS3Disk; +use App\Traits\TracksPendingStoragePaths; +use Uwil\Storage\Contracts\StorageService; use Webmozart\Assert\Assert; /** * @implements \App\Contracts\Action<\App\Cqs\Actions\Ranges\DeleteRangeInput, bool> + * @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Ranges\DeleteRangeInput, bool> + * @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Ranges\DeleteRangeInput> */ -final class DeleteRange implements Action +final class DeleteRange implements Action, HandlesFailure, HandlesSuccess { + use TracksPendingStoragePaths; + + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + ) { + } + /** * @param \App\Cqs\Actions\Ranges\DeleteRangeInput $input */ @@ -21,6 +36,29 @@ final class DeleteRange implements Action { Assert::isInstanceOf($input, DeleteRangeInput::class); - return (bool) $input->range->deleteOrFail(); + $picture = $input->range->picture; + $deletion = (bool) $input->range->deleteOrFail(); + + if ($deletion) { + $this->trackObsoletePath($input, $picture); + } + + return $deletion; + } + + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + foreach ($this->pullObsoletePaths($input) as $path) { + if ($this->storageService->fileExistsOnDisk($path, $this->s3Disk->disk)) { + $this->storageService->removeFromDisk($path, $this->s3Disk->disk); + } + } + } + + #[\Override] + public function onFailure(ActionInput $input, \Throwable $exception): void + { + $this->clearTrackedPaths($input); } } diff --git a/app/Cqs/Actions/Ranges/UpdateRange.php b/app/Cqs/Actions/Ranges/UpdateRange.php index 5e37f58a..97055198 100644 --- a/app/Cqs/Actions/Ranges/UpdateRange.php +++ b/app/Cqs/Actions/Ranges/UpdateRange.php @@ -6,14 +6,28 @@ namespace App\Cqs\Actions\Ranges; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Contracts\HandlesFailure; +use App\Contracts\HandlesSuccess; use App\Models\Range; +use App\Services\PublicImageStorageService; +use App\Traits\TracksPendingStoragePaths; +use Illuminate\Http\UploadedFile; use Webmozart\Assert\Assert; /** * @implements \App\Contracts\Action<\App\Cqs\Actions\Ranges\UpdateRangeInput, \App\Models\Range> + * @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Ranges\UpdateRangeInput, \App\Models\Range> + * @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Ranges\UpdateRangeInput> */ -final class UpdateRange implements Action +final class UpdateRange implements Action, HandlesFailure, HandlesSuccess { + use TracksPendingStoragePaths; + + public function __construct( + private readonly PublicImageStorageService $publicImageStorageService, + ) { + } + /** * @param \App\Cqs\Actions\Ranges\UpdateRangeInput $input */ @@ -22,6 +36,9 @@ final class UpdateRange implements Action { Assert::isInstanceOf($input, UpdateRangeInput::class); + $previousPicture = $input->range->picture; + $newPicture = null; + $attributes = [ 'name' => $input->name, 'description' => $input->description, @@ -30,14 +47,34 @@ final class UpdateRange implements Action 'status' => $input->status, ]; - if ($input->picture !== null) { - $attributes['picture'] = $input->picture; + if ($input->picture instanceof UploadedFile) { + $newPicture = $this->publicImageStorageService->store($input->picture); + $attributes['picture'] = $newPicture; + $this->trackUploadedPath($input, $newPicture); } $range = $input->range; $range->fill($attributes); $range->saveOrFail(); + $this->trackReplacedPath($input, $previousPicture, $newPicture); + return $range; } + + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + foreach ($this->pullObsoletePaths($input) as $path) { + $this->publicImageStorageService->deleteIfExists($path); + } + } + + #[\Override] + public function onFailure(ActionInput $input, \Throwable $exception): void + { + foreach ($this->pullUploadedPaths($input) as $path) { + $this->publicImageStorageService->deleteIfExists($path); + } + } } 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/Shops/CreateShop.php b/app/Cqs/Actions/Shops/CreateShop.php index 1f9760bf..86c415ba 100644 --- a/app/Cqs/Actions/Shops/CreateShop.php +++ b/app/Cqs/Actions/Shops/CreateShop.php @@ -6,7 +6,9 @@ namespace App\Cqs\Actions\Shops; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Models\PickupException; use App\Models\Shop; +use Illuminate\Support\Facades\Date; use Webmozart\Assert\Assert; /** @@ -37,6 +39,15 @@ final class CreateShop implements Action $shop->default = $input->default; $shop->saveOrFail(); + $publicHolidays = PickupException::query() + ->where('auto_updated', true) + ->where('date', '>=', Date::now('Europe/Paris')->startOfYear()->format('Y-m-d')) + ->get(); + + if ($publicHolidays->isNotEmpty()) { + $shop->pickupExceptions()->syncWithoutDetaching($publicHolidays); + } + return $shop; } } diff --git a/app/Cqs/Actions/Slides/CreateSlide.php b/app/Cqs/Actions/Slides/CreateSlide.php index 92823dc1..291776ad 100644 --- a/app/Cqs/Actions/Slides/CreateSlide.php +++ b/app/Cqs/Actions/Slides/CreateSlide.php @@ -6,15 +6,34 @@ namespace App\Cqs\Actions\Slides; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Contracts\HandlesFailure; +use App\Contracts\HandlesSuccess; +use App\Lib\PublicS3Disk; use App\Models\Slide; +use App\Services\ImageOptimizerService; +use App\Traits\TracksPendingStoragePaths; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Carbon; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Webmozart\Assert\Assert; /** * @implements \App\Contracts\Action<\App\Cqs\Actions\Slides\CreateSlideInput, \App\Models\Slide> + * @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Slides\CreateSlideInput, \App\Models\Slide> + * @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Slides\CreateSlideInput> */ -final class CreateSlide implements Action +final class CreateSlide implements Action, HandlesFailure, HandlesSuccess { + use TracksPendingStoragePaths; + + public function __construct( + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, + protected readonly ImageOptimizerService $imageOptimizerService, + ) { + } + /** * @param \App\Cqs\Actions\Slides\CreateSlideInput $input */ @@ -36,8 +55,10 @@ 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) { + $storedPath = $this->storeFile($input->picture); + $attributes['picture'] = $storedPath; + $this->trackUploadedPath($input, $storedPath); } $slide = new Slide(); @@ -46,4 +67,27 @@ final class CreateSlide implements Action return $slide; } + + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + $this->clearTrackedPaths($input); + } + + #[\Override] + public function onFailure(ActionInput $input, \Throwable $exception): void + { + foreach ($this->pullUploadedPaths($input) as $path) { + if ($this->storageService->fileExistsOnDisk($path, $this->s3Disk->disk)) { + $this->storageService->removeFromDisk($path, $this->s3Disk->disk); + } + } + } + + 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..ab854dd5 100644 --- a/app/Cqs/Actions/Slides/DeleteSlide.php +++ b/app/Cqs/Actions/Slides/DeleteSlide.php @@ -6,13 +6,28 @@ namespace App\Cqs\Actions\Slides; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Contracts\HandlesFailure; +use App\Contracts\HandlesSuccess; +use App\Lib\PublicS3Disk; +use App\Traits\TracksPendingStoragePaths; +use Uwil\Storage\Contracts\StorageService; use Webmozart\Assert\Assert; /** * @implements \App\Contracts\Action<\App\Cqs\Actions\Slides\DeleteSlideInput, bool> + * @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Slides\DeleteSlideInput, bool> + * @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Slides\DeleteSlideInput> */ -final class DeleteSlide implements Action +final class DeleteSlide implements Action, HandlesFailure, HandlesSuccess { + use TracksPendingStoragePaths; + + public function __construct( + private readonly StorageService $storageService, + private readonly PublicS3Disk $s3Disk, + ) { + } + /** * @param \App\Cqs\Actions\Slides\DeleteSlideInput $input */ @@ -21,6 +36,29 @@ final class DeleteSlide implements Action { Assert::isInstanceOf($input, DeleteSlideInput::class); - return (bool) $input->slide->deleteOrFail(); + $picture = $input->slide->picture; + $deletion = (bool) $input->slide->deleteOrFail(); + + if ($deletion) { + $this->trackObsoletePath($input, $picture); + } + + return $deletion; + } + + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + foreach ($this->pullObsoletePaths($input) as $path) { + if ($this->storageService->fileExistsOnDisk($path, $this->s3Disk->disk)) { + $this->storageService->removeFromDisk($path, $this->s3Disk->disk); + } + } + } + + #[\Override] + public function onFailure(ActionInput $input, \Throwable $exception): void + { + $this->clearTrackedPaths($input); } } diff --git a/app/Cqs/Actions/Slides/UpdateSlide.php b/app/Cqs/Actions/Slides/UpdateSlide.php index 075af4e7..d710b3e9 100644 --- a/app/Cqs/Actions/Slides/UpdateSlide.php +++ b/app/Cqs/Actions/Slides/UpdateSlide.php @@ -6,15 +6,29 @@ namespace App\Cqs\Actions\Slides; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Contracts\HandlesFailure; +use App\Contracts\HandlesSuccess; use App\Models\Slide; +use App\Services\PublicImageStorageService; +use App\Traits\TracksPendingStoragePaths; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Carbon; use Webmozart\Assert\Assert; /** * @implements \App\Contracts\Action<\App\Cqs\Actions\Slides\UpdateSlideInput, \App\Models\Slide> + * @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Slides\UpdateSlideInput, \App\Models\Slide> + * @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Slides\UpdateSlideInput> */ -final class UpdateSlide implements Action +final class UpdateSlide implements Action, HandlesFailure, HandlesSuccess { + use TracksPendingStoragePaths; + + public function __construct( + private readonly PublicImageStorageService $publicImageStorageService, + ) { + } + /** * @param \App\Cqs\Actions\Slides\UpdateSlideInput $input */ @@ -23,6 +37,9 @@ final class UpdateSlide implements Action { Assert::isInstanceOf($input, UpdateSlideInput::class); + $previousPicture = $input->slide->picture; + $newPicture = null; + $attributes = [ 'title' => $input->title, 'text' => $input->text, @@ -36,14 +53,34 @@ 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) { + $newPicture = $this->publicImageStorageService->store($input->picture); + $attributes['picture'] = $newPicture; + $this->trackUploadedPath($input, $newPicture); } $slide = $input->slide; $slide->fill($attributes); $slide->saveOrFail(); + $this->trackReplacedPath($input, $previousPicture, $newPicture); + return $slide; } + + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + foreach ($this->pullObsoletePaths($input) as $path) { + $this->publicImageStorageService->deleteIfExists($path); + } + } + + #[\Override] + public function onFailure(ActionInput $input, \Throwable $exception): void + { + foreach ($this->pullUploadedPaths($input) as $path) { + $this->publicImageStorageService->deleteIfExists($path); + } + } } 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/Cqs/Actions/Slides/UpdateSlidesStatus.php b/app/Cqs/Actions/Slides/UpdateSlidesStatus.php new file mode 100644 index 00000000..0e5cc28e --- /dev/null +++ b/app/Cqs/Actions/Slides/UpdateSlidesStatus.php @@ -0,0 +1,68 @@ + + */ +final class UpdateSlidesStatus implements Action +{ + public function __construct( + private readonly LoggerInterface $logger, + ) { + } + + /** + * @param \App\Contracts\ActionInputEmpty $input + */ + #[\Override] + public function __invoke(ActionInput $input): void + { + Assert::isInstanceOf($input, ActionInputEmpty::class); + + $now = Date::now(); + + $unpublishQuery = Slide::query() + ->where('date_end', '<=', $now) + ->whereNotNull('date_end') + ->where('status', true); + + $unpublishCount = $unpublishQuery->count(); + $this->logger->debug(self::class . ' slides to unpublish ' . $unpublishCount); + + if ($unpublishCount > 0) { + $unpublishQuery->update([ + 'status' => false, + ]); + } + + $publishQuery = Slide::query() + ->where('date_start', '<=', $now) + ->whereNotNull('date_start') + ->where(function (Builder $query) use ($now): void { + $query->whereNull('date_end') + ->orWhere('date_end', '>', $now); + }) + ->where('status', false); + + $publishCount = $publishQuery->count(); + $this->logger->debug(self::class . ' slides to publish ' . $publishCount); + + if ($publishCount > 0) { + $publishQuery->update([ + 'status' => true, + ]); + } + } +} diff --git a/app/Cqs/Actions/Users/CreateUser.php b/app/Cqs/Actions/Users/CreateUser.php new file mode 100644 index 00000000..48ac76ba --- /dev/null +++ b/app/Cqs/Actions/Users/CreateUser.php @@ -0,0 +1,37 @@ + + */ +final class CreateUser implements Action +{ + /** + * @param \App\Cqs\Actions\Users\CreateUserInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): User + { + Assert::isInstanceOf($input, CreateUserInput::class); + + $user = new User(); + $user->firstname = $input->firstname; + $user->lastname = $input->lastname; + $user->email = $input->email; + $user->password = Hash::make($input->password); + $user->email_verified_at = now(); + $user->role = $input->role; + $user->saveOrFail(); + + return $user; + } +} diff --git a/app/Cqs/Actions/Users/CreateUserInput.php b/app/Cqs/Actions/Users/CreateUserInput.php new file mode 100644 index 00000000..a81d4c5f --- /dev/null +++ b/app/Cqs/Actions/Users/CreateUserInput.php @@ -0,0 +1,28 @@ +firstname)); + Assert::maxLength($this->firstname, 255); + Assert::stringNotEmpty(trim($this->lastname)); + Assert::maxLength($this->lastname, 255); + Assert::stringNotEmpty(trim($this->email)); + Assert::maxLength($this->email, 255); + Assert::stringNotEmpty($this->password); + } +} diff --git a/app/Cqs/Queries/Basket/GetBasketQuery.php b/app/Cqs/Queries/Basket/GetBasketQuery.php index 57009010..bea870e6 100644 --- a/app/Cqs/Queries/Basket/GetBasketQuery.php +++ b/app/Cqs/Queries/Basket/GetBasketQuery.php @@ -7,12 +7,15 @@ namespace App\Cqs\Queries\Basket; use App\Contracts\Query; use App\Contracts\QueryInput; use App\Contracts\QueryInputEmpty; -use Domain\Models\Entities\Basket; +use App\Dto\BasketDto; +use App\Dto\BasketProductDto; +use App\Models\Product; +use Domain\Models\ValueObjects\BasketProduct; use Domain\Services\BasketService; use Webmozart\Assert\Assert; /** - * @implements \App\Contracts\Query<\App\Contracts\QueryInputEmpty, \Domain\Models\Entities\Basket> + * @implements \App\Contracts\Query<\App\Contracts\QueryInputEmpty, \App\Dto\BasketDto> */ final readonly class GetBasketQuery implements Query { @@ -21,13 +24,41 @@ final readonly class GetBasketQuery implements Query ) { } - public function __invoke(QueryInput $input): Basket + #[\Override] + public function __invoke(QueryInput $input): BasketDto { Assert::isAOf( $input, QueryInputEmpty::class, ); - return $this->basketService->getBasket(); + $basket = $this->basketService->getBasket(); + $basketItems = array_values($basket->items()); + $ids = array_map( + static fn (BasketProduct $item): string => $item->id->value->toString(), + $basketItems + ); + + if ($ids === []) { + $publishedMap = []; + } else { + $publishedIds = Product::query() + ->whereIn('id', $ids) + ->where('status', true) + ->pluck('id') + ->all(); + Assert::allString($publishedIds); + $publishedMap = array_flip($publishedIds); + } + + $items = array_map( + static fn (BasketProduct $item): BasketProductDto => new BasketProductDto( + product: $item, + isPublished: isset($publishedMap[$item->id->value->toString()]), + ), + $basketItems + ); + + return BasketDto::fromEntity($basket, $items); } } diff --git a/app/Cqs/Queries/Discounts/GetDiscountFormDataQuery.php b/app/Cqs/Queries/Discounts/GetDiscountFormDataQuery.php index 4bd2c9fd..241e7fe3 100644 --- a/app/Cqs/Queries/Discounts/GetDiscountFormDataQuery.php +++ b/app/Cqs/Queries/Discounts/GetDiscountFormDataQuery.php @@ -47,6 +47,7 @@ final readonly class GetDiscountFormDataQuery implements Query $discountDto = DiscountDto::fromModel($input->discount); } else { + /** @var \Illuminate\Support\Collection */ $selectedProds = collect(); $existingProds = Product::query() ->select(['id', 'name', 'picture']) 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 eea184b1..52e1ac04 100644 --- a/app/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQuery.php +++ b/app/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQuery.php @@ -8,9 +8,9 @@ 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 SortDirection; use Webmozart\Assert\Assert; /** @@ -44,7 +44,8 @@ final readonly class GetFoCustomerPaginatedOrdersQuery implements Query $paginator = Order::query() ->where('employee_matricule', $employeeMatricule->value) - ->orderBy('id', SortDirection::Descending) + ->whereNotIn('status', [OrderStatus::PENDING, OrderStatus::FAILED]) + ->orderBy('id', \SortDirection::Descending) ->paginate( perPage: $input->pagination->pageSize()->value(), page: $input->pagination->pageNumber()->value(), diff --git a/app/Cqs/Queries/Orders/GetPickTimeSlotQueryOutput.php b/app/Cqs/Queries/Orders/GetPickTimeSlotQueryOutput.php index 48a3cf93..ce940050 100644 --- a/app/Cqs/Queries/Orders/GetPickTimeSlotQueryOutput.php +++ b/app/Cqs/Queries/Orders/GetPickTimeSlotQueryOutput.php @@ -11,7 +11,7 @@ use Domain\Models\ValueObjects\PickupTimeSlot; final readonly class GetPickTimeSlotQueryOutput { /** - * @param array $timeSlots + * @param array $timeSlots */ public function __construct( public OrderTunnelStep $step, diff --git a/app/Cqs/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQuery.php b/app/Cqs/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQuery.php new file mode 100644 index 00000000..bac8ae0e --- /dev/null +++ b/app/Cqs/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQuery.php @@ -0,0 +1,33 @@ + + */ +final readonly class HasAutoUpdatedPickupExceptionsForYearQuery implements Query +{ + /** + * @param \App\Cqs\Queries\PickupExceptions\HasAutoUpdatedPickupExceptionsForYearQueryInput $input + */ + #[\Override] + public function __invoke(QueryInput $input): bool + { + Assert::isInstanceOf($input, HasAutoUpdatedPickupExceptionsForYearQueryInput::class); + + return PickupException::query() + ->whereYear('date', $input->year) + ->where('auto_updated', true) + ->exists(); + } +} diff --git a/app/Cqs/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryInput.php b/app/Cqs/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryInput.php new file mode 100644 index 00000000..4d97c6ba --- /dev/null +++ b/app/Cqs/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryInput.php @@ -0,0 +1,17 @@ +year, 2026); + } +} diff --git a/app/Cqs/Queries/ProductIncos/GetArcadiaIncoPreviewQuery.php b/app/Cqs/Queries/ProductIncos/GetArcadiaIncoPreviewQuery.php index 1bad4eb4..f33585a1 100644 --- a/app/Cqs/Queries/ProductIncos/GetArcadiaIncoPreviewQuery.php +++ b/app/Cqs/Queries/ProductIncos/GetArcadiaIncoPreviewQuery.php @@ -6,12 +6,14 @@ namespace App\Cqs\Queries\ProductIncos; use App\Contracts\Query; use App\Contracts\QueryInput; -use App\Dto\ArcadiaIncoPreviewDto; use App\Services\ArcadiaIncoService; use Webmozart\Assert\Assert; /** - * @implements \App\Contracts\Query<\App\Cqs\Queries\ProductIncos\GetArcadiaIncoPreviewQueryInput, ?\App\Dto\ArcadiaIncoPreviewDto> + * @implements \App\Contracts\Query< + * \App\Cqs\Queries\ProductIncos\GetArcadiaIncoPreviewQueryInput, + * \App\Cqs\Queries\ProductIncos\GetArcadiaIncoPreviewQueryOutput + * > */ final readonly class GetArcadiaIncoPreviewQuery implements Query { @@ -21,10 +23,18 @@ final readonly class GetArcadiaIncoPreviewQuery implements Query } #[\Override] - public function __invoke(QueryInput $input): ?ArcadiaIncoPreviewDto + public function __invoke(QueryInput $input): GetArcadiaIncoPreviewQueryOutput { Assert::isInstanceOf($input, GetArcadiaIncoPreviewQueryInput::class); - return $this->arcadiaIncoService->getPreview($input->noArt); + try { + $preview = $this->arcadiaIncoService->getPreview($input->noArt); + } catch (\RuntimeException $e) { + return GetArcadiaIncoPreviewQueryOutput::apiError($e->getMessage()); + } + + return $preview !== null + ? GetArcadiaIncoPreviewQueryOutput::found($preview) + : GetArcadiaIncoPreviewQueryOutput::notFound(); } } diff --git a/app/Cqs/Queries/ProductIncos/GetArcadiaIncoPreviewQueryOutput.php b/app/Cqs/Queries/ProductIncos/GetArcadiaIncoPreviewQueryOutput.php new file mode 100644 index 00000000..829f112f --- /dev/null +++ b/app/Cqs/Queries/ProductIncos/GetArcadiaIncoPreviewQueryOutput.php @@ -0,0 +1,41 @@ + + */ +final readonly class GetProductIncoForEditQuery implements Query +{ + public function __construct( + private ProductDtoAssemblerService $assembler, + ) { + } + + /** + * @param \App\Cqs\Queries\ProductIncos\GetProductIncoForEditQueryInput $input + */ + #[\Override] + public function __invoke(QueryInput $input): GetProductIncoForEditQueryOutput + { + Assert::isInstanceOf($input, GetProductIncoForEditQueryInput::class); + + $product = Product::query() + ->with(['inco', 'validDiscount', 'range']) + ->where('id', $input->productId->value->toString()) + ->firstOrFail(); + + return new GetProductIncoForEditQueryOutput( + product: $this->assembler->toDto($product), + inco: $product->inco instanceof ProductInco ? ProductIncoDto::fromModel($product->inco) : null, + ); + } +} diff --git a/app/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryInput.php b/app/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryInput.php new file mode 100644 index 00000000..8471abc8 --- /dev/null +++ b/app/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryInput.php @@ -0,0 +1,16 @@ +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..0e583baf 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() @@ -55,6 +59,7 @@ final readonly class GetFoProductIndexPageQuery implements Query )->values(); $rangeList = Range::query() + ->published() ->orderBy('order') ->get() ->map(fn (Range $range): RangeDto => RangeDto::fromModel($range)); 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..5a18461b 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', 'range']) + ->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( @@ -73,6 +91,7 @@ final readonly class GetProductFormDataQuery implements Query tags: $tags, existingProds: $existingProds, selectedProds: $selectedProds, + product: $product !== null ? $this->assembler->toDto($product) : null, ); } } 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/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 @@ + + */ +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']) + ->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 @@ + $pickupExceptions + * @param array $pickupExceptions */ public function __construct( public ShopDto $shop, diff --git a/app/Cqs/Queries/Timeslots/GetAvailableTimeslotsQueryOutput.php b/app/Cqs/Queries/Timeslots/GetAvailableTimeslotsQueryOutput.php index 39883a6e..82793250 100644 --- a/app/Cqs/Queries/Timeslots/GetAvailableTimeslotsQueryOutput.php +++ b/app/Cqs/Queries/Timeslots/GetAvailableTimeslotsQueryOutput.php @@ -13,9 +13,9 @@ final readonly class GetAvailableTimeslotsQueryOutput public function __construct( public array $timeslotList, ) { - Assert::allInArray( + Assert::allIsInstanceOf( $this->timeslotList, - fn ($value) => $value instanceof PickupTimeSlot, + PickupTimeSlot::class, 'All elements of $timeslotList must be instances of PickupTimeSlot' ); } diff --git a/app/Directories/EloquentCustomerDirectory.php b/app/Directories/EloquentCustomerDirectory.php deleted file mode 100644 index 7a7b7ba0..00000000 --- a/app/Directories/EloquentCustomerDirectory.php +++ /dev/null @@ -1,23 +0,0 @@ -toString()); - } - - public function getCustomerByEmail(Email $email): ?Customer - { - return Customer::where('email', $email->value)->first(); - } -} diff --git a/app/Directories/EloquentEmployeeDirectory.php b/app/Directories/EloquentEmployeeDirectory.php deleted file mode 100644 index 89042363..00000000 --- a/app/Directories/EloquentEmployeeDirectory.php +++ /dev/null @@ -1,53 +0,0 @@ -where('id', $id) - ->first(); - } - - public function countActiveEmployees(): int - { - return Employee::query() - ->active() - ->count(); - } - - public function countActiveRegisteredEmployees(): int - { - return Employee::query() - ->active() - ->whereHas('customer') - ->count(); - } - - public function countActiveEmployeesWithin(CarbonInterface $start, CarbonInterface $end): int - { - return Employee::query() - ->active() - ->whereDate('created_at', '>=', $start) - ->whereDate('created_at', '<=', $end) - ->count(); - } - - public function countActiveRegisteredEmployeesWithin(CarbonInterface $start, CarbonInterface $end): int - { - return Employee::query() - ->active() - ->whereHas('customer') - ->whereDate('created_at', '>=', $start) - ->whereDate('created_at', '<=', $end) - ->count(); - } -} diff --git a/app/Directories/EloquentOrderDirectory.php b/app/Directories/EloquentOrderDirectory.php deleted file mode 100644 index 048f17be..00000000 --- a/app/Directories/EloquentOrderDirectory.php +++ /dev/null @@ -1,185 +0,0 @@ - */ - public function getPaginatedOrdersOf( - Customer $customer, - Pagination $pagination, - bool $orderByDate = false - ): PaginationLengthAwarePaginator { - $query = $this->orderByQueryFor($customer); - - if ($query === null) { - return new LengthAwarePaginator( - items: [], - total: 0, - perPage: $pagination->pageSize()->value(), - currentPage: $pagination->pageNumber()->value(), - ); - } - - if ($orderByDate) { - $query->orderBy('id', SortDirection::Descending); - } - - return $query->paginate( - perPage: $pagination->pageSize()->value(), - page: $pagination->pageNumber()->value(), - ); - } - - public function find(UuidInterface $id): ?Order - { - return Order::query() - ->where('id', $id->toString()) - ->first(); - } - - public function findOf(Customer $customer, UuidInterface $id): ?Order - { - $query = $this->orderByQueryFor($customer); - if ($query === null) { - return null; - } - - return $query->where('id', $id->toString())->first(); - } - - /** @return \Illuminate\Database\Eloquent\Builder<\App\Models\Order>|null */ - private function orderByQueryFor(Customer $customer): ?Builder - { - /** @var \Domain\Models\ValueObjects\Matricule | null */ - $employeeMatricule = $customer->employee()->value('matricule'); - - if ($employeeMatricule === null) { - return null; - } - - return Order::query() - ->where('employee_matricule', $employeeMatricule->value); - } - - /** - * @return Collection - */ - public function getValidatedOrders(CarbonInterface $start, CarbonInterface $end): Collection - { - return Order::query() - ->whereIn('status', [OrderStatus::VALIDATED->value]) - ->whereCreatedAtBetween($start, $end) - ->get(); - } - - /** - * @return Collection - */ - public function getOrdersByStatus(OrderStatus $status, CarbonInterface $start, CarbonInterface $end): Collection - { - return Order::query() - ->where('status', $status->value) - ->whereCreatedAtBetween($start, $end) - ->get(); - } - - public function getNbActiveClients(CarbonInterface $start, CarbonInterface $end): int - { - $matricules = Order::query() - ->whereCreatedAtBetween($start, $end) - ->get(['employee']) - ->map(fn (Order $order) => $order->employee->matricule->value) - ->filter() - ->unique(); - - if ($matricules->isEmpty()) { - return 0; - } - - return Customer::query() - ->whereHas('employee', function (Builder $query) use ($matricules): void { - $query->whereIn('matricule', $matricules); - })->count(); - } - - public function getNbCmdWith7DayDelay(CarbonInterface $start, CarbonInterface $end): int - { - return Order::query() - ->whereIn('status', [OrderStatus::VALIDATED->value]) - ->whereCreatedAtBetween($start, $end) - ->get() - ->filter(function (Order $order) { - if (is_null($order->pickup_day) || is_null($order->created_at)) { - return false; - } - - return $order->pickup_day->lessThanOrEqualTo($order->created_at->modify('+7 day')); - })->count(); - } - - public function getNbCmdWith14DayDelay(CarbonInterface $start, CarbonInterface $end): int - { - return Order::query() - ->whereIn('status', [OrderStatus::VALIDATED->value]) - ->whereCreatedAtBetween($start, $end) - ->get() - ->filter(function (Order $order) { - if (is_null($order->pickup_day) || is_null($order->created_at)) { - return false; - } - - return Date::create($order->pickup_day)->betweenIncluded( - Date::create($order->created_at->modify('+8 day')), - Date::create($order->created_at->modify('+14 day')) - ); - })->count(); - } - - public function getCaHt(CarbonInterface $start, CarbonInterface $end): float - { - $totalCaHt = OrderLine::query()->whereHas('order', function (Builder $query) use ($start, $end): void { - $query->whereIn('status', [OrderStatus::VALIDATED->value]) - ->whereCreatedAtBetween($start, $end); - })->sum('total_ht'); - - return ((float) (new Money((int) $totalCaHt, resolve(Currency::class)))->getAmount()) / 100; - } - - public function getCaTtc(CarbonInterface $start, CarbonInterface $end): float - { - $totalCaTtc = OrderLine::query()->whereHas('order', function (Builder $query) use ($start, $end): void { - $query->whereIn('status', [OrderStatus::VALIDATED->value]) - ->whereCreatedAtBetween($start, $end); - })->sum('total_ttc'); - - return ((float) (new Money((int) $totalCaTtc, resolve(Currency::class)))->getAmount()) / 100; - } - - public function getTotalQuantity(CarbonInterface $start, CarbonInterface $end): int - { - return (int) OrderLine::query()->whereHas('order', function (Builder $query) use ($start, $end): void { - $query->where('status', OrderStatus::VALIDATED->value) - ->whereCreatedAtBetween($start, $end); - })->sum('quantity'); - } -} diff --git a/app/Dto/BasketDto.php b/app/Dto/BasketDto.php new file mode 100644 index 00000000..eacd538f --- /dev/null +++ b/app/Dto/BasketDto.php @@ -0,0 +1,43 @@ + $items + */ + public function __construct( + public array $items, + public Money $totalTaxIncluded, + public Money $totalVat, + public Money $totalRaw, + public Money $totalDiscount, + public int $totalWeight, + public int $countItems, + ) { + Assert::allIsInstanceOf($items, BasketProductDto::class); + } + + /** + * @param list<\App\Dto\BasketProductDto> $items + */ + public static function fromEntity(Basket $basket, array $items): self + { + return new self( + items: $items, + totalTaxIncluded: $basket->totalTaxIncluded(), + totalVat: $basket->totalVat(), + totalRaw: $basket->totalRaw(), + totalDiscount: $basket->totalDiscount(), + totalWeight: $basket->totalWeight(), + countItems: $basket->countItems(), + ); + } +} diff --git a/app/Dto/BasketProductDto.php b/app/Dto/BasketProductDto.php new file mode 100644 index 00000000..9f815ca8 --- /dev/null +++ b/app/Dto/BasketProductDto.php @@ -0,0 +1,16 @@ +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/FaqDto.php b/app/Dto/FaqDto.php index d57ce031..b34272b8 100644 --- a/app/Dto/FaqDto.php +++ b/app/Dto/FaqDto.php @@ -6,8 +6,12 @@ namespace App\Dto; use App\Models\Faq; use Illuminate\Contracts\Routing\UrlRoutable; +use Illuminate\Contracts\Support\Arrayable; -final readonly class FaqDto implements UrlRoutable +/** + * @implements Arrayable + */ +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..55a74f3a 100644 --- a/app/Dto/ProductDto.php +++ b/app/Dto/ProductDto.php @@ -5,10 +5,16 @@ declare(strict_types=1); namespace App\Dto; use App\Models\Product; +use App\Models\Tag; 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\ProductWeight; use Illuminate\Contracts\Routing\UrlRoutable; use Illuminate\Contracts\Support\Arrayable; +use Illuminate\Support\Carbon; use Money\Money; /** @@ -16,6 +22,9 @@ use Money\Money; */ final readonly class ProductDto implements Arrayable, UrlRoutable { + /** + * @param list $tags + */ public function __construct( public string $id, public string $name, @@ -30,39 +39,69 @@ final readonly class ProductDto implements Arrayable, UrlRoutable public ?string $picture_large_title = null, public ?Money $price = null, public ?DiscountDto $discount = null, + public ?TaxRate $tax_rate = null, + public ?InvoicingUnit $invoicing_unit = null, public int $stock = 0, public ?SellUnit $sell_unit = null, + public ?OrderUnit $order_unit = null, public ?RangeDto $range = null, + public array $tags = [], 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 ?Carbon $orderable_start = null, + public ?Carbon $orderable_end = null, 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); + + /** @var list $tags */ + $tags = $product->relationLoaded('tags') + ? array_values($product->tags->map(static fn (Tag $tag): TagDto => TagDto::fromModel($tag))->all()) + : []; + 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, + tax_rate: $product->tax_rate, + invoicing_unit: $product->invoicing_unit, stock: (int) $product->stock, sell_unit: $product->sell_unit, + order_unit: $product->order_unit, range: $product->relationLoaded('range') && $product->range ? RangeDto::fromModel($product->range) : null, + tags: $tags, 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, + orderable_start: $product->orderable_start, + orderable_end: $product->orderable_end, short_description: $product->short_description, description: $product->description, ); @@ -110,16 +149,42 @@ final readonly class ProductDto implements Arrayable, UrlRoutable 'picture_large' => $this->picture_large, 'picture_large_alt' => $this->picture_large_alt, 'picture_large_title' => $this->picture_large_title, - 'price' => $this->price?->getAmount(), - 'discount' => $this->discount?->toArray(), - 'stock' => $this->stock, - 'sell_unit' => $this->sell_unit?->value, + ...$this->pricingAndUnitsToArray(), 'range' => $this->range?->toArray(), + 'tags' => array_map(static fn (TagDto $tag): array => $tag->toArray(), $this->tags), 'order' => $this->order, + 'product_weight' => $this->product_weight?->value, + 'weight_variable' => $this->weight_variable, 'status' => $this->status, 'star' => $this->star, + 'orderable_start' => $this->orderable_start, + 'orderable_end' => $this->orderable_end, 'short_description' => $this->short_description, 'description' => $this->description, ]; } + + /** + * @return array{ + * price: string|null, + * discount: array|null, + * tax_rate: int|null, + * invoicing_unit: string|null, + * stock: int, + * sell_unit: string|null, + * order_unit: string|null + * } + */ + private function pricingAndUnitsToArray(): array + { + return [ + 'price' => $this->price?->getAmount(), + 'discount' => $this->discount?->toArray(), + 'tax_rate' => $this->tax_rate?->value, + 'invoicing_unit' => $this->invoicing_unit?->value, + 'stock' => $this->stock, + 'sell_unit' => $this->sell_unit?->value, + 'order_unit' => $this->order_unit?->value, + ]; + } } diff --git a/app/Dto/ProductFormDataDto.php b/app/Dto/ProductFormDataDto.php index b3121d85..e67bc91b 100644 --- a/app/Dto/ProductFormDataDto.php +++ b/app/Dto/ProductFormDataDto.php @@ -34,6 +34,7 @@ final readonly class ProductFormDataDto public Collection $tags, public Collection $existingProds, public Collection $selectedProds, + public ?ProductDto $product = null, ) { } } 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/PublicHolidayDto.php b/app/Dto/PublicHolidayDto.php new file mode 100644 index 00000000..bfce6b21 --- /dev/null +++ b/app/Dto/PublicHolidayDto.php @@ -0,0 +1,16 @@ +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/SettingDto.php b/app/Dto/SettingDto.php index be99389e..0c74c7ea 100644 --- a/app/Dto/SettingDto.php +++ b/app/Dto/SettingDto.php @@ -15,7 +15,7 @@ use Illuminate\Contracts\Support\Arrayable; final readonly class SettingDto implements Arrayable, UrlRoutable { /** - * @param array $employeeSites + * @param array $employeeSites */ public function __construct( public int $id, @@ -37,7 +37,7 @@ final readonly class SettingDto implements Arrayable, UrlRoutable } /** - * @return array + * @return array<\Domain\Models\ValueObjects\ShopperSiteCode> */ public function getShopperSiteCodes(): array { @@ -72,7 +72,7 @@ final readonly class SettingDto implements Arrayable, UrlRoutable } /** - * @return array{id: int, employee_sites: array} + * @return array{id: int, employee_sites: array} */ #[\Override] public function toArray(): array 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/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/Enums/ApplyPickTimeSlotStatus.php b/app/Enums/ApplyPickTimeSlotStatus.php new file mode 100644 index 00000000..ebd1bdbb --- /dev/null +++ b/app/Enums/ApplyPickTimeSlotStatus.php @@ -0,0 +1,11 @@ +render( + fn (RegateExportFailedException $_, Request $__) => to_route('fo.sales.confirmation') + ->with( + 'message', + __('An error occurred while validating your order. Please try again later.') + ) + ); + $exceptions->render(function (CustomerNotEmployedException $_, Request $request) { Auth::guard('frontend')->logout(); $request->session()->invalidate(); 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 @@ +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/OrdersController.php b/app/Http/Controllers/Bo/OrdersController.php index 8143b8a4..b9bce6a0 100644 --- a/app/Http/Controllers/Bo/OrdersController.php +++ b/app/Http/Controllers/Bo/OrdersController.php @@ -7,6 +7,7 @@ namespace App\Http\Controllers\Bo; use App\Contracts\Executor; use App\Cqs\Actions\Orders\CancelOrder; use App\Cqs\Actions\Orders\CancelOrderInput; +use App\Cqs\Actions\Orders\CancelOrderOutput; use App\Cqs\Queries\Orders\GetBoOrderDetailQuery; use App\Cqs\Queries\Orders\GetBoOrderDetailQueryInput; use App\Cqs\Queries\Orders\GetBoPaginatedOrdersQuery; @@ -76,15 +77,14 @@ class OrdersController extends Controller { $this->authorize('cancel', $order); - try { - $this->executor->execute( - $action, - new CancelOrderInput($order), - ); - } catch (\Throwable) { - return back()->with('error', trans('Action failed')); - } + $output = $this->executor->execute( + $action, + new CancelOrderInput($order), + ); - return back()->with('warning', trans('Order cancelled')); + return match ($output) { + CancelOrderOutput::CANCELLED => back()->with('warning', trans('Order cancelled')), + CancelOrderOutput::NOT_FOUND => back()->with('error', trans('Action failed')), + }; } } 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..c87716b7 100644 --- a/app/Http/Controllers/Bo/ProductIncosController.php +++ b/app/Http/Controllers/Bo/ProductIncosController.php @@ -8,8 +8,10 @@ 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\Cqs\Queries\ProductIncos\GetProductIncoForEditQuery; +use App\Cqs\Queries\ProductIncos\GetProductIncoForEditQueryInput; +use App\Enums\ArcadiaIncoPreviewStatus; +use App\Enums\ProductIncoSyncStatus; use App\Http\Controllers\Controller; use App\Http\Requests\Bo\ProductIncos\AssociateProductIncoRequest; use App\Http\Requests\Bo\ProductIncos\PreviewArcadiaIncoRequest; @@ -19,6 +21,7 @@ use App\Models\ProductInco; use Illuminate\Contracts\View\View; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; +use Webmozart\Assert\Assert; class ProductIncosController extends Controller { @@ -31,76 +34,98 @@ class ProductIncosController extends Controller { $this->authorize('associateInco', $product); - try { - $preview = $this->executor->execute( - $query, - $request->toGetArcadiaIncoPreviewQueryInput(), - ); - } catch (\RuntimeException $e) { - return response()->json([ - 'message' => __('Arcadia API error: :error', ['error' => $e->getMessage()]), - ], 502); - } + $output = $this->executor->execute( + $query, + $request->toGetArcadiaIncoPreviewQueryInput(), + ); - if ($preview === null) { - return response()->json([ + return match ($output->status) { + ArcadiaIncoPreviewStatus::FOUND => response()->json($output->preview), + ArcadiaIncoPreviewStatus::NOT_FOUND => response()->json([ 'message' => __('No INCO sheet found on Arcadia for this article number.'), - ], 404); - } - - return response()->json($preview); + ], 404), + ArcadiaIncoPreviewStatus::API_ERROR => response()->json([ + 'message' => __('Arcadia API error: :error', ['error' => $output->errorMessage ?? '']), + ], 502), + }; } public function associate(AssociateProductIncoRequest $request, Product $product, AssociateProductInco $action): RedirectResponse { $this->authorize('associateInco', $product); - try { - $inco = $this->executor->execute( - $action, - $request->toAssociateProductIncoInput($product), - ); - } catch (\RuntimeException $e) { - return back()->with('danger', __('Arcadia API error: :error', ['error' => $e->getMessage()])); - } + $output = $this->executor->execute( + $action, + $request->toAssociateProductIncoInput($product->getId()), + ); - return to_route('bo.products.incos.edit', compact('product', 'inco')) - ->with('success', __('The INCO sheet has been successfully associated with the product.')); + return $this->buildSyncRedirect( + $output->status, + $product, + $output->inco, + $output->errorMessage, + __('The INCO sheet has been successfully associated with the product.'), + ); } public function sync(SyncProductIncoRequest $request, Product $product, SyncProductInco $action): RedirectResponse { $this->authorize('syncInco', $product); - try { - $inco = $this->executor->execute( - $action, - $request->toSyncProductIncoInput($product), - ); - } catch (\RuntimeException $e) { - return back()->with('danger', __('Arcadia API error: :error', ['error' => $e->getMessage()])); - } + $output = $this->executor->execute( + $action, + $request->toSyncProductIncoInput($product->getId()), + ); - return to_route('bo.products.incos.edit', compact('product', 'inco')) - ->with('success', __('The INCO sheet has been successfully synchronized from Arcadia.')); + return $this->buildSyncRedirect( + $output->status, + $product, + $output->inco, + $output->errorMessage, + __('The INCO sheet has been successfully synchronized from Arcadia.'), + ); } - public function create(Product $product): View + private function buildSyncRedirect( + ProductIncoSyncStatus $status, + Product $product, + ?ProductInco $inco, + ?string $errorMessage, + string $successMessage, + ): RedirectResponse { + return match ($status) { + ProductIncoSyncStatus::SUCCESS => $this->redirectToEditSuccess($product, $inco, $successMessage), + ProductIncoSyncStatus::NOT_ASSOCIATED, + ProductIncoSyncStatus::NOT_FOUND_ON_ARCADIA, + ProductIncoSyncStatus::API_ERROR => back()->with( + 'danger', + __('Arcadia API error: :error', ['error' => $errorMessage ?? '']), + ), + }; + } + + private function redirectToEditSuccess(Product $product, ?ProductInco $inco, string $message): RedirectResponse { - return $this->edit($product); + Assert::notNull($inco); + + return to_route('bo.products.incos.edit', [ + 'product' => $product, + 'inco' => $inco, + ])->with('success', $message); } - public function edit(Product $product, ?ProductInco $inco = null): View + public function edit(Product $product, GetProductIncoForEditQuery $query): View { $this->authorize('associateInco', $product); - $productDto = ProductDto::fromModel($product); - $incoModel = $inco ?? $product->inco; - $incoDto = $incoModel instanceof ProductInco ? ProductIncoDto::fromModel($incoModel) : null; + $output = $this->executor->execute( + $query, + new GetProductIncoForEditQueryInput($product->getId()), + ); return view('bo.product-incos.edit', [ - 'product' => $productDto, - 'inco' => $incoDto, + 'product' => $output->product, + 'inco' => $output->inco, ]); } } diff --git a/app/Http/Controllers/Bo/ProductsController.php b/app/Http/Controllers/Bo/ProductsController.php index 9cee5f75..c021a3d3 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' => $formData->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/Auth/AuthController.php b/app/Http/Controllers/Fo/Auth/AuthController.php index c8c71152..958f29c3 100644 --- a/app/Http/Controllers/Fo/Auth/AuthController.php +++ b/app/Http/Controllers/Fo/Auth/AuthController.php @@ -5,65 +5,7 @@ declare(strict_types=1); namespace App\Http\Controllers\Fo\Auth; use App\Http\Controllers\Controller; -use App\Models\Customer; -use Illuminate\Auth\Notifications\ResetPassword; -use Illuminate\Auth\Notifications\VerifyEmail; -use Illuminate\Support\Facades\Config; -use Illuminate\Support\Facades\Date; -use Illuminate\Support\Facades\URL; abstract class AuthController extends Controller { - public function __construct() - { - ResetPassword::$createUrlCallback = $this->createResetUrl(...); - VerifyEmail::$createUrlCallback = $this->createValidationUrl(...); - } - - public function createValidationUrl(Customer $notifiable): string - { - $appKey = Config::string('app.key'); - - if (empty(trim($appKey))) { - throw new \UnexpectedValueException('App key is not set.'); - } - - return url( - URL::temporarySignedRoute( - 'fo.auth.verification.verify', - Date::now()->addMinutes(Config::integer( - 'auth.verification.expire', - 60 - )), - [ - 'id' => $notifiable->getKey(), - 'hash' => hash_hmac( - 'sha256', - $notifiable->getEmailForVerification(), - $appKey - ), - ], - false - ) - ); - } - - public function createResetUrl(mixed $notifiable, string $token): string - { - if (! is_object($notifiable) || ! ($notifiable instanceof Customer)) { - throw new \InvalidArgumentException('Invalid notifiable provided.'); - } - - return url( - URL::temporarySignedRoute( - 'fo.auth.reset-password', - Date::now()->addMinutes(Config::integer('auth.reset.expire', 60)), - [ - 'token' => $token, - 'email' => $notifiable->getEmailForPasswordReset(), - ], - false - ) - ); - } } diff --git a/app/Http/Controllers/Fo/Auth/ForgotPasswordController.php b/app/Http/Controllers/Fo/Auth/ForgotPasswordController.php index 407b5c7a..6494a0c3 100644 --- a/app/Http/Controllers/Fo/Auth/ForgotPasswordController.php +++ b/app/Http/Controllers/Fo/Auth/ForgotPasswordController.php @@ -7,7 +7,6 @@ namespace App\Http\Controllers\Fo\Auth; use App\Contracts\Executor; use App\Cqs\Queries\Customers\GetCustomerByEmailQuery; use App\Cqs\Queries\Customers\GetCustomerByEmailQueryInput; -use App\Exceptions\CustomerNotEmployedException; use Domain\Models\ValueObjects\Email; use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Services\ShopperService; @@ -30,7 +29,6 @@ class ForgotPasswordController extends AuthController private readonly ShopperService $shopperService, ) { $this->middleware('guest:frontend'); - parent::__construct(); } public function showLinkRequestForm(): View @@ -47,16 +45,36 @@ class ForgotPasswordController extends AuthController new GetCustomerByEmailQueryInput(new Email($request->string('email')->toString())), ); - if ($shopperId instanceof ShopperId) { - $shopper = $this->shopperService->getShopperFor($shopperId); - if (! $shopper || ! $shopper->isActive()) { - throw new CustomerNotEmployedException(); - } + if (! $shopperId instanceof ShopperId) { + return $this->sendResponse($request->wantsJson()); + } + + $shopper = $this->shopperService->getShopperFor($shopperId); + if (! $shopper || ! $shopper->isActive()) { + return $this->sendResponse($request->wantsJson()); } 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/app/Http/Controllers/Fo/Auth/LoginController.php b/app/Http/Controllers/Fo/Auth/LoginController.php index 7e86456e..b4a7f233 100644 --- a/app/Http/Controllers/Fo/Auth/LoginController.php +++ b/app/Http/Controllers/Fo/Auth/LoginController.php @@ -14,17 +14,18 @@ use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Session; +use Infrastructure\Adapters\Services\AppCustomerAuthService; class LoginController extends AuthController { use AuthenticatesUsers; public function __construct( - private readonly ShopperService $shopperService + private readonly ShopperService $shopperService, + private readonly AppCustomerAuthService $authService, ) { $this->middleware('guest:frontend')->except('logout'); $this->middleware('auth:frontend')->only('logout'); - parent::__construct(); } protected function guard(): StatefulGuard @@ -45,7 +46,9 @@ class LoginController extends AuthController throw new CustomerNotEmployedException(); } - Session::flash('success', \trans('You are logged in!')); + if ($this->authService->hasVerifiedEmail($user)) { + Session::flash('success', \trans('You are logged in!')); + } } protected function loggedOut(Request $request): RedirectResponse diff --git a/app/Http/Controllers/Fo/Auth/RegisterController.php b/app/Http/Controllers/Fo/Auth/RegisterController.php index 3eae52c4..f232770f 100644 --- a/app/Http/Controllers/Fo/Auth/RegisterController.php +++ b/app/Http/Controllers/Fo/Auth/RegisterController.php @@ -6,15 +6,16 @@ namespace App\Http\Controllers\Fo\Auth; use App\Contracts\Executor; use App\Cqs\Actions\Customers\RegisterCustomer; +use App\Enums\RegisterCustomerStatus; use App\Http\Requests\Fo\Auth\RegisterRequest; use Illuminate\Contracts\View\View; +use Illuminate\Http\RedirectResponse; class RegisterController extends AuthController { public function __construct( private readonly Executor $executor, ) { - parent::__construct(); } public function showForm(): View @@ -22,10 +23,21 @@ class RegisterController extends AuthController return view('fo.auth.register'); } - public function submitForm(RegisterRequest $request, RegisterCustomer $action): View + public function submitForm(RegisterRequest $request, RegisterCustomer $action): View | RedirectResponse { - $this->executor->execute($action, $request->toRegisterCustomerInput()); + $output = $this->executor->execute($action, $request->toRegisterCustomerInput()); - return view('fo.auth.verify'); + return match ($output->status) { + RegisterCustomerStatus::SUCCESS => view('fo.auth.verify'), + RegisterCustomerStatus::EMPLOYEE_ALREADY_REGISTERED => back() + ->withInput($request->except(['password', 'password_confirmation'])) + ->withErrors(['matricule' => __('This employee already has an account.')]), + RegisterCustomerStatus::EMPLOYEE_INACTIVE => back() + ->withInput($request->except(['password', 'password_confirmation'])) + ->withErrors(['matricule' => __('This employee account is no longer active.')]), + RegisterCustomerStatus::LOCK_TIMEOUT => back() + ->withInput($request->except(['password', 'password_confirmation'])) + ->withErrors(['matricule' => __('Registration is already in progress. Please try again in a moment.')]), + }; } } diff --git a/app/Http/Controllers/Fo/Auth/ResetPasswordController.php b/app/Http/Controllers/Fo/Auth/ResetPasswordController.php index de0d7ebb..03c5cfd6 100644 --- a/app/Http/Controllers/Fo/Auth/ResetPasswordController.php +++ b/app/Http/Controllers/Fo/Auth/ResetPasswordController.php @@ -4,7 +4,14 @@ declare(strict_types=1); namespace App\Http\Controllers\Fo\Auth; +use App\Contracts\Executor; +use App\Cqs\Actions\Auth\ResetCustomerPassword; +use App\Cqs\Actions\Auth\ResetCustomerPasswordInput; +use App\Enums\ResetCustomerPasswordStatus; +use App\Exceptions\CustomerNotEmployedException; use App\Models\Customer; +use Illuminate\Auth\Events\PasswordReset; +use Illuminate\Contracts\Auth\CanResetPassword; use Illuminate\Contracts\Auth\PasswordBroker; use Illuminate\Contracts\Auth\StatefulGuard; use Illuminate\Contracts\View\View; @@ -13,16 +20,16 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Password; use Illuminate\Validation\ValidationException; -use Infrastructure\Adapters\Services\AppCustomerAuthService; +use Webmozart\Assert\Assert; class ResetPasswordController extends AuthController { use ResetsPasswords; public function __construct( - private readonly AppCustomerAuthService $authService + private readonly Executor $executor, + private readonly ResetCustomerPassword $resetCustomerPassword, ) { - parent::__construct(); } public function showResetForm(Request $request): View @@ -34,18 +41,34 @@ class ResetPasswordController extends AuthController ); } - protected function setUserPassword(Customer $customer, string $password): void + protected function resetPassword(CanResetPassword $user, string $password): void { - $result = $this->authService->resetPasswordFor($customer, $password); + Assert::isInstanceOf($user, Customer::class); - if ($result instanceof ValidationException) { - throw ValidationException::withMessages([ + $output = $this->executor->execute( + $this->resetCustomerPassword, + new ResetCustomerPasswordInput($user, $password), + ); + + match ($output->status) { + ResetCustomerPasswordStatus::NOT_EMPLOYED => throw new CustomerNotEmployedException(), + ResetCustomerPasswordStatus::INVALID_PASSWORD => throw ValidationException::withMessages([ 'error' => sprintf( '%s : %s', trans('validation.attributes.password'), - $result->getMessage() + $output->errorMessage ?? '' ), - ]); + ]), + ResetCustomerPasswordStatus::SUCCESS => $this->afterPasswordReset($user, $output->emailVerified), + }; + } + + private function afterPasswordReset(Customer $user, bool $emailVerified): void + { + event(new PasswordReset($user)); + + if ($emailVerified) { + $this->guard()->login($user); } } diff --git a/app/Http/Controllers/Fo/Auth/VerificationController.php b/app/Http/Controllers/Fo/Auth/VerificationController.php index 4c76f9d7..cc827fde 100644 --- a/app/Http/Controllers/Fo/Auth/VerificationController.php +++ b/app/Http/Controllers/Fo/Auth/VerificationController.php @@ -26,7 +26,6 @@ class VerificationController extends AuthController $this->middleware('is-employed'); $this->middleware('signed:relative')->only('verify'); $this->middleware('throttle:6,1')->only(['verify', 'resend']); - parent::__construct(); } public function show(Request $request): RedirectResponse | View diff --git a/app/Http/Controllers/Fo/Pages/ContactController.php b/app/Http/Controllers/Fo/Pages/ContactController.php index 28a4982b..827f8ac7 100644 --- a/app/Http/Controllers/Fo/Pages/ContactController.php +++ b/app/Http/Controllers/Fo/Pages/ContactController.php @@ -5,13 +5,14 @@ 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; use App\Cqs\Queries\Shops\GetShopQueryInput; use App\Http\Controllers\Controller; use App\Http\Requests\Fo\ContactFormRequest; -use App\Mail\SendContactMail; +use App\Jobs\SendContactMailJob; use Domain\Enums\StaticPageSlug; use Domain\Models\ValueObjects\Slug; use Illuminate\Contracts\View\View; @@ -19,7 +20,6 @@ use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Mail\Mailables\Address; use Illuminate\Support\Facades\Config; -use Illuminate\Support\Facades\Mail; class ContactController extends Controller { @@ -61,12 +61,18 @@ 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)); + SendContactMailJob::dispatch( + $contactData, + $this->mailToContact->address, + $this->mailToContact->name, + ); return back()->with(self::SESSION_STATUS_KEY, true); } diff --git a/app/Http/Controllers/Fo/Pages/ProductsController.php b/app/Http/Controllers/Fo/Pages/ProductsController.php index e185efff..64c55dcf 100644 --- a/app/Http/Controllers/Fo/Pages/ProductsController.php +++ b/app/Http/Controllers/Fo/Pages/ProductsController.php @@ -7,9 +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\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; @@ -46,12 +49,19 @@ class ProductsController extends Controller ]); } - public function view(Request $request, ProductWithPricingDto $productWithPricing): View - { - $this->authorize('viewPublished', $productWithPricing->product); + public function view( + Request $request, + ProductWithPricingDto $productWithPricing, + GetPublishedAssociatedProductsQuery $query, + ): View { + $this->authorize('viewPublished', $productWithPricing); - $associated = $productWithPricing->product->products; - $associated->loadMissing(['inco', 'validDiscount']); + $associated = $this->executor->execute( + $query, + new GetPublishedAssociatedProductsQueryInput( + slug: new Slug($productWithPricing->product->slug), + ), + ); $associatedProducts = FilteredProductResource::collection( $associated diff --git a/app/Http/Controllers/Fo/TunnelController.php b/app/Http/Controllers/Fo/TunnelController.php index 040187fb..ecea8e80 100644 --- a/app/Http/Controllers/Fo/TunnelController.php +++ b/app/Http/Controllers/Fo/TunnelController.php @@ -6,8 +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\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; use App\Cqs\Queries\Orders\GetBasketSummaryQuery; use App\Cqs\Queries\Orders\GetBasketSummaryQueryInput; use App\Cqs\Queries\Orders\GetOrderConfirmationQuery; @@ -16,23 +25,27 @@ use App\Cqs\Queries\Orders\GetPickTimeSlotQuery; 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\PlacePendingOrderStatus; +use App\Exceptions\CustomerNotEmployedException; use App\Http\Controllers\Controller; use App\Http\Requests\Fo\Orders\ConfirmOrderRequest; use App\Http\Requests\Fo\Orders\PickTimeSlotRequest; use App\Http\Requests\Fo\Orders\ValidateSummaryRequest; use App\Models\Order; use Domain\Enums\OrderTunnelStep; -use Domain\Exceptions\OrderTunnel\OrderLimitExceededException; -use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException; 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, ) { } @@ -94,18 +107,17 @@ class TunnelController extends Controller ): RedirectResponse { $this->authorize('canPickTimeSlot', OrderTunnelStep::class); - $matchedSlot = $this->executor->execute( + $output = $this->executor->execute( $action, $request->toApplyPickTimeSlotInput() ); - if ($matchedSlot === null) { - return back()->withErrors([ + return match ($output->status) { + ApplyPickTimeSlotStatus::MATCHED => to_route('fo.sales.confirmation'), + ApplyPickTimeSlotStatus::UNAVAILABLE => back()->withErrors([ 'timeslot' => trans('Invalid or unavailable time slot'), - ])->withInput(); - } - - return to_route('fo.sales.confirmation'); + ])->withInput(), + }; } // * -- STEP 3 -- * @@ -129,21 +141,105 @@ class TunnelController extends Controller public function confirmationSubmit( ConfirmOrderRequest $request, - FinalizeOrder $action + PlacePendingOrder $placePendingOrder, + ExportOrderToRegate $exportOrderToRegate, + ConfirmPlacedOrder $confirmPlacedOrder, + FailPendingOrder $failPendingOrder, ): RedirectResponse { $this->authorize('canFinalizeOrder', OrderTunnelStep::class); - try { - /** @var \Domain\Models\ValueObjects\OrderReference $orderReference */ - $orderReference = $this->executor->execute( - $action, - $request->toFinalizeOrderInput() - ); - } catch (WeeklyLimitExceededException | OrderLimitExceededException $e) { - return back()->with('message', $e->getMessage()); - } + $placeInput = $request->toPlacePendingOrderInput(); + $shopperId = $placeInput->shopperId ?? $this->authService->getCustomerAsMandatory()->getId(); - return to_route('fo.sales.confirmation.show-confirmed', (string) $orderReference); + 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 + ); + + 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($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', + __('Your order is already being processed. Please wait a moment and try again.') + ); + } + } + + 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 ?? ''), + ]), + PlacePendingOrderStatus::INACTIVE_SHOPPER => throw new CustomerNotEmployedException(), + PlacePendingOrderStatus::BASKET_PRICE_CHANGED, + PlacePendingOrderStatus::UNORDERABLE_PRODUCT => to_route('fo.sales.summary')->withErrors([ + 'basket' => trans($output->errorMessage ?? ''), + ]), + 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.') + ), + }; } // * -- CONFIRMATION -- * diff --git a/app/Http/Middleware/CustomerIsEmployed.php b/app/Http/Middleware/CustomerIsEmployed.php index 59661ffc..8988e65a 100644 --- a/app/Http/Middleware/CustomerIsEmployed.php +++ b/app/Http/Middleware/CustomerIsEmployed.php @@ -5,7 +5,6 @@ declare(strict_types=1); namespace App\Http\Middleware; use App\Exceptions\CustomerNotEmployedException; -use Closure; use Domain\Services\ShopperService; use Infrastructure\Adapters\Services\AppCustomerAuthService; use Symfony\Component\HttpFoundation\Response; @@ -24,7 +23,7 @@ class CustomerIsEmployed * @param \Illuminate\Http\Request $request * @param \Closure(\Illuminate\Http\Request):(\Illuminate\Http\Response) $next */ - public function handle($request, Closure $next): Response + public function handle($request, \Closure $next): Response { $customer = $this->authService->getCustomerAsMandatory(); $shopper = $this->shopperService->getShopperFor($customer->getId()); diff --git a/app/Http/Middleware/EnsureCustomerEmailIsVerified.php b/app/Http/Middleware/EnsureCustomerEmailIsVerified.php index 7628b97f..ef76451b 100644 --- a/app/Http/Middleware/EnsureCustomerEmailIsVerified.php +++ b/app/Http/Middleware/EnsureCustomerEmailIsVerified.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace App\Http\Middleware; -use Closure; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\URL; use Infrastructure\Adapters\Services\AppCustomerAuthService; @@ -34,7 +33,7 @@ class EnsureCustomerEmailIsVerified * @param \Illuminate\Http\Request $request * @param \Closure(\Illuminate\Http\Request):(\Illuminate\Http\Response) $next */ - public function handle($request, Closure $next, ?string $redirectToRoute = null): Response + public function handle($request, \Closure $next, ?string $redirectToRoute = null): Response { $customer = $this->authService->getCustomer(); diff --git a/app/Http/Middleware/HtmlSanitizer.php b/app/Http/Middleware/HtmlSanitizer.php index 56fa2da1..5f460ce4 100644 --- a/app/Http/Middleware/HtmlSanitizer.php +++ b/app/Http/Middleware/HtmlSanitizer.php @@ -4,14 +4,34 @@ declare(strict_types=1); namespace App\Http\Middleware; -use App\Lib\Helpers\ToolboxHelper; -use Illuminate\Http\Request; -use Illuminate\Http\UploadedFile; +use Illuminate\Foundation\Http\Middleware\TransformsRequest; +use Illuminate\Support\Str; use Mews\Purifier\Purifier; -use Symfony\Component\HttpFoundation\Response; -class HtmlSanitizer +/** + * Portable request sanitization middleware built on Laravel's `TransformsRequest`. + * + * Cleans query, form, and JSON bags while leaving uploaded files untouched: + * strips HTML tags by default, applies HTMLPurifier to listed rich-HTML fields, + * and skips fields matching `$except`. + */ +class HtmlSanitizer extends TransformsRequest { + /** + * The attributes that should not be sanitized. + * + * @var list + */ + protected array $except = [ + 'current_password', + 'password', + 'password_confirmation', + 'password_old', + ]; + + /** @var list */ + private array $richFields = []; + public function __construct( private readonly Purifier $purifierService ) { @@ -20,77 +40,78 @@ class HtmlSanitizer /** * Handle an incoming request. * - * @param \Closure(\Illuminate\Http\Request):(\Illuminate\Http\Response) $next + * @param \Illuminate\Http\Request $request + * @param \Closure(\Illuminate\Http\Request):(\Symfony\Component\HttpFoundation\Response) $next * @param string ...$params List of input names that should be sanitized with rich sanitization (allowing some HTML) */ - public function handle(Request $request, \Closure $next, string ...$params): Response + #[\Override] + public function handle($request, \Closure $next, string ...$params): mixed { - $inputs = $request->all(); + $this->richFields = array_values($params); - \array_walk($inputs, function (null | string | array | UploadedFile &$input, string $name) use ($params): void { - $this->cleanInput($input, $name, null, $params); - }); - $request->merge($inputs); + try { + return parent::handle($request, $next); + } finally { + $this->richFields = []; + } + } - return $next($request); + #[\Override] + protected function cleanValue($key, $value): mixed + { + if ($this->matchesPattern((string) $key, $this->except)) { + return $value; + } + + return parent::cleanValue($key, $value); + } + + #[\Override] + protected function transform($key, $value): mixed + { + if (! is_string($value)) { + return $value; + } + + if ($this->matchesPattern((string) $key, $this->richFields)) { + return $this->sanitizeRichInput($value); + } + + return strip_tags($value); } /** - * @param null|string|array|\Illuminate\Http\UploadedFile $input - * @param string[] $params + * @param list $patterns */ - private function cleanInput( - null | string | array | UploadedFile &$input, - string $name, - ?string $rootName, - array $params - ): void { - if (is_array($input)) { - array_walk_recursive( - $input, - function (null | string | array | UploadedFile &$nestedInput, string $nestedName) use ($name, $params): void { - $this->cleanInput($nestedInput, $nestedName, $name, $params); - } - ); + private function matchesPattern(string $key, array $patterns): bool + { + if ($patterns === []) { + return false; } - if (! is_string($input)) { - return; - } + $root = Str::before($key, '.'); + $leaf = Str::afterLast($key, '.'); - if ($this->shouldApplyRichSanitization($name, $rootName, $params)) { - $this->sanitizeRichInput($input); - - return; - } - - $input = strip_tags($input); + return Str::is($patterns, $key) + || Str::is($patterns, $root) + || Str::is($patterns, $leaf); } - /** - * @param array $params - */ - private function shouldApplyRichSanitization(string $name, ?string $rootName, array $params): bool + private function sanitizeRichInput(string $input): string { - return in_array($name, $params) || in_array($rootName ?? $name, $params); - } - - private function sanitizeRichInput(string &$input): void - { - $isJson = \json_decode($input, true); - if ($isJson && is_array($isJson)) { - \array_walk_recursive($isJson, function (string | array &$item): void { + $decoded = \json_decode($input, true); + if ($decoded && is_array($decoded)) { + \array_walk_recursive($decoded, function (mixed &$item): void { if (\is_string($item)) { $item = $this->purifyString($item); } }); - $input = json_encode($isJson, \JSON_THROW_ON_ERROR) ?: throw new \UnexpectedValueException('Failed to encode JSON after sanitization.'); - - return; + return json_encode($decoded, \JSON_THROW_ON_ERROR) + ?: throw new \UnexpectedValueException('Failed to encode JSON after sanitization.'); } - $input = $this->purifyString($input); + return $this->purifyString($input); } private function purifyString(string $input): string @@ -101,6 +122,20 @@ class HtmlSanitizer throw new \UnexpectedValueException('Purifier should return a string when input is a string.'); } - return ToolboxHelper::stripCkEditorSchemesOnMediaInputs($cleaned); + return $this->stripCkEditorSchemesOnMediaInputs($cleaned); + } + + /** + * Strip scheme (http) on oembed urls + * Only embed allowed are for MP4 self hosted videos right now + * + * https is force by ckeditor MediaElements which natively supports + * only cloud hosted medias (youtube, spotify etc..) + */ + private function stripCkEditorSchemesOnMediaInputs(string $input): string + { + return Str::of($input) + ->replaceMatches('/(?<=)/m', '') + ->toString(); } } diff --git a/app/Http/Middleware/SecureHeaders.php b/app/Http/Middleware/SecureHeaders.php index 59227c81..33f167cc 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,21 +99,22 @@ class SecureHeaders // * VITE DEV $viteDevSocket, $viteDevOrigin, + $s3PublicEndpoint, ]) . ';', "img-src 'self' data: blob: " . implode(' ', [ $viteDevOrigin, $openStreetMapTiles, + $s3PublicEndpoint, ]) . ' data:;', - 'child-src ' . implode(' ', []) . ';', + "worker-src 'self' blob:;", "object-src 'none';", + "child-src 'none';", "font-src 'self' data: " . \implode(' ', [ // * VITE DEV $viteDevOrigin, ]) . ';', - // ! Using CKEditor will must have unsafe-inline style + // ! Using CKEditor / inline UI components requires unsafe-inline style "style-src 'self' 'unsafe-inline' " . \implode(' ', [ - $jsdelivrUrl, - // * File Manager $jsdelivrUrl, // * VITE DEV $viteDevOrigin, @@ -110,12 +122,12 @@ class SecureHeaders // ! If you dont use ckeditor use this // "style-src 'self' 'nonce-$nonce';", - "script-src 'self' 'nonce-$nonce' 'strict-dynamic' " . \implode(' ', [ - 'https: blob:', + "script-src 'self' 'nonce-$nonce' 'strict-dynamic' " . \implode(' ', array_filter([ + 'https: blob:', $jsBo, // * VITE DEV $viteDevOrigin, - ]) . ';', + ])) . ';', ]; $response->headers->set( 'Content-Security-Policy', diff --git a/app/Http/Middleware/UserHasRole.php b/app/Http/Middleware/UserHasRole.php index 7617a58b..1c2534db 100644 --- a/app/Http/Middleware/UserHasRole.php +++ b/app/Http/Middleware/UserHasRole.php @@ -5,7 +5,6 @@ declare(strict_types=1); namespace App\Http\Middleware; use App\Models\User; -use Closure; use Domain\Enums\UserRole; use Illuminate\Auth\AuthenticationException; use Illuminate\Http\Request; @@ -20,7 +19,7 @@ class UserHasRole * @param \Closure(\Illuminate\Http\Request):(\Illuminate\Http\Response) $next * @param string ...$parameters The first parameter is the minimum required role (e.g., 'admin', 'editor', etc.) */ - public function handle(Request $request, Closure $next, string ...$parameters): Response + public function handle(Request $request, \Closure $next, string ...$parameters): Response { $parameter = $parameters[0] ?? ''; $guard = Auth::guard('backend'); diff --git a/app/Http/Requests/Basket/AddBasketRequest.php b/app/Http/Requests/Basket/AddBasketRequest.php index f6712ab7..d128d2a3 100644 --- a/app/Http/Requests/Basket/AddBasketRequest.php +++ b/app/Http/Requests/Basket/AddBasketRequest.php @@ -4,20 +4,35 @@ declare(strict_types=1); namespace App\Http\Requests\Basket; +use App\Contracts\Executor; 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; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; class AddBasketRequest extends FormRequest { + public function __construct( + private readonly Executor $executor, + private readonly GetProductWithPricingQuery $getProductWithPricingQuery, + ) { + } + public function authorize(): bool { - $product = Product::query() - ->where('id', $this->input('rowId')) - ->first(); + $rowId = $this->input('rowId'); + + if (! is_string($rowId) || ! UuidHelper::isValid($rowId)) { + return false; + } + + $product = $this->executor->execute( + $this->getProductWithPricingQuery, + new GetProductQueryInput($this->getProductId()), + ); return $product !== null && Gate::allows('addToBasket', $product); } @@ -33,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/Discounts/StoreDiscountRequest.php b/app/Http/Requests/Bo/Discounts/StoreDiscountRequest.php index a9e30202..9a34529c 100644 --- a/app/Http/Requests/Bo/Discounts/StoreDiscountRequest.php +++ b/app/Http/Requests/Bo/Discounts/StoreDiscountRequest.php @@ -5,11 +5,11 @@ declare(strict_types=1); namespace App\Http\Requests\Bo\Discounts; use App\Cqs\Actions\Discounts\CreateDiscountInput; +use App\Traits\Requests\ConvertsClientDatesToUtc; use Domain\Enums\DiscountType; use Domain\Models\ValueObjects\DatePeriod; use Domain\Models\ValueObjects\DiscountValue; use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Support\Facades\Date; use Illuminate\Validation\Rule; use Illuminate\Validation\Rules\Enum; use Infrastructure\Adapters\Services\AppAdminAuthService; @@ -18,8 +18,11 @@ use Money\Money; class StoreDiscountRequest extends FormRequest { + use ConvertsClientDatesToUtc; + public function __construct( - private readonly AppAdminAuthService $authService + private readonly AppAdminAuthService $authService, + private readonly Currency $currency, ) { } @@ -51,9 +54,14 @@ class StoreDiscountRequest extends FormRequest /** @return array */ public function getAssociatedProductsIds(): array { + $filtered = array_filter( + $this->array('associated_products'), + fn ($id) => is_string($id) || is_int($id) + ); + return array_map( fn ($id) => (string) $id, - $this->array('associated_products') + $filtered ); } @@ -82,7 +90,7 @@ class StoreDiscountRequest extends FormRequest return DiscountValue::fromAmount( new Money( intval($this->integer('value')), - resolve(Currency::class) + $this->currency, ) ); } @@ -131,36 +139,8 @@ class StoreDiscountRequest extends FormRequest #[\Override] protected function passedValidation() { - if ($this->filled('date_start')) { - $inputValue = Date::createFromFormat( - 'Y-m-d\TH:i', - $this->string('date_start')->value(), - $this->string('client_timezone')->value() - )?->setTimezone('UTC'); - - if (! $inputValue) { - throw new \UnexpectedValueException('Invalid date_start value'); - } - - $this->merge([ - 'date_start' => $inputValue->format('Y-m-d H:i:s'), - ]); - } - if ($this->filled('date_end')) { - $inputValue = Date::createFromFormat( - 'Y-m-d\TH:i', - $this->string('date_end')->value(), - $this->string('client_timezone')->value() - )?->setTimezone('UTC'); - - if (! $inputValue) { - throw new \UnexpectedValueException('Invalid date_end value'); - } - - $this->merge([ - 'date_end' => $inputValue->format('Y-m-d H:i:s'), - ]); - } + $this->mergeLocalDatetimeAsUtc('date_start'); + $this->mergeLocalDatetimeAsUtc('date_end'); } #[\Override] 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/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/Requests/Bo/Products/StoreProductRequest.php b/app/Http/Requests/Bo/Products/StoreProductRequest.php index 2efc596c..c97a0b52 100644 --- a/app/Http/Requests/Bo/Products/StoreProductRequest.php +++ b/app/Http/Requests/Bo/Products/StoreProductRequest.php @@ -5,7 +5,8 @@ declare(strict_types=1); namespace App\Http\Requests\Bo\Products; use App\Cqs\Actions\Products\CreateProductInput; -use App\Traits\Requests\HasPicture; +use App\Rules\FileExtensionMatchesMimeType; +use App\Traits\Requests\ConvertsClientDatesToUtc; use Carbon\CarbonImmutable; use Domain\Enums\ProductBrand; use Domain\Enums\SellUnit; @@ -13,18 +14,37 @@ use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Support\Facades\Date; +use Illuminate\Support\Arr; +use Illuminate\Validation\Rule; use Illuminate\Validation\Rules\Enum; use Infrastructure\Adapters\Services\AppAdminAuthService; use Money\Currency; use Money\Money; +use Webmozart\Assert\Assert; class StoreProductRequest extends FormRequest { - use HasPicture; + use ConvertsClientDatesToUtc; + + public const int MAX_FILE_SIZE_KB = 5120; + + public const int PICTURE_WIDTH = 200; + + public const int PICTURE_HEIGHT = 200; + + public const int PICTURE_LARGE_WIDTH = 500; + + public const int PICTURE_LARGE_HEIGHT = 500; + + /** @var list */ + public const array ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png']; + + /** @var list */ + public const array ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png']; public function __construct( - private readonly AppAdminAuthService $authService + private readonly AppAdminAuthService $authService, + private readonly Currency $currency, ) { } @@ -49,16 +69,21 @@ class StoreProductRequest extends FormRequest { return new Money( intval($this->integer('price')), - resolve(Currency::class) + $this->currency, ); } /** @return list */ public function getAssociatedProductsIds(): array { + $filtered = array_filter( + $this->array('associated_products'), + fn ($id) => is_string($id) || is_int($id) + ); + return array_values(array_map( fn ($id) => (string) $id, - $this->array('associated_products') + $filtered )); } @@ -82,108 +107,111 @@ class StoreProductRequest extends FormRequest orderableEnd: $this->filled('orderable_end') ? CarbonImmutable::parse($this->string('orderable_end')->value()) : null, star: $this->boolean('star'), status: $this->boolean('status'), - picture: $this->file('picture') ?? $this->input('picture'), + picture: $this->hasFile('picture') ? $this->file('picture') : null, pictureAlt: $this->filled('picture_alt') ? $this->string('picture_alt')->value() : null, pictureTitle: $this->filled('picture_title') ? $this->string('picture_title')->value() : null, - pictureLarge: $this->file('picture_large') ?? $this->input('picture_large'), + pictureLarge: $this->hasFile('picture_large') ? $this->file('picture_large') : null, pictureLargeAlt: $this->filled('picture_large_alt') ? $this->string('picture_large_alt')->value() : null, pictureLargeTitle: $this->filled('picture_large_title') ? $this->string('picture_large_title')->value() : null, - tags: $this->array('tags'), + tags: $this->getTags(), associatedProductsIds: $this->getAssociatedProductsIds(), ); } - /** @return array */ + /** @return array{ id: string, label: string }[] */ + protected function getTags(): array + { + $tags = $this->array('tags'); + + Assert::allIsArray($tags); + + return array_map( + static function (array $tag): array { + $id = Arr::get($tag, 'id'); + Assert::scalar($id); + + return [ + 'id' => (string) $id, + 'label' => Arr::string($tag, 'label'), + ]; + }, + $tags + ); + } + + /** @return array|string> */ public function rules(): array { - $maxWidth = 200; - $maxHeight = 200; - $maxWidthLarge = 500; - $maxHeightLarge = 500; + return [ + 'name' => ['required', 'string', 'min:3', 'max:255'], + 'brand' => ['required', 'string', new Enum(ProductBrand::class)], + 'short_description' => ['required', 'string', 'min:15', 'max:100'], + 'description' => ['required', 'string', 'min:15'], + 'price' => ['required', 'min:0', 'numeric'], + 'invoicing_unit' => ['required', new Enum(InvoicingUnit::class)], + 'stock' => ['required', 'integer', 'min:0'], + 'weight' => ['sometimes', 'nullable', 'numeric'], - return array_merge( - [ - 'name' => ['required', 'string', 'min:3', 'max:255'], - 'brand' => ['sometimes', 'nullable', 'string', 'min:3', 'max:255'], - 'short_description' => ['required', 'string', 'min:15', 'max:100'], - 'description' => ['required', 'string', 'min:15'], - 'price' => ['required', 'min:0', 'numeric'], - 'invoicing_unit' => ['required', new Enum(InvoicingUnit::class)], - 'stock' => ['required', 'integer', 'min:0'], - 'weight' => ['sometimes', 'nullable', 'numeric'], + 'orderable_start' => ['nullable', 'date_format:Y-m-d\TH:i'], + 'orderable_end' => ['nullable', 'date_format:Y-m-d\TH:i', 'after:orderable_start'], + 'client_timezone' => ['required', 'timezone'], - 'orderable_start' => ['nullable', 'date_format:Y-m-d\TH:i'], - 'orderable_end' => ['nullable', 'date_format:Y-m-d\TH:i', 'after:orderable_start'], - 'client_timezone' => ['required', 'timezone'], + 'range_id' => ['required', 'integer', 'exists:ranges,id'], - 'range_id' => ['required', 'integer', 'exists:ranges,id'], + 'tags' => ['present', 'array', 'min:0'], + 'tags.*.id' => ['required', 'exists:tags,id'], + 'tags.*.label' => ['required', 'string', 'min:2', 'max:45'], + 'star' => ['required', 'boolean'], + 'status' => ['required', 'boolean'], + 'weight_variable' => ['required', 'boolean'], - 'tags' => ['present', 'array'], - 'tags.*.id' => ['sometimes', 'exists:tags,id'], - 'tags.*.label' => ['required', 'string', 'min:2', 'max:45'], - 'star' => ['required', 'boolean'], - 'status' => ['required', 'boolean'], - 'weight_variable' => ['required', 'boolean'], + 'sell_unit' => ['required', new Enum(SellUnit::class)], + 'order_unit' => ['required', new Enum(OrderUnit::class)], + 'tax_rate' => ['required', new Enum(TaxRate::class)], - 'sell_unit' => ['required', new Enum(SellUnit::class)], - 'order_unit' => ['required', new Enum(OrderUnit::class)], - 'tax_rate' => ['required', new Enum(TaxRate::class)], - - 'associated_products' => ['present', 'array'], - 'associated_products.*' => ['string', 'exists:products,id'], + 'picture' => [ + Rule::imageFile() + ->extensions(self::ALLOWED_EXTENSIONS) + ->rules([ + 'mimetypes:' . implode(',', self::ALLOWED_MIME_TYPES), + new FileExtensionMatchesMimeType(), + ]) + ->max(self::MAX_FILE_SIZE_KB) + ->dimensions( + Rule::dimensions() + ->width(static::PICTURE_WIDTH) + ->height(static::PICTURE_HEIGHT) + ), ], - $this->pictureRules( - 'picture', - $maxWidth, - $maxHeight, - $maxWidth, - $maxHeight, - true - ), - $this->pictureRules( - 'picture_large', - $maxWidthLarge, - $maxHeightLarge, - $maxWidthLarge, - $maxHeightLarge, - true - ) - ); + 'picture_alt' => ['nullable', 'string', 'max:255'], + 'picture_title' => ['nullable', 'string', 'max:255'], + 'picture_large' => [ + Rule::imageFile() + ->extensions(self::ALLOWED_EXTENSIONS) + ->rules([ + 'mimetypes:' . implode(',', self::ALLOWED_MIME_TYPES), + new FileExtensionMatchesMimeType(), + ]) + ->max(self::MAX_FILE_SIZE_KB) + ->dimensions( + Rule::dimensions() + ->width(static::PICTURE_LARGE_WIDTH) + ->height(static::PICTURE_LARGE_HEIGHT) + ), + ], + 'picture_large_alt' => ['nullable', 'string', 'max:255'], + 'picture_large_title' => ['nullable', 'string', 'max:255'], + + 'associated_products' => ['present', 'array'], + 'associated_products.*' => ['string', 'exists:products,id'], + ]; } #[\Override] protected function passedValidation() { - if ($this->filled('orderable_start')) { - $inputValue = Date::createFromFormat( - 'Y-m-d\TH:i', - $this->string('orderable_start')->value(), - $this->string('client_timezone')->value() - )?->setTimezone('UTC'); - - if (! $inputValue) { - throw new \UnexpectedValueException('Invalid orderable_start value'); - } - - $this->merge([ - 'orderable_start' => $inputValue->format('Y-m-d H:i:s'), - ]); - } - if ($this->filled('orderable_end')) { - $inputValue = Date::createFromFormat( - 'Y-m-d\TH:i', - $this->string('orderable_end')->value(), - $this->string('client_timezone')->value() - )?->setTimezone('UTC'); - - if (! $inputValue) { - throw new \UnexpectedValueException('Invalid orderable_end value'); - } - - $this->merge([ - 'orderable_end' => $inputValue->format('Y-m-d H:i:s'), - ]); - } + $this->mergeLocalDatetimeAsUtc('orderable_start'); + $this->mergeLocalDatetimeAsUtc('orderable_end'); // * Convert to gram if ($this->filled('weight')) { diff --git a/app/Http/Requests/Bo/Products/UpdateProductRequest.php b/app/Http/Requests/Bo/Products/UpdateProductRequest.php index b49fa77d..5bc82318 100644 --- a/app/Http/Requests/Bo/Products/UpdateProductRequest.php +++ b/app/Http/Requests/Bo/Products/UpdateProductRequest.php @@ -5,20 +5,20 @@ declare(strict_types=1); namespace App\Http\Requests\Bo\Products; use App\Cqs\Actions\Products\UpdateProductInput; -use App\Models\Product; use Carbon\CarbonImmutable; 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; class UpdateProductRequest extends StoreProductRequest { - public function toUpdateProductInput(Product $product): UpdateProductInput + public function toUpdateProductInput(ProductId $productId): UpdateProductInput { return new UpdateProductInput( - product: $product, + productId: $productId, name: $this->string('name')->value(), shortDescription: $this->string('short_description')->value(), description: $this->string('description')->value(), @@ -36,13 +36,13 @@ class UpdateProductRequest extends StoreProductRequest orderableEnd: $this->filled('orderable_end') ? CarbonImmutable::parse($this->string('orderable_end')->value()) : null, star: $this->boolean('star'), status: $this->boolean('status'), - picture: $this->file('picture') ?? $this->input('picture'), + picture: $this->hasFile('picture') ? $this->file('picture') : null, pictureAlt: $this->filled('picture_alt') ? $this->string('picture_alt')->value() : null, pictureTitle: $this->filled('picture_title') ? $this->string('picture_title')->value() : null, - pictureLarge: $this->file('picture_large') ?? $this->input('picture_large'), + pictureLarge: $this->hasFile('picture_large') ? $this->file('picture_large') : null, pictureLargeAlt: $this->filled('picture_large_alt') ? $this->string('picture_large_alt')->value() : null, pictureLargeTitle: $this->filled('picture_large_title') ? $this->string('picture_large_title')->value() : null, - tags: $this->array('tags'), + tags: $this->getTags(), associatedProductsIds: $this->getAssociatedProductsIds(), ); } diff --git a/app/Http/Requests/Bo/Ranges/StoreRangeRequest.php b/app/Http/Requests/Bo/Ranges/StoreRangeRequest.php index e91a52b4..b013c0ba 100644 --- a/app/Http/Requests/Bo/Ranges/StoreRangeRequest.php +++ b/app/Http/Requests/Bo/Ranges/StoreRangeRequest.php @@ -5,17 +5,28 @@ declare(strict_types=1); namespace App\Http\Requests\Bo\Ranges; use App\Cqs\Actions\Ranges\CreateRangeInput; -use App\Traits\Requests\HasPicture; +use App\Rules\FileExtensionMatchesMimeType; use Domain\Models\ValueObjects\PictureMetadata; use Illuminate\Foundation\Http\FormRequest; +use Illuminate\Validation\Rule; use Infrastructure\Adapters\Services\AppAdminAuthService; class StoreRangeRequest extends FormRequest { - use HasPicture; + public const int MAX_FILE_SIZE_KB = 5120; + + public const int PICTURE_WIDTH = 500; + + public const int PICTURE_HEIGHT = 500; + + /** @var list */ + public const array ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png']; + + /** @var list */ + public const array ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png']; public function __construct( - private readonly AppAdminAuthService $authService + private readonly AppAdminAuthService $authService, ) { } @@ -32,29 +43,30 @@ class StoreRangeRequest extends FormRequest ]); } - /** @return array */ + /** @return array|string> */ public function rules(): array { - $maxWidth = 500; - $maxHeight = 500; - - return array_merge( - [ - 'name' => ['required', 'string', 'min:2', 'max:45'], - 'description' => ['nullable', 'string', 'min:2'], - 'picture_alt' => ['required_with:picture', 'string', 'min:4', 'max:75'], - 'picture_title' => ['required_with:picture', 'string', 'min:4', 'max:75'], - 'status' => ['present', 'boolean:strict'], + return [ + 'name' => ['required', 'string', 'min:2', 'max:45'], + 'description' => ['nullable', 'string', 'min:2'], + 'picture_alt' => ['required_with:picture', 'string', 'min:4', 'max:75'], + 'picture_title' => ['required_with:picture', 'string', 'min:4', 'max:75'], + 'picture' => [ + Rule::imageFile() + ->extensions(self::ALLOWED_EXTENSIONS) + ->rules([ + 'mimetypes:' . implode(',', self::ALLOWED_MIME_TYPES), + new FileExtensionMatchesMimeType(), + ]) + ->max(self::MAX_FILE_SIZE_KB) + ->dimensions( + Rule::dimensions() + ->width(static::PICTURE_WIDTH) + ->height(static::PICTURE_HEIGHT) + ), ], - $this->pictureRules( - 'picture', - $maxWidth, - $maxHeight, - $maxWidth, - $maxHeight, - true - ) - ); + 'status' => ['present', 'boolean:strict'], + ]; } #[\Override] @@ -78,7 +90,7 @@ class StoreRangeRequest extends FormRequest return new CreateRangeInput( name: $this->string('name')->value(), description: $this->filled('description') ? $this->string('description')->value() : null, - picture: $this->file('picture'), + picture: $this->hasFile('picture') ? $this->file('picture') : null, pictureMetadata: new PictureMetadata( alt: $pictureAlt, title: $pictureTitle, diff --git a/app/Http/Requests/Bo/Ranges/UpdateRangeRequest.php b/app/Http/Requests/Bo/Ranges/UpdateRangeRequest.php index 9369d3ba..66265917 100644 --- a/app/Http/Requests/Bo/Ranges/UpdateRangeRequest.php +++ b/app/Http/Requests/Bo/Ranges/UpdateRangeRequest.php @@ -19,7 +19,7 @@ class UpdateRangeRequest extends StoreRangeRequest range: $range, name: $this->string('name')->value(), description: $this->filled('description') ? $this->string('description')->value() : null, - picture: $this->file('picture'), + picture: $this->hasFile('picture') ? $this->file('picture') : null, pictureMetadata: new PictureMetadata( alt: $pictureAlt, title: $pictureTitle, 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/Bo/Shops/UpdateShopPickupExceptionsRequest.php b/app/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequest.php index 832e8c46..060c7aa4 100644 --- a/app/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequest.php +++ b/app/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequest.php @@ -6,13 +6,16 @@ namespace App\Http\Requests\Bo\Shops; use App\Cqs\Actions\Shops\UpdateShopPickupExceptionsInput; use App\Models\Shop; +use App\Traits\Requests\ConvertsClientDatesToUtc; use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Support\Facades\Date; use Illuminate\Support\Str; use Infrastructure\Adapters\Services\AppAdminAuthService; +use Webmozart\Assert\Assert; class UpdateShopPickupExceptionsRequest extends FormRequest { + use ConvertsClientDatesToUtc; + public function __construct( private readonly AppAdminAuthService $authService ) { @@ -73,14 +76,8 @@ class UpdateShopPickupExceptionsRequest extends FormRequest $timezone = $this->string('client_timezone')->value(); foreach ($deadlines as $id => $deadline) { - if (! empty($deadline)) { - $deadlines[$id] = Date::createFromFormat( - 'Y-m-d\TH:i', - $deadline, - $timezone - ) - ?->setTimezone('UTC') - ?->format('Y-m-d H:i:s'); + if (is_string($deadline) && $deadline !== '') { + $deadlines[$id] = $this->convertLocalDatetimeToUtc($deadline, $timezone); } } @@ -112,12 +109,16 @@ class UpdateShopPickupExceptionsRequest extends FormRequest $replacementDates = $this->array('replacement_date'); $orderDeadlines = $this->array('order_deadline_at'); + Assert::allScalar($pickupExceptions); + Assert::allNullOrString($replacementDates); + Assert::allNullOrString($orderDeadlines); + $syncData = []; foreach ($pickupExceptions as $exceptionId) { $exceptionId = (string) $exceptionId; - $replacementDate = ! empty($replacementDates[$exceptionId]) ? (string) $replacementDates[$exceptionId] : null; - $orderDeadline = ! empty($orderDeadlines[$exceptionId]) ? (string) $orderDeadlines[$exceptionId] : null; + $replacementDate = $this->getValue($replacementDates, $exceptionId); + $orderDeadline = $this->getValue($orderDeadlines, $exceptionId); $syncData[$exceptionId] = [ 'replacement_date' => $replacementDate, @@ -127,4 +128,10 @@ class UpdateShopPickupExceptionsRequest extends FormRequest return $syncData; } + + /** @param array $array */ + private function getValue(array $array, string $key): ?string + { + return ! empty($array[$key]) ? $array[$key] : null; + } } diff --git a/app/Http/Requests/Bo/Slides/StoreSlideRequest.php b/app/Http/Requests/Bo/Slides/StoreSlideRequest.php index 8ae5461f..29c870d8 100644 --- a/app/Http/Requests/Bo/Slides/StoreSlideRequest.php +++ b/app/Http/Requests/Bo/Slides/StoreSlideRequest.php @@ -5,19 +5,32 @@ declare(strict_types=1); namespace App\Http\Requests\Bo\Slides; use App\Cqs\Actions\Slides\CreateSlideInput; -use App\Traits\Requests\HasPicture; +use App\Rules\FileExtensionMatchesMimeType; +use App\Traits\Requests\ConvertsClientDatesToUtc; use Domain\Models\ValueObjects\DatePeriod; use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Http\UploadedFile; -use Illuminate\Support\Facades\Date; +use Illuminate\Support\Stringable; +use Illuminate\Validation\Rule; use Infrastructure\Adapters\Services\AppAdminAuthService; class StoreSlideRequest extends FormRequest { - use HasPicture; + use ConvertsClientDatesToUtc; + + public const int MAX_FILE_SIZE_KB = 5120; + + public const int PICTURE_WIDTH = 1440; + + public const int PICTURE_HEIGHT = 960; + + /** @var list */ + public const array ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png']; + + /** @var list */ + public const array ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png']; public function __construct( - private readonly AppAdminAuthService $authService + private readonly AppAdminAuthService $authService, ) { } @@ -26,18 +39,6 @@ class StoreSlideRequest extends FormRequest return $this->authService->check(); } - public function resolvePicture(): UploadedFile | string | null - { - $file = $this->file('picture'); - if ($file instanceof UploadedFile) { - return $file; - } - - return $this->has('picture') && is_string($this->input('picture')) - ? $this->input('picture') - : null; - } - public function toDatePeriod(): DatePeriod { return new DatePeriod( @@ -51,7 +52,7 @@ class StoreSlideRequest extends FormRequest return new CreateSlideInput( title: $this->string('title')->value(), text: $this->filled('text') ? $this->string('text')->value() : null, - picture: $this->resolvePicture(), + picture: $this->hasFile('picture') ? $this->file('picture') : null, pictureAlt: $this->filled('picture_alt') ? $this->string('picture_alt')->value() : null, pictureTitle: $this->filled('picture_title') ? $this->string('picture_title')->value() : null, link: $this->filled('link') ? $this->string('link')->value() : null, @@ -65,8 +66,12 @@ class StoreSlideRequest extends FormRequest #[\Override] protected function prepareForValidation(): void { - $text = $this->input('text'); - if (is_string($text) && trim(html_entity_decode(strip_tags($text), ENT_QUOTES | ENT_HTML5, 'UTF-8')) === '') { + $text = $this->string('text')->value(); + $trimmedText = $this->string('text') + ->pipe(fn (Stringable $text) => html_entity_decode(strip_tags((string) $text), ENT_QUOTES | ENT_HTML5, 'UTF-8')) + ->trim() + ->toString(); + if ($trimmedText === '') { $text = null; } @@ -77,62 +82,43 @@ class StoreSlideRequest extends FormRequest ]); } - /** @return array */ + /** @return array|string> */ public function rules(): array { - $maxWidth = 1440; - $maxHeight = 960; - - return array_merge( - [ - 'title' => ['required', 'string', 'min:4', 'max:75'], - 'picture_alt' => ['required_with:picture', 'string', 'min:4', 'max:75'], - 'picture_title' => ['required_with:picture', 'string', 'min:4', 'max:75'], - 'text' => ['nullable', 'required_without:picture', 'string', 'min:4'], - 'link' => ['nullable', 'url:https', 'max:255'], - 'link_label' => ['nullable', 'string', 'min:5', 'max:255'], - 'link_new_tab' => ['present', 'boolean:strict'], - 'connected' => ['present', 'boolean:strict'], - 'date_start' => ['nullable', 'date_format:Y-m-d\TH:i'], - 'date_end' => ['nullable', 'date_format:Y-m-d\TH:i', 'after:date_start'], - 'client_timezone' => ['required', 'timezone'], + return [ + 'title' => ['required', 'string', 'min:4', 'max:75'], + 'picture_alt' => ['required_with:picture', 'string', 'min:4', 'max:75'], + 'picture_title' => ['required_with:picture', 'string', 'min:4', 'max:75'], + 'picture' => [ + Rule::imageFile() + ->extensions(self::ALLOWED_EXTENSIONS) + ->rules([ + 'mimetypes:' . implode(',', self::ALLOWED_MIME_TYPES), + new FileExtensionMatchesMimeType(), + ]) + ->max(self::MAX_FILE_SIZE_KB) + ->dimensions( + Rule::dimensions() + ->width(static::PICTURE_WIDTH) + ->height(static::PICTURE_HEIGHT) + ), ], - $this->pictureRules( - 'picture', - $maxWidth, - $maxHeight, - $maxWidth, - $maxHeight, - true - ) - ); + 'text' => ['nullable', 'required_without:picture', 'string', 'min:4'], + 'link' => ['nullable', 'url:https', 'max:255'], + 'link_label' => ['nullable', 'string', 'min:5', 'max:255'], + 'link_new_tab' => ['present', 'boolean:strict'], + 'connected' => ['present', 'boolean:strict'], + 'date_start' => ['nullable', 'date_format:Y-m-d\TH:i'], + 'date_end' => ['nullable', 'date_format:Y-m-d\TH:i', 'after:date_start'], + 'client_timezone' => ['required', 'timezone'], + ]; } #[\Override] - protected function passedValidation() + protected function passedValidation(): void { - if ($this->filled('date_start')) { - $inputValue = Date::createFromFormat( - 'Y-m-d\TH:i', - $this->string('date_start')->value(), - $this->string('client_timezone')->value() - )?->setTimezone('UTC'); - - $this->merge([ - 'date_start' => $inputValue?->format('Y-m-d H:i:s'), - ]); - } - if ($this->filled('date_end')) { - $inputValue = Date::createFromFormat( - 'Y-m-d\TH:i', - $this->string('date_end')->value(), - $this->string('client_timezone')->value() - )?->setTimezone('UTC'); - - $this->merge([ - 'date_end' => $inputValue?->format('Y-m-d H:i:s'), - ]); - } + $this->mergeLocalDatetimeAsUtc('date_start'); + $this->mergeLocalDatetimeAsUtc('date_end'); } #[\Override] diff --git a/app/Http/Requests/Bo/Slides/UpdateSlideRequest.php b/app/Http/Requests/Bo/Slides/UpdateSlideRequest.php index 13817bbe..b1d24401 100644 --- a/app/Http/Requests/Bo/Slides/UpdateSlideRequest.php +++ b/app/Http/Requests/Bo/Slides/UpdateSlideRequest.php @@ -15,7 +15,7 @@ class UpdateSlideRequest extends StoreSlideRequest slide: $slide, title: $this->string('title')->value(), text: $this->filled('text') ? $this->string('text')->value() : null, - picture: $this->resolvePicture(), + picture: $this->hasFile('picture') ? $this->file('picture') : null, pictureAlt: $this->filled('picture_alt') ? $this->string('picture_alt')->value() : null, pictureTitle: $this->filled('picture_title') ? $this->string('picture_title')->value() : null, link: $this->filled('link') ? $this->string('link')->value() : null, diff --git a/app/Http/Requests/Fo/Ajax/FilterProductsRequest.php b/app/Http/Requests/Fo/Ajax/FilterProductsRequest.php index 117a13c3..8874a89b 100644 --- a/app/Http/Requests/Fo/Ajax/FilterProductsRequest.php +++ b/app/Http/Requests/Fo/Ajax/FilterProductsRequest.php @@ -16,15 +16,23 @@ class FilterProductsRequest extends FormRequest { public function toGetFoFilteredProductsQueryInput(): GetFoFilteredProductsQueryInput { + $ranges = $this->filterScalarArray($this->array('ranges')); + $tags = $this->filterScalarArray($this->array('tags')); + $brands = $this->filterScalarArray($this->array('brands')); + + $ranges = array_map(fn ($range) => intval($range), $ranges); + $tags = array_map(fn ($tag) => intval($tag), $tags); + $brands = array_map(fn ($brand) => strval($brand), $brands); + return new GetFoFilteredProductsQueryInput( pagination: Pagination::ofPage( new PageNumber($this->integer('page', 1)), new PageSize($this->integer('perPage', 6)), ), search: $this->filled('search') ? $this->string('search')->value() : '', - ranges: array_map('intval', $this->array('ranges')), - tags: array_map('intval', $this->array('tags')), - brands: array_map('strval', $this->array('brands')), + ranges: $ranges, + tags: $tags, + brands: $brands, isDiscounted: $this->boolean('isDiscounted'), ); } @@ -72,4 +80,16 @@ class FilterProductsRequest extends FormRequest 'perPage' => trans('validation.custom.attributes.per_page'), ]; } + + /** + * @param array $array + * @return array + */ + private function filterScalarArray(array $array): array + { + return array_filter( + $array, + fn ($item) => is_string($item) || is_int($item), + ); + } } diff --git a/app/Http/Requests/Fo/Auth/RegisterRequest.php b/app/Http/Requests/Fo/Auth/RegisterRequest.php index 78b02fff..445ad711 100644 --- a/app/Http/Requests/Fo/Auth/RegisterRequest.php +++ b/app/Http/Requests/Fo/Auth/RegisterRequest.php @@ -6,11 +6,14 @@ namespace App\Http\Requests\Fo\Auth; use App\Cqs\Actions\Customers\RegisterCustomerInput; use App\Rules\Adult; +use App\Rules\Matricule as MatriculeRule; use Domain\Models\ValueObjects\Code; use Domain\Models\ValueObjects\Email; use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\PhoneNumber; +use Illuminate\Database\Query\Builder; use Illuminate\Foundation\Http\FormRequest; +use Illuminate\Support\Facades\Date; use Illuminate\Validation\Rule; use Illuminate\Validation\Rules\Password; use Infrastructure\Adapters\Services\AppCustomerAuthService; @@ -65,12 +68,40 @@ class RegisterRequest extends FormRequest /** @return array */ public function rules(): array { + $today = Date::now('Europe/Paris')->format('Y-m-d'); + $onlyActiveEmployee = static function (Builder $query) use ($today): void { + $query + ->whereNull('customer_id') + ->where(static fn (Builder $q): Builder => $q->whereNull('start_date')->orWhere('start_date', '<=', $today)) + ->where(static fn (Builder $q): Builder => $q->whereNull('end_date')->orWhere('end_date', '>', $today)); + }; + return [ - 'matricule' => ['required', 'exists:employees,matricule'], - 'code' => [ + 'matricule' => [ + 'bail', 'required', + 'string', + new MatriculeRule(), + Rule::exists('employees', 'matricule')->where($onlyActiveEmployee), + ], + 'code' => [ + 'bail', + 'required', + 'string', + static function (string $attribute, mixed $value, \Closure $fail): void { + if (! is_string($value)) { + return; + } + + try { + new Code($value); + } catch (\DomainException) { + $fail(trans('validation.regex', ['attribute' => $attribute])); + } + }, Rule::exists('employees', 'code') - ->where('matricule', $this->string('matricule')->value()), + ->where('matricule', $this->string('matricule')->value()) + ->where($onlyActiveEmployee), ], 'lastname' => ['required', 'string', 'max:255'], 'firstname' => ['required', 'string', 'max:255'], diff --git a/app/Http/Requests/Fo/ContactFormRequest.php b/app/Http/Requests/Fo/ContactFormRequest.php index d7fcb469..2ebe6ed2 100644 --- a/app/Http/Requests/Fo/ContactFormRequest.php +++ b/app/Http/Requests/Fo/ContactFormRequest.php @@ -4,14 +4,23 @@ declare(strict_types=1); namespace App\Http\Requests\Fo; -use Domain\Models\ValueObjects\AttachedFile; -use Domain\Models\ValueObjects\ContactFormData; +use App\Cqs\Actions\Contact\SubmitContactFormInput; +use App\Rules\FileExtensionMatchesMimeType; +use Domain\Models\ValueObjects\OrderReference; use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Support\Facades\Storage; +use Illuminate\Http\UploadedFile; use Illuminate\Validation\Rule; class ContactFormRequest extends FormRequest { + public const int MAX_FILE_SIZE_KB = 5120; + + /** @var list */ + public const array ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png', 'pdf']; + + /** @var list */ + public const array ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png', 'application/pdf']; + /** @return array */ public function rules(): array { @@ -26,13 +35,29 @@ class ContactFormRequest extends FormRequest ->validateMxRecord(), ], 'subject' => ['required', 'string', 'min:2'], - 'order_ref' => ['nullable', 'string', 'regex:/^[0-9]+$/'], + 'order_ref' => [ + 'nullable', + 'string', + static function (string $attribute, mixed $value, \Closure $fail): void { + if (! is_string($value) || $value === '') { + return; + } + + try { + OrderReference::fromString($value); + } catch (\DomainException) { + $fail(trans('validation.regex', ['attribute' => $attribute])); + } + }, + ], 'message' => ['required', 'string', 'min:20', 'max:1900'], 'file' => [ 'nullable', Rule::file() - ->max(5120) - ->types(['jpg', 'jpeg', 'png', 'pdf']), + ->types([...self::ALLOWED_EXTENSIONS, ...self::ALLOWED_MIME_TYPES]) + ->extensions(self::ALLOWED_EXTENSIONS) + ->rules([new FileExtensionMatchesMimeType()]) + ->max(self::MAX_FILE_SIZE_KB), ], 'ok_cgv' => ['accepted'], ]; @@ -49,34 +74,20 @@ class ContactFormRequest extends FormRequest ]; } - public function toValueObject(): ContactFormData + public function toSubmitContactFormInput(): SubmitContactFormInput { - $attachedFile = null; + $file = $this->file('file'); + $uploadedFile = $file instanceof UploadedFile ? $file : null; + $orderRef = $this->input('order_ref'); - if ($this->hasFile('file') && $this->file('file')->isValid()) { - $uploadedFile = $this->file('file'); - $storedPath = $uploadedFile->store('contact-attachments', 'private'); - - if ($storedPath !== false) { - $fullPath = Storage::disk('private')->path($storedPath); - - $attachedFile = new AttachedFile( - path: $fullPath, - originalName: $uploadedFile->getClientOriginalName(), - mimeType: $uploadedFile->getMimeType() ?? 'application/octet-stream', - ); - } - } - - return new ContactFormData( + return new SubmitContactFormInput( lastName: $this->string('last_name')->value(), firstName: $this->string('first_name')->value(), email: $this->string('email')->value(), subject: $this->string('subject')->value(), message: $this->string('message')->value(), - orderRef: empty($this->input('order_ref')) ? - null : $this->string('order_ref')->value(), - file: $attachedFile, + orderRef: empty($orderRef) ? null : OrderReference::fromString($this->string('order_ref')->value()), + file: $uploadedFile, ); } 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/Http/Requests/Fo/Orders/PickTimeSlotRequest.php b/app/Http/Requests/Fo/Orders/PickTimeSlotRequest.php index 47ec13b5..bd935bdf 100644 --- a/app/Http/Requests/Fo/Orders/PickTimeSlotRequest.php +++ b/app/Http/Requests/Fo/Orders/PickTimeSlotRequest.php @@ -9,7 +9,6 @@ use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException; use Domain\Ports\Repositories\ShopperRepository; -use Domain\Services\BasketService; use Domain\Services\OrderTunnelService; use Illuminate\Foundation\Http\FormRequest; use Infrastructure\Adapters\Services\AppCustomerAuthService; @@ -18,7 +17,6 @@ class PickTimeSlotRequest extends FormRequest { public function __construct( private readonly AppCustomerAuthService $authService, - private readonly BasketService $basketService, private readonly ShopperRepository $shopperRepository, private readonly OrderTunnelService $orderTunnelService ) { @@ -42,9 +40,10 @@ class PickTimeSlotRequest extends FormRequest #[\Override] protected function prepareForValidation(): void { + $basket = $this->orderTunnelService->getBuilderFromBasketOrFail()->getBasket(); + $this->merge([ - 'basketTotal' => $this->basketService - ->getBasket() + 'basketTotal' => $basket ->totalTaxIncluded() ->getAmount(), ]); @@ -66,16 +65,18 @@ class PickTimeSlotRequest extends FormRequest 'basketTotal' => [ function (string $_, mixed $__, \Closure $fail) { try { - $customer = $this->authService->getCustomerAsMandatory(); - $shopper = $this->shopperRepository->getByIdOrFail($customer->getId()); - $atDate = $this->getTimeslot(); - $basket = $this->basketService->getBasket(); + $atDate = $this->getTimeslot(); + $customer = $this->authService->getCustomerAsMandatory(); + $shopper = $this->shopperRepository->getByIdOrFail($customer->getId()); + $basket = $this->orderTunnelService->getBuilderFromBasketOrFail()->getBasket(); $this->orderTunnelService->assertBasketWeeklyAmountWithinLimitFor( shopper: $shopper, withBasket: $basket, atDate: $atDate ); + } catch (\InvalidArgumentException) { + return; } catch (WeeklyLimitExceededException) { $fail(trans('You will reach the maximum weekly order limit with this basket.')); } 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/Http/Resources/Fo/Ajax/BasketProductResource.php b/app/Http/Resources/Fo/Ajax/BasketProductResource.php index 21ae3f89..c5d978ce 100644 --- a/app/Http/Resources/Fo/Ajax/BasketProductResource.php +++ b/app/Http/Resources/Fo/Ajax/BasketProductResource.php @@ -4,15 +4,15 @@ declare(strict_types=1); namespace App\Http\Resources\Fo\Ajax; +use App\Dto\BasketProductDto; use App\Lib\Helpers\MoneyHelper; -use Domain\Models\ValueObjects\BasketProduct; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Support\Facades\Gate; class BasketProductResource extends JsonResource { - public function __construct(private readonly BasketProduct $basketProduct) + public function __construct(private readonly BasketProductDto $item) { } @@ -20,36 +20,31 @@ class BasketProductResource extends JsonResource #[\Override] public function toArray(Request $request): array { + $product = $this->item->product; + $canViewPrices = Gate::allows('viewPrices', $this->item); + return [ - 'id' => $this->basketProduct->id->value, - 'name' => $this->basketProduct->name, - 'qty' => $this->basketProduct->qty, + 'id' => $product->id->value, + 'name' => $product->name, + 'qty' => $product->qty, - 'unitPriceHt' => Gate::allows('viewPrices', $this->basketProduct) ? - MoneyHelper::serialized($this->basketProduct->unitPriceHt()) : null, - 'discountTotal' => Gate::allows('viewPrices', $this->basketProduct) ? - MoneyHelper::serialized($this->basketProduct->discountTotal()) : null, - 'taxTotal' => Gate::allows('viewPrices', $this->basketProduct) ? - MoneyHelper::serialized($this->basketProduct->taxTotal()) : null, - 'subtotalHt' => Gate::allows('viewPrices', $this->basketProduct) ? - MoneyHelper::serialized($this->basketProduct->subtotalHt()) : null, - 'totalTtc' => Gate::allows('viewPrices', $this->basketProduct) ? - MoneyHelper::serialized($this->basketProduct->totalTtc()) : null, + 'unitPriceHt' => $canViewPrices ? MoneyHelper::serialized($product->unitPriceHt()) : null, + 'discountTotal' => $canViewPrices ? MoneyHelper::serialized($product->discountTotal()) : null, + 'taxTotal' => $canViewPrices ? MoneyHelper::serialized($product->taxTotal()) : null, + 'subtotalHt' => $canViewPrices ? MoneyHelper::serialized($product->subtotalHt()) : null, + 'totalTtc' => $canViewPrices ? MoneyHelper::serialized($product->totalTtc()) : null, - 'discountedPriceTtc' => Gate::allows('viewPrices', $this->basketProduct) ? - MoneyHelper::serialized($this->basketProduct->unitTtc()) : null, - 'priceKgTtc' => Gate::allows('viewPrices', $this->basketProduct) ? - MoneyHelper::serialized($this->basketProduct->priceKgTtc) : null, + 'discountedPriceTtc' => $canViewPrices ? MoneyHelper::serialized($product->unitTtc()) : null, + 'priceKgTtc' => $canViewPrices ? MoneyHelper::serialized($product->priceKgTtc) : null, - 'slug' => $this->basketProduct->slug, - 'picture' => $this->basketProduct->picture ? - url($this->basketProduct->picture) : null, - 'description' => $this->basketProduct->description, - 'weight_variable' => $this->basketProduct->weightVariable, - 'discountRate' => $this->basketProduct->discountRate->ratio(), + 'slug' => $product->slug, + 'picture' => $product->picture ? publicS3Asset($product->picture) : null, + 'description' => $product->description, + 'weight_variable' => $product->weightVariable, + 'discountRate' => $product->discountRate->ratio(), - 'taxRate' => $this->basketProduct->taxRate->percent(), - 'weightGrams' => $this->basketProduct->weightGrams, + 'taxRate' => $product->taxRate->percent(), + 'weightGrams' => $product->weightGrams, ]; } } diff --git a/app/Http/Resources/Fo/Ajax/BasketResource.php b/app/Http/Resources/Fo/Ajax/BasketResource.php index b40d0921..1b4ca844 100644 --- a/app/Http/Resources/Fo/Ajax/BasketResource.php +++ b/app/Http/Resources/Fo/Ajax/BasketResource.php @@ -4,15 +4,15 @@ declare(strict_types=1); namespace App\Http\Resources\Fo\Ajax; +use App\Dto\BasketDto; use App\Lib\Helpers\MoneyHelper; -use Domain\Models\Entities\Basket; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Support\Facades\Gate; class BasketResource extends JsonResource { - public function __construct(private readonly Basket $basket) + public function __construct(private readonly BasketDto $basket) { } @@ -20,19 +20,17 @@ class BasketResource extends JsonResource #[\Override] public function toArray(Request $request): array { - return [ - 'items' => BasketProductResource::collection(array_values($this->basket->items())), + $canViewTotal = Gate::allows('viewTotal', $this->basket); - 'totalTTC' => Gate::allows('viewTotal', $this->basket) ? - MoneyHelper::serialized($this->basket->totalTaxIncluded()) : null, - 'totalTVA' => Gate::allows('viewTotal', $this->basket) ? - MoneyHelper::serialized($this->basket->totalVat()) : null, - 'totalHT' => Gate::allows('viewTotal', $this->basket) ? - MoneyHelper::serialized($this->basket->totalRaw()) : null, - 'totaldiscount' => Gate::allows('viewTotal', $this->basket) ? - MoneyHelper::serialized($this->basket->totalDiscount()) : null, - 'totalweight' => $this->basket->totalWeight(), - 'countItems' => $this->basket->countItems(), + return [ + 'items' => BasketProductResource::collection($this->basket->items), + + 'totalTTC' => $canViewTotal ? MoneyHelper::serialized($this->basket->totalTaxIncluded) : null, + 'totalTVA' => $canViewTotal ? MoneyHelper::serialized($this->basket->totalVat) : null, + 'totalHT' => $canViewTotal ? MoneyHelper::serialized($this->basket->totalRaw) : null, + 'totaldiscount' => $canViewTotal ? MoneyHelper::serialized($this->basket->totalDiscount) : null, + 'totalweight' => $this->basket->totalWeight, + 'countItems' => $this->basket->countItems, ]; } } 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/Jobs/DeleteOldResetTokens.php b/app/Jobs/DeleteOldResetTokens.php index d0eec7cd..5015bc36 100644 --- a/app/Jobs/DeleteOldResetTokens.php +++ b/app/Jobs/DeleteOldResetTokens.php @@ -4,7 +4,9 @@ declare(strict_types=1); namespace App\Jobs; -use App\Models\PasswordReset; +use App\Contracts\ActionInputEmpty; +use App\Contracts\Executor; +use App\Cqs\Actions\Auth\DeleteOldResetTokens as DeleteOldResetTokensAction; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; @@ -15,10 +17,10 @@ class DeleteOldResetTokens implements ShouldQueue /** * Execute the job. */ - public function handle(): void - { - PasswordReset::query() - ->where('created_at', '<=', now()->subDays(7)) - ->forceDelete(); + public function handle( + Executor $executor, + DeleteOldResetTokensAction $action, + ): void { + $executor->execute($action, new ActionInputEmpty()); } } diff --git a/app/Jobs/EnsurePublicHolidaysSyncedJob.php b/app/Jobs/EnsurePublicHolidaysSyncedJob.php new file mode 100644 index 00000000..09e82983 --- /dev/null +++ b/app/Jobs/EnsurePublicHolidaysSyncedJob.php @@ -0,0 +1,80 @@ + + */ + public array $backoff = [10, 30]; + + public function handle( + Executor $executor, + HasAutoUpdatedPickupExceptionsForYearQuery $hasHolidaysQuery, + PublicHolidaysApiService $apiService, + UpsertShopsPickupExceptionsForYear $action, + ): void { + $now = Date::now(); + + if ($now->year >= 2026) { + $this->syncYearIfMissing( + $now->year, + $executor, + $hasHolidaysQuery, + $apiService, + $action, + ); + } + + if ($now->month >= 11) { + $this->syncYearIfMissing( + $now->year + 1, + $executor, + $hasHolidaysQuery, + $apiService, + $action, + ); + } + } + + private function syncYearIfMissing( + int $year, + Executor $executor, + HasAutoUpdatedPickupExceptionsForYearQuery $hasHolidaysQuery, + PublicHolidaysApiService $apiService, + UpsertShopsPickupExceptionsForYear $action, + ): void { + $alreadySynced = $executor->execute( + $hasHolidaysQuery, + new HasAutoUpdatedPickupExceptionsForYearQueryInput($year), + ); + + if ($alreadySynced) { + return; + } + + $holidays = $apiService->fetchForYear($year); + + $executor->execute( + $action, + new UpsertShopsPickupExceptionsForYearInput($year, $holidays), + ); + } +} 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/Jobs/SendContactMailJob.php b/app/Jobs/SendContactMailJob.php new file mode 100644 index 00000000..fb9cef24 --- /dev/null +++ b/app/Jobs/SendContactMailJob.php @@ -0,0 +1,74 @@ + + */ + public function backoff(): array + { + return [10, 30, 60, 300]; + } + + public function handle( + Mailer $mailer, + StorageService $storageService, + PrivateS3Disk $privateS3Disk, + ): void { + $mailer->to(new Address($this->recipientEmail, $this->recipientName)) + ->send(new SendContactMail($this->data)); + + $this->cleanupAttachment($storageService, $privateS3Disk); + } + + public function failed(\Throwable $exception): void + { + $this->cleanupAttachment( + app()->make(StorageService::class), + app()->make(PrivateS3Disk::class), + ); + } + + private function cleanupAttachment( + StorageService $storageService, + PrivateS3Disk $privateS3Disk, + ): void { + if ($this->data->file === null) { + return; + } + + $filePath = new StorageFilePath($this->data->file->path); + + if ($storageService->fileExistsOnDisk($filePath, $privateS3Disk->disk)) { + $storageService->removeFromDisk($filePath, $privateS3Disk->disk); + } + } +} diff --git a/app/Jobs/SendMissingOrderReminderJob.php b/app/Jobs/SendMissingOrderReminderJob.php index f7101316..e210f465 100644 --- a/app/Jobs/SendMissingOrderReminderJob.php +++ b/app/Jobs/SendMissingOrderReminderJob.php @@ -4,19 +4,30 @@ declare(strict_types=1); namespace App\Jobs; -use App\Contracts\Repositories\EmployeeRepository; -use App\Contracts\Repositories\OrderRepository; +use App\Dto\IcsContentDto; +use App\Models\Customer; use App\Models\Employee; +use App\Models\Order; use App\Notifications\MissingOrderReminderNotification; -use Carbon\CarbonInterface; +use App\Services\IcsGeneratorService; +use Carbon\CarbonImmutable; +use Domain\Enums\OrderStatus; +use Domain\Models\Entities\Shopper; +use Domain\Models\ValueObjects\IcsContent; use Domain\Services\PickupSchedulingService; +use Domain\Services\ShopperService; +use Illuminate\Contracts\Cache\Repository as CacheRepository; +use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Foundation\Queue\Queueable; -use Illuminate\Support\Carbon; -use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Config; +use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Gate; +use Webmozart\Assert\Assert; -class SendMissingOrderReminderJob implements ShouldQueue +class SendMissingOrderReminderJob implements ShouldBeUnique, ShouldQueue { use Queueable; @@ -24,41 +35,241 @@ class SendMissingOrderReminderJob implements ShouldQueue public const int HOURS_BEFORE_CUTOFF = 6; + public int $uniqueFor = 3600; + + private const int CHUNK_SIZE = 100; + + public function uniqueId(): string + { + return Date::now()->format('o-\WW'); + } + public function handle( PickupSchedulingService $schedulingService, - OrderRepository $orderRepository, - EmployeeRepository $employeeRepository + ShopperService $shopperService, + IcsGeneratorService $icsGenerator, + CacheRepository $cache, ): void { - $pickupDay = Carbon::now()->next($schedulingService->getPickupDay()->value); - $employees = $this->getEmployeesToNotify($pickupDay, $orderRepository, $employeeRepository); + $timezone = $schedulingService->getCutoffTimezone(); + $targetFriday = CarbonImmutable::instance($schedulingService->nextPickup()) + ->setTimezone($timezone) + ->startOfDay(); + $weekKey = $targetFriday->format('o-\WW'); + + /** @var array $windowsByShopId */ + $windowsByShopId = []; + + /** @var array $icsByCutoffKey */ + $icsByCutoffKey = []; + + Employee::query() + ->whereNotNull('customer_id') + ->with('customer') + ->active() + ->chunkById( + self::CHUNK_SIZE, + function (Collection $employees) use ( + $schedulingService, + $shopperService, + $icsGenerator, + $cache, + $targetFriday, + $weekKey, + &$windowsByShopId, + &$icsByCutoffKey, + ): void { + /** @var \Illuminate\Database\Eloquent\Collection $employees */ + $this->processChunk( + $employees, + $schedulingService, + $shopperService, + $icsGenerator, + $cache, + $targetFriday, + $weekKey, + $windowsByShopId, + $icsByCutoffKey, + ); + }, + 'id' + ); + } + + /** + * @param \Illuminate\Database\Eloquent\Collection $employees + * @param array $windowsByShopId + * @param array $icsByCutoffKey + */ + private function processChunk( + Collection $employees, + PickupSchedulingService $schedulingService, + ShopperService $shopperService, + IcsGeneratorService $icsGenerator, + CacheRepository $cache, + CarbonImmutable $targetFriday, + string $weekKey, + array &$windowsByShopId, + array &$icsByCutoffKey, + ): void { + $timezone = $schedulingService->getCutoffTimezone(); + + /** @var list $candidates */ + $candidates = []; foreach ($employees as $employee) { - $employee->notify(new MissingOrderReminderNotification($pickupDay)); + if (! $this->canNotifyEmployee($employee) || $cache->has($this->reminderCacheKey($weekKey, $employee->id))) { + continue; + } + + $shop = $shopperService->resolveShopForEmployee($this->mapEmployeeToShopper($employee)); + $shopId = $shop->id()->value->toString(); + + if (! array_key_exists($shopId, $windowsByShopId)) { + $windowsByShopId[$shopId] = $schedulingService->getPickupWindowFor($shop, $targetFriday); + } + + $window = $windowsByShopId[$shopId]; + if ($window === null) { + continue; + } + + $pickupDateKey = CarbonImmutable::instance($window->timeSlot->getAt()) + ->setTimezone($timezone) + ->format('Y-m-d'); + + $candidates[] = [ + 'employee' => $employee, + 'window' => $window, + 'pickupDateKey' => $pickupDateKey, + ]; + } + + if ($candidates === []) { + return; + } + + $orderedPairs = $this->findValidatedOrderPairs( + matricules: array_values(array_unique(array_map( + fn (array $candidate): string => $candidate['employee']->matricule->value, + $candidates, + ))), + pickupDates: array_values(array_unique(array_map( + fn (array $candidate): string => $candidate['pickupDateKey'], + $candidates, + ))), + ); + + foreach ($candidates as $candidate) { + $employee = $candidate['employee']; + $pairKey = $employee->matricule->value . '|' . $candidate['pickupDateKey']; + + if (isset($orderedPairs[$pairKey])) { + continue; + } + + if (! $cache->add($this->reminderCacheKey($weekKey, $employee->id), true, Date::now()->addWeek())) { + continue; + } + + $cutoffDate = $candidate['window']->deadline->setTimezone($timezone); + $cutoffKey = $cutoffDate->format(\DateTimeInterface::ATOM); + $icsContent = $icsByCutoffKey[$cutoffKey] ??= $this->generateIcsContent($icsGenerator, $cutoffDate); + $pickupDay = CarbonImmutable::instance($candidate['window']->timeSlot->getAt())->setTimezone($timezone); + + $employee->notify(new MissingOrderReminderNotification($pickupDay, $cutoffDate, $icsContent)); } } - /** @return Collection */ - private function getEmployeesToNotify( - CarbonInterface $pickupDay, - OrderRepository $orderRepository, - EmployeeRepository $employeeRepository - ): Collection { - $orders = $orderRepository->getValidatedOrdersForPickupDay($pickupDay); + private function reminderCacheKey(string $weekKey, int $employeeId): string + { + return 'missing-order-reminder:' . $weekKey . ':' . $employeeId; + } - /** @var array $excludedMatricules */ - $excludedMatricules = collect($orders) - ->map(fn ($order) => $order->employee->matricule) - ->uniqueValues() - ->all(); + /** + * @param list $matricules + * @param list $pickupDates + * @return array + */ + private function findValidatedOrderPairs(array $matricules, array $pickupDates): array + { + $orders = Order::query() + ->whereIn('employee_matricule', $matricules) + ->where('status', OrderStatus::VALIDATED) + ->where(function (Builder $query) use ($pickupDates): void { + foreach ($pickupDates as $date) { + $query->orWhereDate('pickup_day', $date); + } + }) + ->get(['employee', 'pickup_day']); - return collect($employeeRepository->getWithCustomerWhereMatriculeNotIn($excludedMatricules)) - ->filter(fn ($employee) => $this->canNotifyEmployee($employee)); + $pairs = []; + foreach ($orders as $order) { + $date = $order->pickup_day?->format('Y-m-d'); + if ($date !== null) { + $pairs[$order->employee->matricule->value . '|' . $date] = true; + } + } + + return $pairs; + } + + private function generateIcsContent(IcsGeneratorService $icsGenerator, CarbonImmutable $cutoffDate): IcsContent + { + $appUrl = Config::string('app.url'); + $appHost = parse_url($appUrl, \PHP_URL_HOST); + + if (empty($appHost)) { + throw new \UnexpectedValueException('Invalid app URL configuration'); + } + + $appName = Config::string('app.name', 'La Boutique de Cocotte'); + $closureTime = $cutoffDate->format('G') . 'h'; + $eventStart = $cutoffDate->subHours(2); + $eventEnd = $eventStart->addMinutes(15); + + return $icsGenerator->generate(new IcsContentDto( + uid: 'reminder-' . $eventStart->format('Y-m-d') . '@' . $appHost, + summary: trans('Place my order :appname', [ + 'appname' => $appName, + ]), + description: trans('Remember to validate your order before :closureTime on :url', [ + 'closureTime' => $closureTime, + 'url' => $appHost, + ]), + startsAt: $eventStart, + endsAt: $eventEnd, + url: $appUrl, + )); + } + + private function mapEmployeeToShopper(Employee $employee): Shopper + { + $customer = $employee->customer; + Assert::isInstanceOf($customer, Customer::class); + + return new Shopper( + id: $customer->getId(), + email: $customer->email, + matricule: clone $employee->matricule, + nom: $employee->nom, + prenom: $employee->prenom, + startDate: $employee->start_date !== null + ? CarbonImmutable::instance($employee->start_date) + : CarbonImmutable::now(), + endDate: $employee->end_date !== null + ? CarbonImmutable::instance($employee->end_date) + : null, + etablissement: $employee->etablissement, + site: $employee->site, + service: $employee->service, + ); } private function canNotifyEmployee(Employee $employee): bool { $customer = $employee->customer; - return $customer && Gate::check('customerPassOrders', $customer); + return $customer instanceof Customer + && Gate::forUser($customer)->check('customerPassOrders'); } } diff --git a/app/Jobs/SendReminderMail.php b/app/Jobs/SendReminderMail.php index db2e31e7..b4d5fbf4 100644 --- a/app/Jobs/SendReminderMail.php +++ b/app/Jobs/SendReminderMail.php @@ -4,62 +4,117 @@ declare(strict_types=1); namespace App\Jobs; -use App\Contracts\Repositories\EmployeeRepository; -use App\Contracts\Repositories\OrderRepository; +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; use App\Models\Order; use App\Notifications\OrderTodayReminderNotification; +use Carbon\CarbonImmutable; +use Domain\Enums\OrderStatus; +use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Foundation\Queue\Queueable; +use Illuminate\Support\Facades\Date; use Money\MoneyFormatter; -class SendReminderMail implements ShouldQueue +class SendReminderMail implements ShouldBeUnique, ShouldQueue { use Queueable; + public int $uniqueFor = 3600; + + private const int CHUNK_SIZE = 100; + public function __construct( private readonly MoneyFormatter $moneyFormatter ) { } - /** - * Execute the job. - * - * @return mixed - */ + public function uniqueId(): string + { + return Date::now()->format('Y-m-d'); + } + public function handle( - OrderRepository $orderRepository, - EmployeeRepository $employeeRepository - ) { - $orders = $orderRepository->getOrdersWithLinesAndShopForPickupDay(now()); + Executor $executor, + ClaimTodayOrderReminder $claimAction, + ReleaseTodayOrderReminder $releaseAction, + ): void { + $today = Date::now()->format('Y-m-d'); - $matricules = collect($orders) - ->map(fn ($order) => $order->employee->matricule) - ->filter() - ->uniqueValues(); + Order::query() + ->with(['lines', 'shop']) + ->whereDate('pickup_day', $today) + ->where('status', OrderStatus::VALIDATED) + ->whereNull('reminded_at') + ->chunkById( + self::CHUNK_SIZE, + function (Collection $orders) use ($executor, $claimAction, $releaseAction): void { + /** @var \Illuminate\Database\Eloquent\Collection $orders */ + $this->processChunk($orders, $executor, $claimAction, $releaseAction); + }, + 'id' + ); + } - /** @var array $matriculesArray */ - $matriculesArray = $matricules->values()->toArray(); - $employees = collect($employeeRepository->getWithCustomerWhereMatriculeIn($matriculesArray)); + /** + * @param \Illuminate\Database\Eloquent\Collection $orders + */ + private function processChunk( + Collection $orders, + Executor $executor, + ClaimTodayOrderReminder $claimAction, + ReleaseTodayOrderReminder $releaseAction, + ): void { + $matricules = $orders + ->map(fn (Order $order): string => $order->employee->matricule->value) + ->unique() + ->values(); + + $employees = Employee::query() + ->with('customer') + ->whereIn('matricule', $matricules) + ->get() + ->keyBy(fn (Employee $employee): string => $employee->matricule->value); foreach ($orders as $order) { - $matricule = $order->employee->matricule->value; + $employee = $employees->get($order->employee->matricule->value); - if (! $employees->has($matricule)) { - continue; - } - $employee = $employees->get($matricule); - - if (! $employee) { + if (! $employee instanceof Employee) { continue; } - $this->notifyEmployee( - $employee, - $this->toDto($order, $employee) + $dto = $this->toDto($order, $employee); + $remindedAt = CarbonImmutable::now()->utc()->startOfSecond(); + $claimed = $executor->execute( + $claimAction, + new ClaimTodayOrderReminderInput($order->getId(), $remindedAt), ); + + if (! $claimed) { + continue; + } + + 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/Jobs/UpdateSlidesStatus.php b/app/Jobs/UpdateSlidesStatus.php index ef5f23e6..cedce570 100644 --- a/app/Jobs/UpdateSlidesStatus.php +++ b/app/Jobs/UpdateSlidesStatus.php @@ -4,11 +4,11 @@ declare(strict_types=1); namespace App\Jobs; -use App\Models\Slide; +use App\Contracts\ActionInputEmpty; +use App\Contracts\Executor; +use App\Cqs\Actions\Slides\UpdateSlidesStatus as UpdateSlidesStatusAction; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; -use Illuminate\Support\Facades\Date; -use Illuminate\Support\Facades\Log; class UpdateSlidesStatus implements ShouldQueue { @@ -17,39 +17,10 @@ class UpdateSlidesStatus implements ShouldQueue /** * Execute the job. */ - public function handle(): void - { - $now = Date::now(); - - $unpublishQuery = Slide::query() - ->where('date_end', '<=', $now) - ->whereNotNull('date_end') - ->where('status', true); - - $unpublishCount = $unpublishQuery->count(); - Log::debug(self::class . ' slides to unpublish ' . $unpublishCount); - - if ($unpublishCount > 0) { - $unpublishQuery->update([ - 'date_start' => null, - 'date_end' => null, - 'status' => false, - ]); - } - - $publishQuery = Slide::query() - ->where('date_start', '<=', $now) - ->whereNotNull('date_start') - ->where('status', false); - - $publishCount = $publishQuery->count(); - Log::debug(self::class . ' slides to publish ' . $publishCount); - - if ($publishCount > 0) { - $publishQuery->update([ - 'date_start' => null, - 'status' => true, - ]); - } + public function handle( + Executor $executor, + UpdateSlidesStatusAction $action, + ): void { + $executor->execute($action, new ActionInputEmpty()); } } diff --git a/app/Jobs/UpsertShopsPickupExceptionsUsingApiForYear.php b/app/Jobs/UpsertShopsPickupExceptionsUsingApiForYear.php index 0548794b..f555911e 100644 --- a/app/Jobs/UpsertShopsPickupExceptionsUsingApiForYear.php +++ b/app/Jobs/UpsertShopsPickupExceptionsUsingApiForYear.php @@ -4,23 +4,24 @@ declare(strict_types=1); namespace App\Jobs; -use App\Models\PickupException; -use App\Models\Shop; -use Domain\Enums\RepeatFrequency; +use App\Contracts\Executor; +use App\Cqs\Actions\PickupExceptions\UpsertShopsPickupExceptionsForYear; +use App\Cqs\Actions\PickupExceptions\UpsertShopsPickupExceptionsForYearInput; +use App\Services\PublicHolidaysApiService; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; -use Illuminate\Support\Arr; use Illuminate\Support\Facades\Date; -use Illuminate\Support\Facades\Http; -use Illuminate\Support\Facades\Validator; class UpsertShopsPickupExceptionsUsingApiForYear implements ShouldQueue { use Queueable; - private const string CALENDAR_API_URL = 'https://calendrier.api.gouv.fr/jours-feries/metropole/:year.json'; + public int $tries = 3; - private const int API_CALL_TIMEOUT = 120; + /** + * @var list + */ + public array $backoff = [10, 30]; protected int $year; @@ -34,84 +35,16 @@ class UpsertShopsPickupExceptionsUsingApiForYear implements ShouldQueue ); } - public function handle(): void - { - $hollydayList = $this->getHollydaysForYear($this->year); + public function handle( + Executor $executor, + PublicHolidaysApiService $apiService, + UpsertShopsPickupExceptionsForYear $action, + ): void { + $holidays = $apiService->fetchForYear($this->year); - foreach ($hollydayList as $holiday) { - $exception = PickupException::query() - ->firstOrNew(['label' => $holiday->label]); - $exception->fill([ - 'date' => $holiday->date->format('Y-m-d'), - 'repeatable' => true, - 'repeat_frequency' => RepeatFrequency::YEARLY, - ]); - $exception->setAttribute('auto_updated', true); - $exception->save(); - } - - // * Sync repeatables api pickup exception for all shops - $repeatablesFromApi = PickupException::query() - ->whereIn('label', array_map( - fn ($v) => $v->label, - $hollydayList - ))->get(); - - Shop::query()->get() - ->each(fn ($shop) => $shop->pickupExceptions() - ->syncWithoutDetaching($repeatablesFromApi)); - } - - /** @return object{date:\DateTimeInterface,label:string}[] */ - private function getHollydaysForYear(int $year): array - { - $url = $this->getCalendarApiUrlFor($year); - - $response = Http::timeout(self::API_CALL_TIMEOUT)->get($url); - throw_unless( - $response->successful(), - \UnexpectedValueException::class, - 'Failed to fetch calendar from api' - ); - - $outputList = $response - ->collect() - ->map(fn ($label, $date) => [ - 'date' => $date, - 'label' => $label, - ])->all(); - - $rules = [ - '*' => 'array', - '*.date' => ['required', 'date'], - '*.label' => ['required', 'string'], - ]; - - $validator = Validator::make($outputList, $rules); - - if ($validator->fails()) { - $errors = $validator->errors(); - throw new \UnexpectedValueException( - 'Invalid response: ' . - json_encode($errors->messages()) - ); - } - - return array_map(fn (array $entry) => (object) [ - 'date' => Date::parse( - $entry['date'], - new \DateTimeZone('Europe/Paris') - ), - 'label' => Arr::string($entry, 'label'), - ], $outputList); - } - - private function getCalendarApiUrlFor(int $year): string - { - return str_replace( - ':year', - strval($year), - self::CALENDAR_API_URL + $executor->execute( + $action, + new UpsertShopsPickupExceptionsForYearInput($this->year, $holidays), ); } } diff --git a/app/Lib/Helpers/ExceptionsHelper.php b/app/Lib/Helpers/ExceptionsHelper.php index 5f129afe..d10e7310 100644 --- a/app/Lib/Helpers/ExceptionsHelper.php +++ b/app/Lib/Helpers/ExceptionsHelper.php @@ -68,14 +68,16 @@ class ExceptionsHelper /** * Get anonymized sentry params. * - * @template T of mixed + * @template T of array * - * @param array $params - * @return array + * @param T $params + * @return array */ private static function getAnonymizedSentryParams(array $params): array { - foreach ($params as &$param) { + $output = []; + + foreach ($params as $key => &$param) { $type = gettype($param); $param = match (true) { @@ -87,9 +89,11 @@ class ExceptionsHelper : sprintf('String(%d)', strlen($param)), default => ucfirst($type), }; + + $output[(string) $key] = $param; } - return $params; + return $output; } /** diff --git a/app/Lib/Helpers/FileStorageHelper.php b/app/Lib/Helpers/FileStorageHelper.php deleted file mode 100644 index 4f3cb6a9..00000000 --- a/app/Lib/Helpers/FileStorageHelper.php +++ /dev/null @@ -1,525 +0,0 @@ -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/RequestHelper.php b/app/Lib/Helpers/RequestHelper.php index ea16c636..9cf0a160 100644 --- a/app/Lib/Helpers/RequestHelper.php +++ b/app/Lib/Helpers/RequestHelper.php @@ -46,4 +46,53 @@ final class RequestHelper { return new Uri($request->fullUrl()); } + + /** + * Build configuration array for the Back-Office image input Vue component. + * + * @param list $allowedExtensions + * @return array{ + * name: string, + * single: bool, + * width: int, + * height: int, + * preview: bool, + * accept: string, + * helper: string, + * value: string, + * } + */ + public static function imageInputConfig( + string $name, + int $width, + int $height, + int $maxSizeKb, + array $allowedExtensions, + string $value = '', + ): array { + $maxSizeMb = round($maxSizeKb / 1024, 1); + $formattedSize = fmod($maxSizeMb, 1.0) === 0.0 + ? (string) (int) $maxSizeMb + : (string) $maxSizeMb; + $prefixedExtensions = array_map( + static fn (string $ext): string => '.' . ltrim($ext, '.'), + $allowedExtensions, + ); + + return [ + 'name' => $name, + 'single' => true, + 'width' => $width, + 'height' => $height, + 'preview' => false, + 'accept' => implode(',', $prefixedExtensions), + 'helper' => __('Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px', [ + 'extensions' => implode(', ', $prefixedExtensions), + 'maxSize' => $formattedSize, + 'width' => $width, + 'height' => $height, + ]), + 'value' => $value, + ]; + } } diff --git a/app/Lib/Helpers/ToolboxHelper.php b/app/Lib/Helpers/ToolboxHelper.php index 85a3a1f1..9905caef 100644 --- a/app/Lib/Helpers/ToolboxHelper.php +++ b/app/Lib/Helpers/ToolboxHelper.php @@ -4,22 +4,9 @@ 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 { @@ -42,20 +29,6 @@ class ToolboxHelper extends ToolboxHelperCore return $merged; } - /** - * Strip scheme (https) on oembed urls - * Only embed allowed are for MP4 self hosted videos right now - * - * https is force by ckeditor MediaElements which natively supports - * only cloud hosted medias (youtube, spotify etc..) - */ - public static function stripCkEditorSchemesOnMediaInputs(string $input): string - { - return Str::of($input) - ->replaceMatches('/(?<=)/m', '') - ->toString(); - } - /** * Asserts that the field is unique. * @@ -92,87 +65,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 */ @@ -193,255 +85,4 @@ 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 - * - * @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); - } - } - - /** - * 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..99add04d 100644 --- a/app/Lib/Helpers/ToolboxHelperCore.php +++ b/app/Lib/Helpers/ToolboxHelperCore.php @@ -4,10 +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; - abstract class ToolboxHelperCore { /** @@ -117,75 +113,4 @@ 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 - */ - 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/Listeners/Orders/EmptyBasketOnOrderPlaced.php b/app/Listeners/Orders/EmptyBasketOnOrderPlaced.php new file mode 100644 index 00000000..5d3618da --- /dev/null +++ b/app/Listeners/Orders/EmptyBasketOnOrderPlaced.php @@ -0,0 +1,22 @@ +basketService->empty(); + } +} diff --git a/app/Listeners/Orders/InvalidateOrderBuilderOnBasketChange.php b/app/Listeners/Orders/InvalidateOrderBuilderOnBasketChange.php new file mode 100644 index 00000000..7a11c655 --- /dev/null +++ b/app/Listeners/Orders/InvalidateOrderBuilderOnBasketChange.php @@ -0,0 +1,23 @@ +orderBuilderSessionManager->clear(); + } +} diff --git a/app/Listeners/Orders/ProcessRegateOrderExport.php b/app/Listeners/Orders/ProcessRegateOrderExport.php deleted file mode 100644 index 5d8be2f0..00000000 --- a/app/Listeners/Orders/ProcessRegateOrderExport.php +++ /dev/null @@ -1,28 +0,0 @@ -regateService->processOrder( - $event->reference, - $event->byMatricule, - CarbonImmutable::instance($event->pickupDay), - $event->lines - ); - } -} 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/Listeners/Orders/SendCustomerOrderConfirmation.php b/app/Listeners/Orders/SendCustomerOrderConfirmation.php index a8ca5f5d..26180e50 100644 --- a/app/Listeners/Orders/SendCustomerOrderConfirmation.php +++ b/app/Listeners/Orders/SendCustomerOrderConfirmation.php @@ -4,22 +4,18 @@ declare(strict_types=1); namespace App\Listeners\Orders; -use App\Contracts\Repositories\EmployeeRepository; +use App\Models\Employee; use App\Notifications\OrderConfirmed; use Domain\Events\AnOrderHasBeenPlaced; // NOTE: This has to be run in SYNC class SendCustomerOrderConfirmation { - public function __construct( - private readonly EmployeeRepository $employeeRepository - ) { - } - public function handle(AnOrderHasBeenPlaced $event): void { - $employee = $this->employeeRepository - ->findByMatricule($event->byMatricule); + $employee = Employee::query() + ->where('matricule', $event->byMatricule->value) + ->first(); if ($employee) { $employee->notify(new OrderConfirmed($event)); diff --git a/app/Listeners/SendRegateOrderMail.php b/app/Listeners/SendRegateOrderMail.php deleted file mode 100644 index 2a207dab..00000000 --- a/app/Listeners/SendRegateOrderMail.php +++ /dev/null @@ -1,35 +0,0 @@ -regateEmail = new Address(Config::string('mail.to.regate')); - } - - public function handle(RegateOrderCsvGenerated $event): void - { - Mail::to($this->regateEmail) - ->send(new RegateOrderMail( - $event->csvContent, - $event->fileName - )); - } -} diff --git a/app/Listeners/UpdateCustomerLastLogin.php b/app/Listeners/UpdateCustomerLastLogin.php index 0d639963..3157bca2 100644 --- a/app/Listeners/UpdateCustomerLastLogin.php +++ b/app/Listeners/UpdateCustomerLastLogin.php @@ -4,20 +4,31 @@ declare(strict_types=1); namespace App\Listeners; +use App\Contracts\Executor; +use App\Cqs\Actions\Customers\UpdateCustomerLastLogin as UpdateCustomerLastLoginAction; +use App\Cqs\Actions\Customers\UpdateCustomerLastLoginInput; use App\Models\Customer; use Illuminate\Auth\Events\Login; // NOTE: This has to be run in SYNC class UpdateCustomerLastLogin { + public function __construct( + private readonly Executor $executor, + private readonly UpdateCustomerLastLoginAction $action, + ) { + } + /** * Handle the event. */ public function handle(Login $event): void { if ($event->user instanceof Customer) { - $event->user->last_login_at = now(); - $event->user->save(); + $this->executor->execute( + $this->action, + new UpdateCustomerLastLoginInput($event->user), + ); } } } diff --git a/app/Mail/SendContactMail.php b/app/Mail/SendContactMail.php index 3c992e0c..f337ca11 100644 --- a/app/Mail/SendContactMail.php +++ b/app/Mail/SendContactMail.php @@ -4,36 +4,17 @@ 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; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Address; use Illuminate\Mail\Mailables\Attachment; use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Envelope; -use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Config; -// NOTE: This may be be queued -class SendContactMail extends Mailable implements ShouldQueue +class SendContactMail extends Mailable { - use Queueable; - use SerializesModels; - - /** 'failed_jobs' after */ - public int $tries = 5; - - /** - * Attempts delays - * - * @return array - */ - public function backoff(): array - { - return [10, 30, 60, 300]; - } - /** * Create a new message instance. */ @@ -88,8 +69,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/Customer.php b/app/Models/Customer.php index 591fd0bb..469b7a6e 100644 --- a/app/Models/Customer.php +++ b/app/Models/Customer.php @@ -6,6 +6,7 @@ namespace App\Models; use App\Casts\CrmHashcodeCast; use App\Casts\EmailCast; +use App\Casts\UtcDatetimeCast; use App\Traits\Models\HasUuidV7AsPrimaryKey; use Domain\Contracts\CustomerDetails; use Domain\Models\ValueObjects\Entities\ShopperId; @@ -14,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 @@ -45,7 +46,7 @@ class Customer extends Authenticatable implements CustomerDetails, MustVerifyEma return [ 'email' => EmailCast::class, 'hashcode' => CrmHashcodeCast::class, - 'last_login_at' => 'datetime', + 'last_login_at' => UtcDatetimeCast::class, ]; } @@ -75,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/Discount.php b/app/Models/Discount.php index 2d3bb81d..028fc558 100644 --- a/app/Models/Discount.php +++ b/app/Models/Discount.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Models; use App\Casts\DiscountValueCast; +use App\Casts\UtcDatetimeCast; use Domain\Enums\DiscountType; use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Builder; @@ -42,8 +43,8 @@ class Discount extends Model 'type' => DiscountType::class, 'value' => DiscountValueCast::class, 'is_old_price_displayed' => 'bool', - 'date_start' => 'datetime', - 'date_end' => 'datetime', + 'date_start' => UtcDatetimeCast::class, + 'date_end' => UtcDatetimeCast::class, ]; } diff --git a/app/Models/Employee.php b/app/Models/Employee.php index f7dcd6bc..4de37b3e 100644 --- a/app/Models/Employee.php +++ b/app/Models/Employee.php @@ -4,11 +4,13 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\CalendarDateCast; use App\Casts\CodeCast; use App\Casts\MatriculeCast; use App\Casts\ShopperEstablishmentCodeCast; use App\Casts\ShopperServiceCodeCast; use App\Casts\ShopperSiteCodeCast; +use App\Casts\UtcDatetimeCast; use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Casts\Attribute; @@ -57,6 +59,8 @@ class Employee extends Model { use Notifiable; + private const string BUSINESS_TIMEZONE = 'Europe/Paris'; + /** @return \Illuminate\Database\Eloquent\Casts\Attribute */ protected function fullName(): Attribute { @@ -75,9 +79,9 @@ class Employee extends Model return [ 'code' => CodeCast::class, 'matricule' => MatriculeCast::class, - 'last_sync' => 'datetime', - 'start_date' => 'datetime', - 'end_date' => 'datetime', + 'last_sync' => UtcDatetimeCast::class, + 'start_date' => CalendarDateCast::class, + 'end_date' => CalendarDateCast::class, 'etablissement' => ShopperEstablishmentCodeCast::class, 'site' => ShopperSiteCodeCast::class, 'service' => ShopperServiceCodeCast::class, @@ -88,7 +92,14 @@ class Employee extends Model protected function isActive(): Attribute { return Attribute::make( - get: fn (): bool => $this->end_date?->greaterThanOrEqualTo(Date::now()) ?? true + get: function (): bool { + $today = Date::now(self::BUSINESS_TIMEZONE)->format('Y-m-d'); + + $hasStarted = $this->start_date === null || $this->start_date->format('Y-m-d') <= $today; + $hasNotEnded = $this->end_date === null || $this->end_date->format('Y-m-d') > $today; + + return $hasStarted && $hasNotEnded; + } ); } @@ -98,11 +109,19 @@ class Employee extends Model */ protected function scopeActive(Builder $query): Builder { - return $query->where( - fn ($q) => $q - ->where('end_date', '>=', Date::now()) - ->orWhereNull('end_date') - ); + $today = Date::now(self::BUSINESS_TIMEZONE)->format('Y-m-d'); + + return $query + ->where( + fn (Builder $q): Builder => $q + ->where('start_date', '<=', $today) + ->orWhereNull('start_date') + ) + ->where( + fn (Builder $q): Builder => $q + ->where('end_date', '>', $today) + ->orWhereNull('end_date') + ); } public function routeNotificationForMail(): string diff --git a/app/Models/Order.php b/app/Models/Order.php index 00500d77..e7330305 100644 --- a/app/Models/Order.php +++ b/app/Models/Order.php @@ -4,10 +4,12 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\CalendarDateCast; use App\Casts\DeliveryAddressCast; use App\Casts\MoneyCast; use App\Casts\OrderEmployeeCast; use App\Casts\OrderReferenceCast; +use App\Casts\UtcDatetimeCast; use App\Traits\Models\HasUuidV7AsPrimaryKey; use Carbon\CarbonInterface; use Domain\Enums\OrderStatus; @@ -17,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 @@ -30,6 +32,7 @@ use Ramsey\Uuid\Uuid; * @property OrderStatus $status * @property \Illuminate\Support\Carbon|null $updated_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 @@ -47,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> */ @@ -65,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]); } @@ -75,7 +78,8 @@ class Order extends Model protected function casts(): array { return [ - 'pickup_day' => 'date', + 'pickup_day' => CalendarDateCast::class, + 'reminded_at' => UtcDatetimeCast::class, 'employee' => OrderEmployeeCast::class, 'total' => MoneyCast::class, 'status' => OrderStatus::class, diff --git a/app/Models/OrderTunnelAttempt.php b/app/Models/OrderTunnelAttempt.php new file mode 100644 index 00000000..970e2b9f --- /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/Models/Page.php b/app/Models/Page.php index bdec942a..53026e88 100644 --- a/app/Models/Page.php +++ b/app/Models/Page.php @@ -33,7 +33,7 @@ use Illuminate\Database\Eloquent\Model; ])] class Page extends Model { - /** @use \App\Traits\Models\IsCachedAsCollection */ + /** @use \App\Traits\Models\IsCachedAsCollection */ use IsCachedAsCollection; #[\Override] diff --git a/app/Models/PasswordReset.php b/app/Models/PasswordReset.php index e4c16b86..2a2b6f22 100644 --- a/app/Models/PasswordReset.php +++ b/app/Models/PasswordReset.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\UtcDatetimeCast; use Illuminate\Database\Eloquent\Attributes\Table; use Illuminate\Database\Eloquent\Attributes\WithoutTimestamps; use Illuminate\Database\Eloquent\Model; @@ -26,7 +27,7 @@ class PasswordReset extends Model protected function casts(): array { return [ - 'created_at' => 'date', + 'created_at' => UtcDatetimeCast::class, ]; } } diff --git a/app/Models/PickupException.php b/app/Models/PickupException.php index a6dbf271..cb223e57 100644 --- a/app/Models/PickupException.php +++ b/app/Models/PickupException.php @@ -4,8 +4,8 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\CalendarDateCast; use App\Traits\Models\HasUuidV7AsPrimaryKey; -use DateTimeInterface; use Domain\Enums\RepeatFrequency; use Domain\Models\ValueObjects\Entities\PickupExceptionId; use Illuminate\Database\Eloquent\Attributes\Fillable; @@ -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 @@ -61,7 +61,7 @@ class PickupException extends Model * Format a date */ #[\Override] - protected function serializeDate(DateTimeInterface $date): string + protected function serializeDate(\DateTimeInterface $date): string { return $date->format('Y-m-d'); } @@ -78,7 +78,7 @@ class PickupException extends Model protected function casts(): array { return [ - 'date' => 'date', + 'date' => CalendarDateCast::class, 'repeatable' => 'bool', 'auto_updated' => 'bool', 'repeat_frequency' => RepeatFrequency::class, diff --git a/app/Models/Product.php b/app/Models/Product.php index 1921efa3..71675ad6 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -4,11 +4,12 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\FilePathCast; use App\Casts\MoneyCast; +use App\Casts\UtcDatetimeCast; 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; @@ -32,9 +33,11 @@ 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; +use Uwil\SitemapGenerator\Contracts\Sitemapable; /** * @property string $id @@ -42,10 +45,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 @@ -109,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; @@ -120,9 +123,22 @@ 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)); + return new ProductId(UuidHelper::fromString($this->id)); } #[\Override] @@ -133,23 +149,16 @@ 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'); + $max = self::query()->withTrashed()->max('order'); $model->order = is_scalar($max) ? intval($max) + 1 : 1; } } @@ -165,8 +174,10 @@ class Product extends Model implements ModelWithOrder, ModelWithStar, ModelWithS protected function casts(): array { return [ - 'orderable_start' => 'datetime', - 'orderable_end' => 'datetime', + 'picture' => FilePathCast::class, + 'picture_large' => FilePathCast::class, + 'orderable_start' => UtcDatetimeCast::class, + 'orderable_end' => UtcDatetimeCast::class, 'price' => MoneyCast::class, 'brand' => ProductBrand::class, 'invoicing_unit' => InvoicingUnit::class, @@ -175,7 +186,7 @@ class Product extends Model implements ModelWithOrder, ModelWithStar, ModelWithS 'weight_variable' => 'bool', 'star' => 'bool', 'status' => 'bool', - 'deleted_at' => 'datetime', + 'deleted_at' => UtcDatetimeCast::class, 'tax_rate' => TaxRate::class, ]; } @@ -216,7 +227,7 @@ class Product extends Model implements ModelWithOrder, ModelWithStar, ModelWithS // * Orderable ->where(function (Builder $q) use ($now): void { $q->whereNull('orderable_start') - ->orWhere('orderable_start', '<', $now); + ->orWhere('orderable_start', '<=', $now); }) ->where(function (Builder $q) use ($now): void { $q->whereNull('orderable_end') diff --git a/app/Models/ProductInco.php b/app/Models/ProductInco.php index 06b4ed8d..30bbf3bb 100644 --- a/app/Models/ProductInco.php +++ b/app/Models/ProductInco.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Models; use App\Casts\NutritionalValuesCast; +use App\Dto\ArcadiaIncoDataDto; use Domain\Enums\Nutriscore; use Domain\Models\ValueObjects\IncoId; use Illuminate\Database\Eloquent\Attributes\Fillable; @@ -101,6 +102,18 @@ class ProductInco extends Model return new IncoId($this->no_art); } + public function hydrateFromArcadiaDto(ArcadiaIncoDataDto $incoData): void + { + $this->ingredients = $incoData->ingredients; + $this->preparation = $incoData->preparation; + $this->servings = $incoData->servings; + $this->allergens = $incoData->allergens; + $this->selling_argument = $incoData->sellingArgument; + $this->nutriscore = $incoData->nutriscore; + $this->nutriscore_args = $incoData->nutriscoreArgs; + $this->nutrition = $incoData->nutrition; + } + /** @return \Illuminate\Database\Eloquent\Relations\BelongsTo<\App\Models\Product,$this> */ public function product(): BelongsTo { diff --git a/app/Models/Range.php b/app/Models/Range.php index ec72dd69..5384b87f 100644 --- a/app/Models/Range.php +++ b/app/Models/Range.php @@ -4,13 +4,14 @@ 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; use Illuminate\Database\Eloquent\Attributes\Fillable; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Str; @@ -22,7 +23,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 @@ -31,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([ @@ -56,9 +59,15 @@ 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'); - }); + } + + /** + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function scopePublished(Builder $query): Builder + { + return $query->where('status', true); } #[\Override] @@ -81,7 +90,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 +113,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/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/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/Models/ShopPickupExceptionPivot.php b/app/Models/ShopPickupExceptionPivot.php index 1df55184..5b21ab27 100644 --- a/app/Models/ShopPickupExceptionPivot.php +++ b/app/Models/ShopPickupExceptionPivot.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\CalendarDateCast; +use App\Casts\UtcDatetimeCast; use Illuminate\Database\Eloquent\Relations\Pivot; /** @@ -20,8 +22,8 @@ class ShopPickupExceptionPivot extends Pivot protected function casts(): array { return [ - 'replacement_date' => 'date', - 'order_deadline_at' => 'datetime', + 'replacement_date' => CalendarDateCast::class, + 'order_deadline_at' => UtcDatetimeCast::class, ]; } } diff --git a/app/Models/Slide.php b/app/Models/Slide.php index bef0dd62..c67683c7 100644 --- a/app/Models/Slide.php +++ b/app/Models/Slide.php @@ -4,9 +4,10 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\FilePathCast; +use App\Casts\UtcDatetimeCast; 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 +22,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 +78,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 +93,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,12 +116,13 @@ class Slide extends Model implements ModelWithOrder, ModelWithStatus protected function casts(): array { return [ + 'picture' => FilePathCast::class, 'link_new_tab' => 'bool', 'connected' => 'bool', 'status' => 'bool', 'order' => 'int', - 'date_start' => 'datetime', - 'date_end' => 'datetime', + 'date_start' => UtcDatetimeCast::class, + 'date_end' => UtcDatetimeCast::class, ]; } } diff --git a/app/Models/Stat.php b/app/Models/Stat.php index 04ee1ed3..053dc4e4 100644 --- a/app/Models/Stat.php +++ b/app/Models/Stat.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\CalendarDateCast; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; @@ -31,7 +32,7 @@ class Stat extends Model protected function casts(): array { return [ - 'date' => 'datetime', + 'date' => CalendarDateCast::class, 'margin' => 'float', 'nb_sale' => 'int', ]; diff --git a/app/Models/User.php b/app/Models/User.php index ccac21a1..70a81ae7 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\UtcDatetimeCast; use Domain\Contracts\AdminDetails; use Domain\Enums\UserRole; use Illuminate\Database\Eloquent\Attributes\Fillable; @@ -60,7 +61,7 @@ class User extends Authenticatable implements AdminDetails protected function casts(): array { return [ - 'email_verified_at' => 'datetime', + 'email_verified_at' => UtcDatetimeCast::class, 'role' => UserRole::class, ]; } diff --git a/app/Notifications/MissingOrderReminderNotification.php b/app/Notifications/MissingOrderReminderNotification.php index 02381c5b..1291110b 100644 --- a/app/Notifications/MissingOrderReminderNotification.php +++ b/app/Notifications/MissingOrderReminderNotification.php @@ -4,14 +4,13 @@ declare(strict_types=1); namespace App\Notifications; -use App\Contracts\Repositories\OrderRepository; -use App\Dto\IcsContentDto; use App\Jobs\SendMissingOrderReminderJob; use App\Models\Employee; -use App\Services\IcsGeneratorService; +use App\Models\Order; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; -use Domain\Services\PickupSchedulingService; +use Domain\Enums\OrderStatus; +use Domain\Models\ValueObjects\IcsContent; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; @@ -29,7 +28,9 @@ class MissingOrderReminderNotification extends Notification implements ShouldQue private readonly string $appHost; public function __construct( - private readonly CarbonInterface $pickupDay + private readonly CarbonInterface $pickupDay, + private readonly CarbonInterface $cutoffDate, + private readonly IcsContent $icsContent, ) { $appUrl = Config::string('app.url'); $appHost = parse_url($appUrl, \PHP_URL_HOST); @@ -48,13 +49,11 @@ class MissingOrderReminderNotification extends Notification implements ShouldQue */ public function shouldSend(Employee $notifiable, string $channel): bool { - /** @var OrderRepository $orderRepository */ - $orderRepository = app(OrderRepository::class); - - return ! $orderRepository->hasValidatedOrderForPickupDay( - $notifiable->matricule, - $this->pickupDay - ); + return ! Order::query() + ->where('employee_matricule', $notifiable->matricule->value) + ->whereDate('pickup_day', $this->pickupDay->format('Y-m-d')) + ->where('status', OrderStatus::VALIDATED) + ->exists(); } /** @@ -68,27 +67,10 @@ class MissingOrderReminderNotification extends Notification implements ShouldQue public function toMail(mixed $notifiable): MailMessage { /** @var Employee $notifiable */ - $icsGenerator = app(IcsGeneratorService::class); - $schedulingService = app(PickupSchedulingService::class); - - $cutoffDate = $schedulingService->getPeriodForPickupDate($this->pickupDay) - ->getStartDate() - ->setTimezone('Europe/Paris'); - + $cutoffDate = CarbonImmutable::instance($this->cutoffDate)->setTimezone('Europe/Paris'); $closureTime = $cutoffDate->format('G') . 'h'; $reminderDay = $cutoffDate->translatedFormat('l'); - $reminderTime = $cutoffDate->copy()->subHours(2)->format('G') . 'h'; - - // The reminder event starts 2 hours before the cutoff on the cutoff day - $eventStart = CarbonImmutable::instance($cutoffDate)->subHours(2); - $eventEnd = $eventStart->addMinutes(15); - - $icsContent = $this->generateIcsContent( - $icsGenerator, - $eventStart, - $eventEnd, - $closureTime - ); + $reminderTime = $cutoffDate->subHours(2)->format('G') . 'h'; return (new MailMessage()) ->subject(trans(':time before order taking closes - :appname', [ @@ -104,32 +86,8 @@ class MissingOrderReminderNotification extends Notification implements ShouldQue 'appHost' => $this->appHost, 'appUrl' => $this->appUrl, ]) - ->attachData($icsContent, 'rappel-commande.ics', [ + ->attachData($this->icsContent->value, 'rappel-commande.ics', [ 'mime' => 'text/calendar', ]); } - - private function generateIcsContent( - IcsGeneratorService $icsGenerator, - CarbonInterface $eventStart, - CarbonInterface $eventEnd, - string $closureTime - ): string { - - $eventDto = new IcsContentDto( - uid: 'reminder-' . $eventStart->format('Y-m-d') . '@' . $this->appHost, - summary: trans('Place my order :appname', [ - 'appname' => $this->appName, - ]), - description: trans('Remember to validate your order before :closureTime on :url', [ - 'closureTime' => $closureTime, - 'url' => $this->appHost, - ]), - startsAt: $eventStart, - endsAt: $eventEnd, - url: $this->appUrl - ); - - return $icsGenerator->generate($eventDto); - } } diff --git a/app/Policies/Backend/OrderPolicy.php b/app/Policies/Backend/OrderPolicy.php index 3a5f6d02..fc20609c 100644 --- a/app/Policies/Backend/OrderPolicy.php +++ b/app/Policies/Backend/OrderPolicy.php @@ -40,12 +40,17 @@ class OrderPolicy return $user->role->isAtLeastEqualsTo(UserRole::Admin); } + /** + * Back-office admins may cancel any non-canceled order regardless of pickup_day + * as an administrative override (see REGLES METIERS.md section 5). + */ public function cancel(User | Customer $user, Order | OrderDto $order): bool { if ($user instanceof Customer) { 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/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/BasketPolicy.php b/app/Policies/Frontend/BasketPolicy.php index 9e7570dc..aafa39d9 100644 --- a/app/Policies/Frontend/BasketPolicy.php +++ b/app/Policies/Frontend/BasketPolicy.php @@ -4,31 +4,23 @@ declare(strict_types=1); namespace App\Policies\Frontend; +use App\Dto\BasketProductDto; use App\Models\Customer; use App\Models\User; -use Domain\Models\ValueObjects\BasketProduct; -use Domain\Ports\Repositories\ProductRepository; class BasketPolicy { - public function __construct( - private readonly ProductRepository $productRepository - ) { - } - public function viewTotal(null | User | Customer $_): bool { return $_ !== null; } - public function viewPrices(null | User | Customer $_, BasketProduct $product): bool + public function viewPrices(null | User | Customer $user, BasketProductDto $item): bool { - if ($_ === null) { + if ($user === null) { return false; } - $domainProduct = $this->productRepository->find($product->id); - - return $domainProduct && $domainProduct->isPublished(); + return $item->isPublished; } } diff --git a/app/Policies/Frontend/OrderPolicy.php b/app/Policies/Frontend/OrderPolicy.php index 8d47d8ec..628bf56e 100644 --- a/app/Policies/Frontend/OrderPolicy.php +++ b/app/Policies/Frontend/OrderPolicy.php @@ -8,12 +8,13 @@ use App\Dto\OrderDto; use App\Models\Customer; use App\Models\Order; use App\Models\User; -use App\Services\OrderService; +use App\Services\OrderOwnershipService; +use Domain\Enums\OrderStatus; class OrderPolicy { public function __construct( - private readonly OrderService $orderService + private readonly OrderOwnershipService $orderOwnershipService ) { } @@ -32,7 +33,11 @@ class OrderPolicy return false; } - return $this->orderService->isOrderOwnedBy( + if (\in_array($order->status, [OrderStatus::PENDING, OrderStatus::FAILED], true)) { + return false; + } + + return $this->orderOwnershipService->isOrderOwnedBy( $order, $user, ); diff --git a/app/Policies/Frontend/OrderTunnelStepPolicy.php b/app/Policies/Frontend/OrderTunnelStepPolicy.php index c6b65cbe..c40dfa34 100644 --- a/app/Policies/Frontend/OrderTunnelStepPolicy.php +++ b/app/Policies/Frontend/OrderTunnelStepPolicy.php @@ -6,14 +6,15 @@ namespace App\Policies\Frontend; use App\Models\Customer; use App\Models\User; -use Domain\Enums\OrderTunnelStep; +use Domain\Services\BasketService; use Domain\Services\OrderTunnelService; use Illuminate\Support\Facades\Gate; class OrderTunnelStepPolicy { public function __construct( - private readonly OrderTunnelService $orderTunnelService + private readonly OrderTunnelService $orderTunnelService, + private readonly BasketService $basketService, ) { } @@ -26,8 +27,8 @@ class OrderTunnelStepPolicy return Gate::allows( 'customerPassOrders', $user - ) && $this->orderTunnelService - ->canAccessStep(OrderTunnelStep::REVIEW); + ) && $this->basketService + ->hasItems(); } public function canPickTimeSlot(User | Customer $user): bool @@ -40,7 +41,7 @@ class OrderTunnelStepPolicy 'customerPassOrders', $user ) && $this->orderTunnelService - ->canAccessStep(OrderTunnelStep::BOOKING); + ->canAccessBooking(); } public function canFinalizeOrder(User | Customer $user): bool @@ -53,6 +54,6 @@ class OrderTunnelStepPolicy 'customerPassOrders', $user ) && $this->orderTunnelService - ->canAccessStep(OrderTunnelStep::CONFIRMATION); + ->canAccessConfirmation(); } } diff --git a/app/Policies/Frontend/ProductPolicy.php b/app/Policies/Frontend/ProductPolicy.php index 3e22e638..64647125 100644 --- a/app/Policies/Frontend/ProductPolicy.php +++ b/app/Policies/Frontend/ProductPolicy.php @@ -4,40 +4,32 @@ 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 $product->product->status; + } - return $domainProduct && $domainProduct->isPublished(); + public function viewPublished(null | User | Customer $_, ProductWithPricingDto $product): bool + { + return $product->product->status; } } diff --git a/app/Policies/Frontend/ShopPolicy.php b/app/Policies/Frontend/ShopPolicy.php index bf4fed49..5c485907 100644 --- a/app/Policies/Frontend/ShopPolicy.php +++ b/app/Policies/Frontend/ShopPolicy.php @@ -12,10 +12,6 @@ class ShopPolicy { public function viewPickupTimeslots(null | User | Customer $user, Shop $__): bool { - if ($user instanceof User) { - return false; - } - - return true; + return $user instanceof Customer; } } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 0d41a518..82586239 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -4,23 +4,21 @@ declare(strict_types=1); namespace App\Providers; -use App\Contracts\Directories\CustomerDirectory; -use App\Contracts\Directories\EmployeeDirectory; -use App\Contracts\Directories\OrderDirectory; use App\Contracts\Executor; -use App\Contracts\Repositories\EmployeeRepository; -use App\Contracts\Repositories\OrderRepository; -use App\Contracts\Repositories\UserRepository; -use App\Directories\EloquentCustomerDirectory; -use App\Directories\EloquentEmployeeDirectory; -use App\Directories\EloquentOrderDirectory; -use App\Repositories\EloquentEmployeeRepository; -use App\Repositories\EloquentOrderRepository; -use App\Repositories\EloquentUserRepository; +use App\Lib\PrivateS3Disk; +use App\Lib\PublicS3Disk; use App\Services\ActionExecutorService; +use App\Services\DataTableService; +use App\Services\IcsGeneratorService; +use Carbon\CarbonInterface; +use Illuminate\Contracts\Foundation\Application; +use Illuminate\Contracts\Session\Session; use Illuminate\Database\Eloquent\Model; +use Illuminate\Http\Request; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Date; +use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\URL; use Illuminate\Support\Facades\Vite; use Illuminate\Support\ServiceProvider; @@ -43,17 +41,43 @@ class AppServiceProvider extends ServiceProvider ); $this->app->singleton('clientIp', function () { + $realIp = request()->header('X-Real-Ip'); + + if (\is_string($realIp) && \filter_var($realIp, \FILTER_VALIDATE_IP) !== false) { + return $realIp; + } + return request()->ip() ?? request()->getClientIp(); }); - $this->app->bind(EmployeeRepository::class, EloquentEmployeeRepository::class); - $this->app->bind(OrderRepository::class, EloquentOrderRepository::class); - $this->app->bind(UserRepository::class, EloquentUserRepository::class); + $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(CustomerDirectory::class, EloquentCustomerDirectory::class); - $this->app->bind(EmployeeDirectory::class, EloquentEmployeeDirectory::class); - $this->app->bind(OrderDirectory::class, EloquentOrderDirectory::class); $this->app->bind(Executor::class, ActionExecutorService::class); + + $this->app->singleton( + IcsGeneratorService::class, + fn (): IcsGeneratorService => new IcsGeneratorService( + Config::string('app.name', 'La Boutique de Cocotte'), + ) + ); + + $this->app->bind( + DataTableService::class, + fn (Application $app): DataTableService => new DataTableService( + request: $app->make(Request::class), + session: $app->make(Session::class), + columnListingResolver: static fn (string $table): array => Schema::getColumnListing($table), + ) + ); } /** @@ -97,40 +121,43 @@ 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'); }); + + Date::macro('forHumansDate', function ($date) { + if (! $date || (! $date instanceof CarbonInterface && ! $date instanceof \DateTimeInterface && ! is_string($date))) { + return null; + } + + $parsed = $date instanceof \DateTimeInterface + ? Date::instance($date) + : Date::parse($date, 'UTC'); + + return $parsed->isoFormat('ddd DD/MM/Y'); + }); + } + + private function withLocalTimezone(CarbonInterface | \DateTimeInterface | string $date): CarbonInterface + { + $timezone = request()->string('client_timezone', 'Europe/Paris')->value(); + + if (! in_array($timezone, \DateTimeZone::listIdentifiers(\DateTimeZone::ALL_WITH_BC), true)) { + $timezone = 'Europe/Paris'; + } + + return Date::parse($date)->setTimezone($timezone); } private function collectionMacro(): void diff --git a/app/Providers/ArcadiaApiProvider.php b/app/Providers/ArcadiaApiProvider.php index e35e18d4..38ae49a8 100644 --- a/app/Providers/ArcadiaApiProvider.php +++ b/app/Providers/ArcadiaApiProvider.php @@ -59,7 +59,7 @@ class ArcadiaApiProvider extends ServiceProvider Config::string('services.arcadia_api.api_secret') ); - $ignoreSelfSignedCert = Config::boolean('services.arcadia_api.ignore_self_signed_cert', true); + $ignoreSelfSignedCert = Config::boolean('services.arcadia_api.ignore_self_signed_cert', false); return new ApiConfig( endpoint: $endpoint, diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 4f76bc1a..b3556d40 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -4,11 +4,14 @@ declare(strict_types=1); namespace App\Providers; +use App\Dto\BasketDto; +use App\Dto\BasketProductDto; use App\Dto\DiscountDto; 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,14 +32,19 @@ 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\Auth\Notifications\ResetPassword; +use Illuminate\Auth\Notifications\VerifyEmail; +use Illuminate\Foundation\Application; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Config; +use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Gate; +use Illuminate\Support\Facades\URL; use Infrastructure\Adapters\Services\AppAdminAuthService; use Infrastructure\Adapters\Services\AppCustomerAuthService; @@ -50,12 +58,14 @@ class AuthServiceProvider extends ServiceProvider #[\Override] protected $policies = [ // * Policies Exceptions - BasketProduct::class => BasketPolicy::class, + BasketDto::class => BasketPolicy::class, + BasketProductDto::class => BasketPolicy::class, DiscountDto::class => DiscountPolicy::class, FaqDto::class => FaqPolicy::class, 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 +84,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) ) @@ -105,6 +115,62 @@ class AuthServiceProvider extends ServiceProvider return class_exists($policyClass) ? $policyClass : null; }); + + $this->authUrlCallbacksSetup(); + } + + private function authUrlCallbacksSetup(): void + { + VerifyEmail::createUrlUsing($this->createEmailVerificationUrl(...)); + ResetPassword::createUrlUsing($this->createPasswordResetUrl(...)); + } + + private function createEmailVerificationUrl(mixed $notifiable): string + { + if (! $notifiable instanceof Customer) { + throw new \InvalidArgumentException('Invalid notifiable provided.'); + } + + $appKey = Config::string('app.key'); + + if (empty(trim($appKey))) { + throw new \UnexpectedValueException('App key is not set.'); + } + + return url( + URL::temporarySignedRoute( + 'fo.auth.verification.verify', + Date::now()->addMinutes(Config::integer('auth.verification.expire', 60)), + [ + 'id' => $notifiable->getKey(), + 'hash' => hash_hmac( + 'sha256', + $notifiable->getEmailForVerification(), + $appKey + ), + ], + false + ) + ); + } + + private function createPasswordResetUrl(mixed $notifiable, string $token): string + { + if (! $notifiable instanceof Customer) { + throw new \InvalidArgumentException('Invalid notifiable provided.'); + } + + return url( + URL::temporarySignedRoute( + 'fo.auth.reset-password', + Date::now()->addMinutes(Config::integer('auth.reset.expire', 60)), + [ + 'token' => $token, + 'email' => $notifiable->getEmailForPasswordReset(), + ], + false + ) + ); } private function currentRouteGuard(): string diff --git a/app/Providers/CrmApiServiceProvider.php b/app/Providers/CrmApiServiceProvider.php index 115e9e9d..160c7209 100644 --- a/app/Providers/CrmApiServiceProvider.php +++ b/app/Providers/CrmApiServiceProvider.php @@ -6,13 +6,18 @@ namespace App\Providers; use App\Auth\CrmUserProvider; use App\Services\CrmService; +use Domain\Ports\Services\CrmCustomerGatewayService; +use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Cache\Repository; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\Hashing\Hasher; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Arr; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Auth; use Illuminate\Support\ServiceProvider; use LDC\LDCCRM\CrmApiV4; +use Webmozart\Assert\Assert; class CrmApiServiceProvider extends ServiceProvider { @@ -27,12 +32,19 @@ class CrmApiServiceProvider extends ServiceProvider $app->make(CrmApiV4::class), $app->make(Repository::class), )); + App::bind(CrmCustomerGatewayService::class, fn (Application $app): CrmCustomerGatewayService => $app->make(CrmService::class)); Auth::provider(CrmUserProvider::class, function (Application $app, array $config) { $hasher = $app->make(Hasher::class); $crmService = $app->make(CrmService::class); - return new CrmUserProvider($hasher, $config['model'], $crmService); + $model = Arr::string($config, 'model'); + + Assert::classExists($model); + Assert::implementsInterface($model, Authenticatable::class); + Assert::subclassOf($model, Model::class); + + return new CrmUserProvider($hasher, $model, $crmService); }); } } diff --git a/app/Providers/DomainServiceProvider.php b/app/Providers/DomainServiceProvider.php index 651a0b98..c55157d9 100644 --- a/app/Providers/DomainServiceProvider.php +++ b/app/Providers/DomainServiceProvider.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace App\Providers; +use App\Services\MailRegateService; +use Domain\Policies\CustomerOrderLimitPolicy; use Domain\Ports\Directories\CodeDirectory; use Domain\Ports\Directories\ShopDirectory; use Domain\Ports\Repositories\BasketRepository; @@ -17,11 +19,15 @@ use Domain\Ports\Services\CsvGenerator; use Domain\Ports\Services\CustomerAuthenticationService; use Domain\Ports\Services\EmployeeImportStorageService; use Domain\Ports\Services\EmployeeStatisticsService; +use Domain\Ports\Services\RegateService; use Domain\Ports\Services\TransactionManager; +use Illuminate\Foundation\Application; +use Illuminate\Support\Facades\Config; use Illuminate\Support\ServiceProvider; use Infrastructure\Adapters\Directories\EloquentCodeDirectory; use Infrastructure\Adapters\Directories\EloquentShopDirectory; use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; +use Infrastructure\Adapters\Locks\LaravelCacheLock; use Infrastructure\Adapters\Repositories\EloquentOrderRepository; use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; use Infrastructure\Adapters\Repositories\EloquentProductRepository; @@ -34,6 +40,8 @@ use Infrastructure\Adapters\Services\CsvGeneratorImpl; use Infrastructure\Adapters\Services\EloquentEmployeeImportStorageService; use Infrastructure\Adapters\Services\EloquentEmployeeStatisticsService; use Infrastructure\Adapters\Services\LaravelTransactionManager; +use Money\Currency; +use Shared\Concurrency\Lock; use Shared\DDD\DomainEventDispatcher; class DomainServiceProvider extends ServiceProvider @@ -44,7 +52,9 @@ class DomainServiceProvider extends ServiceProvider #[\Override] public function register(): void { - $this->app->singleton( + $this->app->scoped(LaravelDomainEventDispatcher::class); + + $this->app->bind( DomainEventDispatcher::class, LaravelDomainEventDispatcher::class ); @@ -118,6 +128,25 @@ class DomainServiceProvider extends ServiceProvider CsvGenerator::class, CsvGeneratorImpl::class ); + + $this->app->bind( + Lock::class, + LaravelCacheLock::class + ); + + $this->app->bind( + RegateService::class, + MailRegateService::class + ); + + $this->app->singleton( + CustomerOrderLimitPolicy::class, + fn (Application $app): CustomerOrderLimitPolicy => new CustomerOrderLimitPolicy( + maxOrderAmountCents: Config::integer('ldc.max_order_amount_cents'), + maxWeeklyAmountCents: Config::integer('ldc.max_weekly_amount_cents'), + currency: $app->make(Currency::class), + ) + ); } /** diff --git a/app/Providers/MoneyServiceProvider.php b/app/Providers/MoneyServiceProvider.php index 6ed2bee5..22fccc64 100644 --- a/app/Providers/MoneyServiceProvider.php +++ b/app/Providers/MoneyServiceProvider.php @@ -71,7 +71,7 @@ class MoneyServiceProvider extends ServiceProvider private function sharetoView(): void { - Blade::directive('money', function ($expression): string { + Blade::directive('money', function (string $expression): string { return "format($expression); ?>"; }); Blade::directive('currency', function ($_): string { diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index bc93b955..8d17c7ce 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -4,6 +4,9 @@ declare(strict_types=1); namespace App\Providers; +use App\Contracts\Executor; +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 +16,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 +141,16 @@ 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 $this->app->make(Executor::class)->execute( + $this->app->make(GetPublishedProductWithPricingQuery::class), + $input, + ) ?? throw new NotFoundHttpException(); } /** @@ -184,7 +175,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 +188,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/ShoppingServiceProvider.php b/app/Providers/ShoppingServiceProvider.php index 69494155..42feda91 100644 --- a/app/Providers/ShoppingServiceProvider.php +++ b/app/Providers/ShoppingServiceProvider.php @@ -8,14 +8,18 @@ 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; use Illuminate\Support\Facades\App; 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; class ShoppingServiceProvider extends ServiceProvider { @@ -23,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. * @@ -30,23 +36,41 @@ class ShoppingServiceProvider extends ServiceProvider */ public function boot() { - App::singleton(SessionService::class, fn () => new AppSessionService('domain_session_uuid')); + App::singleton( + SessionService::class, + fn () => new AppSessionService('domain_session_uuid') + ); - App::singleton(BasketRepository::class, fn () => new SessionBasketRepository( - resolve(Session::class), - self::BASKET_SESSION_KEY_PREFIX, - resolve(BasketSerializer::class) - )); + App::scoped( + BasketRepository::class, + fn (Application $app) => new SessionBasketRepository( + $app->make(Session::class), + self::BASKET_SESSION_KEY_PREFIX, + $app->make(BasketSerializer::class) + ) + ); - App::singleton(BasketService::class, fn () => new BasketService( - resolve(BasketRepository::class), - resolve(ProductRepository::class), - resolve(SessionService::class) - )); + App::scoped( + OrderBuilderSessionManager::class, + fn (Application $app) => new SessionOrderBuilderManager( + $app->make(Session::class), + self::ORDER_BUILDER_SESSION_KEY + ) + ); - App::singleton(OrderBuilderSessionManager::class, fn () => new SessionOrderBuilderManager( - resolve(Session::class), - self::ORDER_BUILDER_SESSION_KEY + 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), + $app->make(SessionService::class), + $app->make(DomainEventDispatcher::class) )); } } diff --git a/app/Providers/TranslationServiceProvider.php b/app/Providers/TranslationServiceProvider.php index 7d7d169d..a00e70d5 100644 --- a/app/Providers/TranslationServiceProvider.php +++ b/app/Providers/TranslationServiceProvider.php @@ -89,7 +89,7 @@ class TranslationServiceProvider extends ServiceProvider /** * Gather json translations. * - * @return array + * @return array */ private function jsonTranslations(string $locale): array { 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/Repositories/EloquentEmployeeRepository.php b/app/Repositories/EloquentEmployeeRepository.php deleted file mode 100644 index 90c37dfd..00000000 --- a/app/Repositories/EloquentEmployeeRepository.php +++ /dev/null @@ -1,102 +0,0 @@ - */ - public function getAll(): array - { - return Employee::query() - ->get() - ->all(); - } - - public function find(UuidInterface $id): ?Employee - { - return Employee::query() - ->where('id', $id->toString()) - ->first(); - } - - public function persist(Employee $employee): void - { - $employee->save(); - } - - public function delete(Employee $employee): void - { - $employee->delete(); - } - - public function findByMatriculeAndCode(Matricule $matricule, Code $code): ?Employee - { - return Employee::query() - ->where('matricule', $matricule->value) - ->where('code', $code->value) - ->first(); - } - - public function findByMatricule(Matricule $matricule): ?Employee - { - return Employee::query() - ->where('matricule', $matricule->value) - ->first(); - } - - /** - * @param array|Collection $matricules - * @return array - */ - public function getWhereMatriculeIn(array | Collection $matricules): array - { - return Employee::query() - ->whereIn('matricule', $matricules) - ->get() - ->all(); - } - - /** - * @param array|Collection $matricules - * @return array - */ - public function getWithCustomerWhereMatriculeIn(array | Collection $matricules): array - { - return Employee::query() - ->with('customer') - ->whereIn('matricule', $matricules) - ->get() - ->keyBy('matricule') - ->all(); - } - - /** - * @param array|Collection $excludedMatricules - * @return array - */ - public function getWithCustomerWhereMatriculeNotIn(array | Collection $excludedMatricules): array - { - return Employee::query() - ->with('customer') - ->whereNotIn('matricule', $excludedMatricules) - ->get() - ->all(); - } - - public function getMostRecentSyncDate(): ?\DateTimeInterface - { - return Employee::query() - ->orderBy('last_sync', 'desc') - ->limit(1) - ->first('last_sync')?->last_sync; - } -} diff --git a/app/Repositories/EloquentOrderRepository.php b/app/Repositories/EloquentOrderRepository.php deleted file mode 100644 index a4f78c5b..00000000 --- a/app/Repositories/EloquentOrderRepository.php +++ /dev/null @@ -1,65 +0,0 @@ - */ - public function getAll(): array - { - return Order::query()->get()->all(); - } - - public function find(UuidInterface $id): ?Order - { - return Order::query()->find($id->toString()); - } - - public function persist(Order $order): void - { - $order->save(); - } - - public function delete(Order $order): void - { - $order->delete(); - } - - /** @return array */ - public function getValidatedOrdersForPickupDay(CarbonInterface $pickupDay): array - { - return Order::query() - ->whereDate('pickup_day', $pickupDay->format('Y-m-d')) - ->where('status', OrderStatus::VALIDATED) - ->get() - ->all(); - } - - public function hasValidatedOrderForPickupDay(Matricule $matricule, CarbonInterface $pickupDay): bool - { - return Order::query() - ->where('employee_matricule', $matricule->value) - ->whereDate('pickup_day', $pickupDay->format('Y-m-d')) - ->where('status', OrderStatus::VALIDATED) - ->exists(); - } - - /** @return array */ - public function getOrdersWithLinesAndShopForPickupDay(CarbonInterface $pickupDay): array - { - return Order::query() - ->with(['lines', 'shop']) - ->whereDate('pickup_day', $pickupDay->format('Y-m-d')) - ->get() - ->all(); - } -} diff --git a/app/Repositories/EloquentUserRepository.php b/app/Repositories/EloquentUserRepository.php deleted file mode 100644 index d3cc4293..00000000 --- a/app/Repositories/EloquentUserRepository.php +++ /dev/null @@ -1,27 +0,0 @@ -find($id); - } - - public function persist(User $user): void - { - $user->save(); - } - - public function delete(User $user): void - { - $user->delete(); - } -} diff --git a/app/Rules/Adult.php b/app/Rules/Adult.php index 85233812..c6f85caa 100644 --- a/app/Rules/Adult.php +++ b/app/Rules/Adult.php @@ -4,35 +4,37 @@ declare(strict_types=1); namespace App\Rules; -use Closure; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Facades\Date; class Adult implements ValidationRule { /** @param \Closure(string, ?string=):\Illuminate\Translation\PotentiallyTranslatedString $fail */ - public function validate(string $attribute, mixed $value, Closure $fail): void + public function validate(string $attribute, mixed $value, \Closure $fail): void { if (! is_string($value)) { - $fail('Erreur sur le champs : date de naissance.'); + $fail(trans('validation.custom.birth_date.date')); return; } + $format = match (true) { + $this->isSqlDate($value) => 'Y-m-d', + $this->isFormDate($value) => 'd/m/Y', + default => null, + }; + + if ($format === null) { + $fail(trans('validation.custom.birth_date.date')); + + return; + } + + $date = Date::createFromFormat($format, $value); $majorityLimit = Date::now()->subYears(18); - if ($this->isSqlDate($value)) { - $d = Date::createFromFormat('Y-m-d', $value); - if (! $d?->lessThanOrEqualTo($majorityLimit)) { - $fail('Vous devez être majeur pour vous inscrire.'); - } - } elseif ($this->isFormDate($value)) { - $d = Date::createFromFormat('d/m/Y', $value); - if (! $d?->lessThanOrEqualTo($majorityLimit)) { - $fail('Vous devez être majeur pour vous inscrire.'); - } - } else { - $fail('Erreur sur le champs : date de naissance.'); + if (! $date || ! $date->lessThanOrEqualTo($majorityLimit)) { + $fail(trans('validation.custom.birth_date.before_or_equal')); } } diff --git a/app/Rules/FileExtensionMatchesMimeType.php b/app/Rules/FileExtensionMatchesMimeType.php new file mode 100644 index 00000000..263d45ce --- /dev/null +++ b/app/Rules/FileExtensionMatchesMimeType.php @@ -0,0 +1,42 @@ +isValid()) { + return; + } + + $extension = strtolower($value->getClientOriginalExtension()); + $detectedMime = strtolower((string) $value->getMimeType()); + + if ($extension === '' || $detectedMime === '') { + return; + } + + $expectedMimes = array_map( + strtolower(...), + MimeTypes::getDefault()->getMimeTypes($extension), + ); + + if ($expectedMimes !== [] && ! in_array($detectedMime, $expectedMimes, true)) { + $fail(trans('validation.mimes', [ + 'attribute' => $attribute, + 'values' => $extension, + ])); + } + } +} diff --git a/app/Rules/IncoId.php b/app/Rules/IncoId.php index 802f8ac2..aaf57770 100644 --- a/app/Rules/IncoId.php +++ b/app/Rules/IncoId.php @@ -4,14 +4,13 @@ declare(strict_types=1); namespace App\Rules; -use Closure; use Domain\Models\ValueObjects\IncoId as ValueObjectsIncoId; use Illuminate\Contracts\Validation\ValidationRule; class IncoId implements ValidationRule { /** @param \Closure(string, ?string=):\Illuminate\Translation\PotentiallyTranslatedString $fail */ - public function validate(string $attribute, mixed $value, Closure $fail): void + public function validate(string $attribute, mixed $value, \Closure $fail): void { try { if (! is_numeric($value)) { diff --git a/app/Rules/Matricule.php b/app/Rules/Matricule.php index cc3b5c8e..4211904b 100644 --- a/app/Rules/Matricule.php +++ b/app/Rules/Matricule.php @@ -4,14 +4,13 @@ declare(strict_types=1); namespace App\Rules; -use Closure; use Domain\Models\ValueObjects\Matricule as ValueObjectsMatricule; use Illuminate\Contracts\Validation\ValidationRule; class Matricule implements ValidationRule { /** @param \Closure(string, ?string=):\Illuminate\Translation\PotentiallyTranslatedString $fail */ - public function validate(string $attribute, mixed $value, Closure $fail): void + public function validate(string $attribute, mixed $value, \Closure $fail): void { try { if (! is_numeric($value)) { diff --git a/app/Services/ActionExecutorService.php b/app/Services/ActionExecutorService.php index 01db42dd..453cd647 100644 --- a/app/Services/ActionExecutorService.php +++ b/app/Services/ActionExecutorService.php @@ -4,30 +4,40 @@ 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; +use App\Contracts\HandlesFailure; +use App\Contracts\HandlesLockTimeout; +use App\Contracts\HandlesSuccess; +use App\Contracts\ProvidesLockKey; use App\Contracts\Query; use App\Contracts\QueryInput; use Illuminate\Support\Facades\DB; -use Override; +use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; use Psr\Log\LoggerInterface; +use Shared\Concurrency\Lock; +use Shared\Concurrency\LockTimeoutException; final class ActionExecutorService implements Executor { public function __construct( - private readonly ?LoggerInterface $logger = null, + private readonly Lock $lock, + private readonly LoggerInterface $logger, + private readonly LaravelDomainEventDispatcher $eventDispatcher, ) { } - #[Override] + #[\Override] public function execute(Action | Query $executable, ActionInput | QueryInput $input): mixed { $executableClass = $executable::class; $actionName = class_basename($executableClass); $type = $executable instanceof Action ? 'Action' : 'Query'; - $this->logger?->info("[{$type}] Executing {$actionName}", [ + $this->logger->info("[{$type}] Executing {$actionName}", [ 'action' => $executableClass, 'input' => $input::class, ]); @@ -36,22 +46,24 @@ final class ActionExecutorService implements Executor if ($executable instanceof Action) { $this->assertInputIsAction($input); - return $this->executeWithinTransaction( - $executable, - $input, - $actionName - ); + $lockedAttribute = $this->resolveLockedAttribute($executable); + + if ($lockedAttribute !== null) { + return $this->executeWithLock($executable, $input, $actionName, $lockedAttribute); + } + + return $this->executeWithoutLock($executable, $input, $actionName); } $this->assertInputIsQuery($input); - return $this->executeWithoutTransaction( + return $this->executeQuery( $executable, $input, $actionName ); } catch (\Throwable $e) { - $this->logger?->error("[{$type}] Failed {$actionName}: {$e->getMessage()}", [ + $this->logger->error("[{$type}] Failed {$actionName}: {$e->getMessage()}", [ 'action' => $executableClass, 'input' => $input::class, 'message' => $e->getMessage(), @@ -69,15 +81,132 @@ final class ActionExecutorService implements Executor * @param TQuery $executable * @param TQueryInput $input */ - private function executeWithoutTransaction(Query $executable, QueryInput $input, string $actionName): mixed + private function executeQuery(Query $executable, QueryInput $input, string $actionName): mixed { $result = $executable($input); - $this->logger?->info("[Query] Succeeded {$actionName}"); + $this->logger->info("[Query] Succeeded {$actionName}"); + + return $result; + } + + /** + * @template TAction of Action + * + * @param TAction $executable + */ + private function resolveLockedAttribute(Action $executable): ?Locked + { + $reflection = new \ReflectionClass($executable); + $attributes = $reflection->getAttributes(Locked::class); + + 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 + * + * @param TAction $executable + * @param TActionInput $input + */ + private function executeWithLock( + Action $executable, + ActionInput $input, + string $actionName, + Locked $locked, + ): mixed { + $lockKey = $executable instanceof ProvidesLockKey + ? $executable->lockKey($input) + : ($locked->key ?? $executable::class); + + try { + $result = $this->lock->synchronize( + key: $lockKey, + callback: fn (): mixed => $this->executeWithinTransaction($executable, $input, $actionName), + ttlSeconds: $locked->ttlSeconds, + waitSeconds: $locked->waitSeconds, + ); + } catch (LockTimeoutException $e) { + if ($executable instanceof HandlesLockTimeout) { + $this->logger->warning("[Action] Lock timeout {$actionName}", [ + 'action' => $executable::class, + 'input' => $input::class, + 'lockKey' => $lockKey, + 'message' => $e->getMessage(), + ]); + + return $executable->onLockTimeout($input); + } + + $this->runFailureHook($executable, $input, $e); + + throw $e; + } catch (\Throwable $e) { + $this->runFailureHook($executable, $input, $e); + + throw $e; + } + + $this->runPostCommitHooks($executable, $input, $result); return $result; } + /** + * @template TAction of Action + * @template TActionInput of ActionInput + * + * @param TAction $executable + * @param TActionInput $input + */ + private function executeWithoutLock( + Action $executable, + ActionInput $input, + string $actionName, + ): mixed { + try { + $result = $this->executeWithinTransaction($executable, $input, $actionName); + } catch (\Throwable $e) { + $this->runFailureHook($executable, $input, $e); + + throw $e; + } + + $this->runPostCommitHooks($executable, $input, $result); + + return $result; + } + + /** + * @template TAction of Action + * @template TActionInput of ActionInput + * + * @param TAction $executable + * @param TActionInput $input + */ + private function runFailureHook( + Action $executable, + ActionInput $input, + \Throwable $exception, + ): void { + if ($executable instanceof HandlesFailure) { + $executable->onFailure($input, $exception); + } + } + /** * @template TAction of Action * @template TActionInput of ActionInput @@ -87,13 +216,41 @@ final class ActionExecutorService implements Executor */ private function executeWithinTransaction(Action $executable, ActionInput $input, string $actionName): mixed { - return DB::transaction(function () use ($executable, $input, $actionName): mixed { + $this->eventDispatcher->beginBuffering(); + + $run = function () use ($executable, $input, $actionName): mixed { $result = $executable($input); - $this->logger?->info("[Action] Succeeded {$actionName}"); + $this->logger->info("[Action] Succeeded {$actionName}"); return $result; - }); + }; + + try { + return $this->hasWithoutTransactionAttribute($executable) + ? $run() + : DB::transaction($run); + } catch (\Throwable $e) { + $this->eventDispatcher->discard(); + + throw $e; + } + } + + /** + * @template TAction of Action + * @template TActionInput of ActionInput + * + * @param TAction $executable + * @param TActionInput $input + */ + private function runPostCommitHooks(Action $executable, ActionInput $input, mixed $result): void + { + $this->eventDispatcher->flush(); + + if ($executable instanceof HandlesSuccess) { + $executable->onSuccess($input, $result); + } } /** diff --git a/app/Services/CrmService.php b/app/Services/CrmService.php index 0572f7d4..85e84c5a 100644 --- a/app/Services/CrmService.php +++ b/app/Services/CrmService.php @@ -13,6 +13,7 @@ use App\Models\Customer as ModelsCustomer; use Domain\Enums\Country; use Domain\Models\ValueObjects\CrmCustomer; use Domain\Models\ValueObjects\Email; +use Domain\Ports\Services\CrmCustomerGatewayService; use Illuminate\Contracts\Cache\Repository as CacheRepository; use Illuminate\Support\Arr; use Illuminate\Validation\ValidationException as IlluminateValidationException; @@ -24,21 +25,20 @@ use LDC\LDCCRM\Exceptions\CrmException; use LDC\LDCCRM\Exceptions\ValidationException; use LDC\LDCCRM\Models\Customer; use Shared\ValueObjects\CrmHashcode; -use UnexpectedValueException; -class CrmService +class CrmService implements CrmCustomerGatewayService { /** * Request-level cache to avoid duplicate CRM calls for the same customer. * - * @var array + * @var array */ private array $customerByHashcodeCache = []; /** * Request-level cache to avoid duplicate CRM calls for the same customer. * - * @var array + * @var array */ private array $customerByEmailCache = []; @@ -126,7 +126,7 @@ class CrmService { throw_if( $crmCustomer->email === null, - new UnexpectedValueException('CRM customer email is required for password change') + new \UnexpectedValueException('CRM customer email is required for password change') ); try { @@ -146,7 +146,7 @@ class CrmService $result = $this->persist($updatedCrmCustomer); throw_if( ! $result->email, - new UnexpectedValueException('CRM customer email is required for password change event') + new \UnexpectedValueException('CRM customer email is required for password change event') ); event(new CustomerPasswordUpdated(new Email($result->email))); @@ -170,7 +170,7 @@ class CrmService if (! $crmCustomer instanceof CrmCustomer) { throw $crmCustomer instanceof \Throwable ? $crmCustomer - : new UnexpectedValueException('CRM customer not found for hashcode: ' . (string) $customer->hashcode); + : new \UnexpectedValueException('CRM customer not found for hashcode: ' . (string) $customer->hashcode); } $updatedData = [ @@ -230,26 +230,30 @@ class CrmService $cacheKey = $this->getCustomerHashcodeCacheKey($hashcode->value); - /** @var null|CrmCustomer|CrmServiceException $result */ - $result = $this->cacheRepository->remember( - $cacheKey, - now()->addMinutes(15), - function () use ($hashcode): null | CrmCustomer | CrmServiceException { - try { - $customer = $this->crmApi->getCustomer($hashcode->value); + try { + /** @var null|CrmCustomer $result */ + $result = $this->cacheRepository->remember( + $cacheKey, + now()->addMinutes(15), + function () use ($hashcode): ?CrmCustomer { + try { + $customer = $this->crmApi->getCustomer($hashcode->value); - return $customer ? - $this->toAppCrmCustomer($customer) : - null; - } catch (ApiErrorException $e) { - if ($e->getApiError()->equals(ApiError::modelNotFound)) { - return null; + return $customer ? + $this->toAppCrmCustomer($customer) : + null; + } catch (ApiErrorException $e) { + if ($e->getApiError()->equals(ApiError::modelNotFound)) { + return null; + } + + throw $e; } - - return CrmServiceException::of(cause: $e); } - } - ); + ); + } catch (ApiErrorException | CrmException | \Exception $e) { + return CrmServiceException::of(cause: $e); + } $this->customerByHashcodeCache[$hashcode->value] = $result; @@ -266,26 +270,30 @@ class CrmService $cacheKey = $this->getCustomerEmailCacheKey($normalizedEmail); - /** @var null|CrmCustomer|CrmServiceException $result */ - $result = $this->cacheRepository->remember( - $cacheKey, - now()->addMinutes(15), - function () use ($normalizedEmail): null | CrmCustomer | CrmServiceException { - try { - $customer = $this->crmApi->getCustomer($normalizedEmail); + try { + /** @var null|CrmCustomer $result */ + $result = $this->cacheRepository->remember( + $cacheKey, + now()->addMinutes(15), + function () use ($normalizedEmail): ?CrmCustomer { + try { + $customer = $this->crmApi->getCustomer($normalizedEmail); - return $customer ? - $this->toAppCrmCustomer($customer) : - null; - } catch (ApiErrorException $e) { - if ($e->getApiError()->equals(ApiError::modelNotFound)) { - return null; + return $customer ? + $this->toAppCrmCustomer($customer) : + null; + } catch (ApiErrorException $e) { + if ($e->getApiError()->equals(ApiError::modelNotFound)) { + return null; + } + + throw $e; } - - return CrmServiceException::of(cause: $e); } - } - ); + ); + } catch (ApiErrorException | CrmException | \Exception $e) { + return CrmServiceException::of(cause: $e); + } $this->customerByEmailCache[$normalizedEmail] = $result; @@ -297,14 +305,7 @@ class CrmService */ 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); @@ -340,14 +341,7 @@ class CrmService */ 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); @@ -378,6 +372,46 @@ class CrmService } } + /** + * @throws \App\Exceptions\CrmServiceException + */ + public function deleteByHashcode(CrmHashcode $hashcode, ?Email $email = null): bool + { + $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]); + + return $customer->delete(); + } catch (ApiErrorException $e) { + if ($e->getApiError()->equals(ApiError::modelNotFound)) { + return true; + } + + throw CrmServiceException::of(cause: $e); + } catch (ValidationException | CrmException | \Exception $e) { + throw CrmServiceException::of(cause: $e); + } + } + /** @param array $andWith */ public function newAppCustomerFrom(CrmCustomer $existing, array $andWith = []): CrmCustomer { @@ -479,6 +513,20 @@ class CrmService $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/app/Services/DataTableService.php b/app/Services/DataTableService.php index dfbff089..c696cd03 100644 --- a/app/Services/DataTableService.php +++ b/app/Services/DataTableService.php @@ -8,10 +8,8 @@ use Illuminate\Contracts\Database\Query\Builder; use Illuminate\Contracts\Session\Session; use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator; -use Illuminate\Support\Facades\Schema; -use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; use Shared\Pagination\Pagination; -use SortDirection; class DataTableService { @@ -25,9 +23,13 @@ class DataTableService private const string CACHE_SORT_WAY_KEY = 'sort_way'; + /** + * @param \Closure(string): array $columnListingResolver + */ public function __construct( protected readonly Request $request, protected readonly Session $session, + protected readonly \Closure $columnListingResolver, ) { } @@ -36,7 +38,7 @@ class DataTableService * splitting search into words or using whole sentence * * @template TModel of \Illuminate\Database\Eloquent\Model - * @template TBuilder of \Illuminate\Contracts\Database\Query\Builder + * @template TBuilder of \Illuminate\Database\Eloquent\Builder * * @param class-string $modelClass * @param TBuilder $query @@ -83,7 +85,7 @@ class DataTableService private function hasTableColumn(string $table, string $column): bool { if (! isset(self::$columnsCache[$table])) { - self::$columnsCache[$table] = Schema::getColumnListing($table); + self::$columnsCache[$table] = ($this->columnListingResolver)($table); } return in_array($column, self::$columnsCache[$table], true); @@ -105,7 +107,7 @@ class DataTableService Builder $query, array $ignore = [], ?string $defaultSortCol = null, - SortDirection $defaultSortWay = SortDirection::Ascending, + \SortDirection $defaultSortWay = \SortDirection::Ascending, array $columnMap = [], ): Builder { $table = (new $modelClass())->getTable(); @@ -130,8 +132,8 @@ class DataTableService if ($sort_col && $sort_col !== 'undefined' && $sort_way && ! in_array($sort_col, $ignore) && $this->hasTableColumn($table, $dbCol)) { $direction = match ($sort_way) { - SortDirection::Descending => 'desc', - default => 'asc', + \SortDirection::Descending => 'desc', + default => 'asc', }; $query->orderBy("{$table}.{$dbCol}", $direction); @@ -141,7 +143,7 @@ class DataTableService $this->persistSortSession( $rName, self::ORDER_COLUMN, - SortDirection::Ascending + \SortDirection::Ascending ); } @@ -192,23 +194,24 @@ class DataTableService * @template TModel of \Illuminate\Database\Eloquent\Model * * @param class-string $modelClass - * @return string|array + * @return string|array */ private function getSearchValue( string $modelClass, string $search, string $field - ) { + ): array | string { $cast = (new $modelClass())->getCasts()[$field] ?? null; - if ($cast && class_exists($cast) && is_subclass_of($cast, BaseEnum::class)) { + if (is_string($cast) && is_subclass_of($cast, HasBaseEnum::class)) { $searchLower = mb_strtolower($search); + $cases = $cast::cases(); + return array_values(array_filter( - $cast::cases(), - fn ($item): bool => str_contains( - // @phpstan-ignore method.notFound (PhpStan cannot detect the label() method on BaseEnum cases) - mb_strtolower((string) $item->label()), + $cases, + static fn (HasBaseEnum $item): bool => str_contains( + mb_strtolower($item->label()), $searchLower ) )); @@ -230,11 +233,11 @@ class DataTableService 'sort_way' => $this->request->input( self::CACHE_SORT_WAY_KEY, $this->session->get("{$rName}." . self::CACHE_SORT_WAY_KEY) - ) === 'desc' ? SortDirection::Descending : SortDirection::Ascending, + ) === 'desc' ? \SortDirection::Descending : \SortDirection::Ascending, ]; } - public function persistSortSession(string $rName, ?string $sortCol, ?SortDirection $sortWay): void + public function persistSortSession(string $rName, ?string $sortCol, ?\SortDirection $sortWay): void { if ($this->request->has(self::CACHE_SORT_COL_KEY)) { $this->session->put("{$rName}." . self::CACHE_SORT_COL_KEY, $sortCol); @@ -242,8 +245,8 @@ class DataTableService if ($this->request->has(self::CACHE_SORT_WAY_KEY)) { $direction = match ($sortWay) { - SortDirection::Descending => 'desc', - default => 'asc', + \SortDirection::Descending => 'desc', + default => 'asc', }; $this->session->put("{$rName}." . self::CACHE_SORT_WAY_KEY, $direction); diff --git a/app/Services/EmployeeCsvReaderService.php b/app/Services/EmployeeCsvReaderService.php index e1a979cd..999e5102 100644 --- a/app/Services/EmployeeCsvReaderService.php +++ b/app/Services/EmployeeCsvReaderService.php @@ -60,7 +60,7 @@ class EmployeeCsvReaderService // * Trim lines. $csv->addFormatter(static fn (array $row): array => array_map( - static fn (?string $value): ?string => $value !== null ? mb_trim($value) : null, + static fn (mixed $value): ?string => is_string($value) ? mb_trim($value) : null, $row )); @@ -107,7 +107,7 @@ class EmployeeCsvReaderService /** * @param \League\Csv\Reader> $csv - * @return array + * @return array */ private function resolveHeaders(Reader $csv): array { @@ -130,8 +130,8 @@ class EmployeeCsvReaderService } /** - * @param array $headers - * @return array + * @param array $headers + * @return array */ private function normalizeHeaders(array $headers): array { diff --git a/app/Services/EmployeeSyncService.php b/app/Services/EmployeeSyncService.php index 6c042ecd..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,56 +36,89 @@ 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) { - $siteIdentifier = method_exists($siteCode, 'value') ? $siteCode->value : (string) $siteCode; + $siteSince = $since !== null ? Carbon::instance($since) : $this->resolveSinceForSite($siteCode); + $siteSyncStartedAt = Carbon::now(); - $this->logger->debug("Fetching employees for site: {$siteIdentifier}", [ - 'site' => $siteIdentifier, - 'since' => $sinceDate->format(Carbon::RFC3339), + $this->logger->debug("Fetching employees for site: {$siteCode->value}", [ + 'site' => $siteCode->value, + '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: {$siteIdentifier}", [ - 'site' => $siteIdentifier, + $this->logger->warning("Failed to fetch employees from Arcadia for site: {$siteCode->value}", [ + 'site' => $siteCode->value, ]); + $failedSites[] = $siteCode->value; continue; } - $this->logger->debug("Retrieved employees for site {$siteIdentifier}.", [ - 'site' => $siteIdentifier, + $this->logger->debug("Retrieved employees for site {$siteCode->value}.", [ + 'site' => $siteCode->value, '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); @@ -95,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/app/Services/IcsGeneratorService.php b/app/Services/IcsGeneratorService.php index 28925cbc..a9f781a7 100644 --- a/app/Services/IcsGeneratorService.php +++ b/app/Services/IcsGeneratorService.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Services; use App\Dto\IcsContentDto; +use Domain\Models\ValueObjects\IcsContent; class IcsGeneratorService { @@ -16,7 +17,7 @@ class IcsGeneratorService } } - public function generate(IcsContentDto $event): string + public function generate(IcsContentDto $event): IcsContent { $dateFormat = 'Ymd\THis\Z'; $lines = [ @@ -40,7 +41,7 @@ class IcsGeneratorService $lines[] = 'END:VCALENDAR'; // NOTE: ICS files must have CRLF line endings - return implode("\r\n", $lines) . "\r\n"; + return new IcsContent(implode("\r\n", $lines) . "\r\n"); } private function escape(string $text): string 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/Services/MailRegateService.php b/app/Services/MailRegateService.php new file mode 100644 index 00000000..1b9153a3 --- /dev/null +++ b/app/Services/MailRegateService.php @@ -0,0 +1,93 @@ +regateEmail = new Address(Config::string('mail.to.regate')); + } + + /** + * @param \Domain\Events\Dto\OrderPlacedLine[] $lines + * + * @throws \Domain\Exceptions\OrderTunnel\RegateExportFailedException + */ + #[\Override] + public function processOrder( + OrderReference $reference, + Matricule $employeeMatricule, + CarbonImmutable $pickupDay, + array $lines, + ): void { + $rows = []; + + foreach ($lines as $line) { + $rows[] = [ + (string) $line->productIncoId->value, + $employeeMatricule->value, + (string) $line->productIncoId->value, + 'commande ferme', + (string) $line->productOrderUnit->value, + $line->productOrderUnit->toRegateCode(), + '', + $pickupDay->format('d/m/Y'), + (string) $line->quantity, + (string) $reference, + ]; + } + + $csvContent = $this->csvGenerator->generate($this->header, $rows); + + $now = CarbonImmutable::now(); + $fileName = sprintf( + 'BTQ-%s-%s%s.csv', + $reference, + $now->format('Ymd_His'), + \microtime(true) + ); + + try { + $this->mailer->to($this->regateEmail) + ->send(new RegateOrderMail($csvContent, $fileName)); + } catch (\Throwable $e) { + throw new RegateExportFailedException($e->getMessage(), $e); + } + } +} diff --git a/app/Services/OrderService.php b/app/Services/OrderOwnershipService.php similarity index 96% rename from app/Services/OrderService.php rename to app/Services/OrderOwnershipService.php index 621b6a8f..74271e34 100644 --- a/app/Services/OrderService.php +++ b/app/Services/OrderOwnershipService.php @@ -9,7 +9,7 @@ use App\Models\Customer; use App\Models\Order; use Domain\Models\ValueObjects\Matricule; -class OrderService +class OrderOwnershipService { public function isOrderOwnedBy(Order | OrderDto $order, Customer $customer): bool { diff --git a/app/Services/ProductDtoAssemblerService.php b/app/Services/ProductDtoAssemblerService.php new file mode 100644 index 00000000..7ad2a190 --- /dev/null +++ b/app/Services/ProductDtoAssemblerService.php @@ -0,0 +1,143 @@ +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', 'inco', 'validDiscount']); + + $entities = []; + foreach ($models as $model) { + $entities[(string) $model->id] = $this->productRepository->toEntity($model); + } + + return [$models, $entities]; + } + + /** + * @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/app/Services/PublicHolidaysApiService.php b/app/Services/PublicHolidaysApiService.php new file mode 100644 index 00000000..c39a2255 --- /dev/null +++ b/app/Services/PublicHolidaysApiService.php @@ -0,0 +1,65 @@ + + */ + public function fetchForYear(int $year): array + { + Assert::greaterThanEq($year, 2026); + + $url = str_replace(':year', strval($year), self::CALENDAR_API_URL); + $response = Http::timeout(self::API_CALL_TIMEOUT_SECONDS)->get($url); + + throw_unless( + $response->successful(), + \UnexpectedValueException::class, + 'Failed to fetch calendar from api' + ); + + $outputList = $response + ->collect() + ->map(fn ($label, $date): array => [ + 'date' => $date, + 'label' => $label, + ])->values()->all(); + + $validator = Validator::make($outputList, [ + '*' => 'array', + '*.date' => ['required', 'date'], + '*.label' => ['required', 'string'], + ]); + + if ($validator->fails()) { + throw new \UnexpectedValueException( + 'Invalid response: ' . json_encode($validator->errors()->messages()) + ); + } + + $timezone = new \DateTimeZone('Europe/Paris'); + + return array_values(array_map( + fn (array $entry): PublicHolidayDto => new PublicHolidayDto( + date: CarbonImmutable::parse(Arr::string($entry, 'date'), $timezone), + label: Arr::string($entry, 'label'), + ), + $outputList + )); + } +} diff --git a/app/Services/PublicImageStorageService.php b/app/Services/PublicImageStorageService.php new file mode 100644 index 00000000..6c66c3d6 --- /dev/null +++ b/app/Services/PublicImageStorageService.php @@ -0,0 +1,45 @@ +imageOptimizerService->optimize($file); + + return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk); + } + + public function deleteIfReplaced( + ?StorageFilePath $oldPath, + ?StorageFilePath $newPath, + ): void { + if ($oldPath === null || $newPath === null || $oldPath->value === $newPath->value) { + return; + } + + $this->deleteIfExists($oldPath); + } + + public function deleteIfExists(?StorageFilePath $path): void + { + if ($path !== null && $this->storageService->fileExistsOnDisk($path, $this->s3Disk->disk)) { + $this->storageService->removeFromDisk($path, $this->s3Disk->disk); + } + } +} diff --git a/app/Services/StatsService.php b/app/Services/StatsService.php index c512c235..61d19393 100644 --- a/app/Services/StatsService.php +++ b/app/Services/StatsService.php @@ -4,20 +4,25 @@ declare(strict_types=1); namespace App\Services; -use App\Contracts\Directories\EmployeeDirectory; -use App\Contracts\Directories\OrderDirectory; +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; use Domain\Enums\StatsCustomerType; use Domain\Enums\StatsShopType; -use Illuminate\Support\Collection; +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Support\Facades\Date; +use Money\Currency; +use Money\Money; class StatsService { public function __construct( - private readonly EmployeeDirectory $employeeDirectory, - private readonly OrderDirectory $orderDirectory + private readonly Currency $currency, ) { } @@ -104,7 +109,7 @@ class StatsService $current = $this->getMembershipRate($start, $end); break; default: - throw new \InvalidArgumentException("Unknown stats type: {$type->label()}"); + throw new \InvalidArgumentException('Unknown stats type: ' . gettype($type)); } $stats[$type->value] = [ @@ -125,7 +130,7 @@ class StatsService $registered = $this->getActiveEmployeesCountWithAnAccount($start, $end); $employee = $this->getActiveEmployeesCount($start, $end); - return $employee ? round($registered / $employee * 100, 2) : 0.0; + return $employee !== 0 ? round($registered / $employee * 100, 2) : 0.0; } /** @@ -146,10 +151,15 @@ class StatsService */ public function getMembershipPercentage(): float { - $employee = $this->employeeDirectory->countActiveEmployees(); - $registered = $this->employeeDirectory->countActiveRegisteredEmployees(); + $employee = Employee::query() + ->active() + ->count(); + $registered = Employee::query() + ->active() + ->whereHas('customer') + ->count(); - return $employee ? round($registered / $employee * 100, 2) : 0.0; + return $employee !== 0 ? round($registered / $employee * 100, 2) : 0.0; } /** @@ -157,7 +167,11 @@ class StatsService */ private function getActiveEmployeesCount(CarbonInterface $start, CarbonInterface $end): int { - return $this->employeeDirectory->countActiveEmployeesWithin($start, $end); + return Employee::query() + ->active() + ->whereDate('created_at', '>=', $start) + ->whereDate('created_at', '<=', $end) + ->count(); } /** @@ -165,17 +179,12 @@ class StatsService */ private function getActiveEmployeesCountWithAnAccount(CarbonInterface $start, CarbonInterface $end): int { - return $this->employeeDirectory->countActiveRegisteredEmployeesWithin($start, $end); - } - - /** - * Get all validated orders. - * - * @return Collection - */ - private function getValidatedOrders(CarbonInterface $start, CarbonInterface $end): Collection - { - return $this->orderDirectory->getValidatedOrders($start, $end); + return Employee::query() + ->active() + ->whereHas('customer') + ->whereDate('created_at', '>=', $start) + ->whereDate('created_at', '<=', $end) + ->count(); } /** @@ -183,7 +192,7 @@ class StatsService */ private function getNbValidateCmd(CarbonInterface $start, CarbonInterface $end): int { - return $this->getValidatedOrders($start, $end)->count(); + return $this->countOrdersByStatus(OrderStatus::VALIDATED, $start, $end); } /** @@ -191,7 +200,16 @@ class StatsService */ private function getNbWaitingCmd(CarbonInterface $start, CarbonInterface $end): int { - return $this->getOrdersByStatus(OrderStatus::WAITING, $start, $end)->count(); + $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; } /** @@ -199,17 +217,15 @@ class StatsService */ private function getNbCanceledCmd(CarbonInterface $start, CarbonInterface $end): int { - return $this->getOrdersByStatus(OrderStatus::CANCELED, $start, $end)->count(); + return $this->countOrdersByStatus(OrderStatus::CANCELED, $start, $end); } - /** - * Get orders by status. - * - * @return Collection - */ - private function getOrdersByStatus(OrderStatus $statusId, CarbonInterface $start, CarbonInterface $end): Collection + private function countOrdersByStatus(OrderStatus $status, CarbonInterface $start, CarbonInterface $end): int { - return $this->orderDirectory->getOrdersByStatus($statusId, $start, $end); + return Order::query() + ->where('status', $status->value) + ->whereCreatedAtBetween($start, $end) + ->count(); } /** @@ -258,11 +274,29 @@ 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 { - return $this->orderDirectory->getNbActiveClients($start, $end); + $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) + ->filter() + ->unique(); + + if ($matricules->isEmpty()) { + return 0; + } + + return Customer::query() + ->whereHas('employee', function (Builder $query) use ($matricules): void { + $query->whereIn('matricule', $matricules); + })->count(); } /** @@ -270,7 +304,17 @@ class StatsService */ private function getNbCmdWith7DayDelay(CarbonInterface $start, CarbonInterface $end): int { - return $this->orderDirectory->getNbCmdWith7DayDelay($start, $end); + return Order::query() + ->where('status', OrderStatus::VALIDATED->value) + ->whereCreatedAtBetween($start, $end) + ->get() + ->filter(function (Order $order): bool { + if (is_null($order->pickup_day) || is_null($order->created_at)) { + return false; + } + + return $order->pickup_day->lessThanOrEqualTo($order->created_at->modify('+7 day')); + })->count(); } /** @@ -278,7 +322,20 @@ class StatsService */ private function getNbCmdWith14DayDelay(CarbonInterface $start, CarbonInterface $end): int { - return $this->orderDirectory->getNbCmdWith14DayDelay($start, $end); + return Order::query() + ->where('status', OrderStatus::VALIDATED->value) + ->whereCreatedAtBetween($start, $end) + ->get() + ->filter(function (Order $order): bool { + if (is_null($order->pickup_day) || is_null($order->created_at)) { + return false; + } + + return Date::create($order->pickup_day)->betweenIncluded( + Date::create($order->created_at->modify('+8 day')), + Date::create($order->created_at->modify('+14 day')) + ); + })->count(); } /** @@ -286,7 +343,14 @@ class StatsService */ private function getCaHt(CarbonInterface $start, CarbonInterface $end): float { - return $this->orderDirectory->getCaHt($start, $end); + $totalCaHt = OrderLine::query()->whereHas('order', function (Builder $query) use ($start, $end): void { + $query->where('status', OrderStatus::VALIDATED->value) + ->whereCreatedAtBetween($start, $end); + })->sum('total_ht'); + + $amount = is_numeric($totalCaHt) ? (int) $totalCaHt : 0; + + return ((float) (new Money($amount, $this->currency))->getAmount()) / 100; } /** @@ -294,7 +358,14 @@ class StatsService */ private function getCaTtc(CarbonInterface $start, CarbonInterface $end): float { - return $this->orderDirectory->getCaTtc($start, $end); + $totalCaTtc = OrderLine::query()->whereHas('order', function (Builder $query) use ($start, $end): void { + $query->where('status', OrderStatus::VALIDATED->value) + ->whereCreatedAtBetween($start, $end); + })->sum('total_ttc'); + + $amount = is_numeric($totalCaTtc) ? (int) $totalCaTtc : 0; + + return ((float) (new Money($amount, $this->currency))->getAmount()) / 100; } /** @@ -302,9 +373,11 @@ class StatsService */ private function getAverageBasketHt(CarbonInterface $start, CarbonInterface $end): float { + $nbValidateCmd = $this->getNbValidateCmd($start, $end); + // Prevent division by 0. - if ($this->getNbValidateCmd($start, $end) !== 0) { - return round($this->getCaHt($start, $end) / $this->getNbValidateCmd($start, $end), 2); + if ($nbValidateCmd !== 0) { + return round($this->getCaHt($start, $end) / $nbValidateCmd, 2); } return 0.0; @@ -319,9 +392,14 @@ class StatsService // Prevent division by 0. if ($nbValidateCmd !== 0) { - $totalQty = $this->orderDirectory->getTotalQuantity($start, $end); + $totalQty = OrderLine::query()->whereHas('order', function (Builder $query) use ($start, $end): void { + $query->where('status', OrderStatus::VALIDATED->value) + ->whereCreatedAtBetween($start, $end); + })->sum('quantity'); - return round((float) $totalQty / $nbValidateCmd, 2); + $qty = is_numeric($totalQty) ? (float) $totalQty : 0.0; + + return round($qty / $nbValidateCmd, 2); } return 0.0; diff --git a/app/Traits/Controllers/ChangesModelOrder.php b/app/Traits/Controllers/ChangesModelOrder.php index 628b5be7..228b328d 100644 --- a/app/Traits/Controllers/ChangesModelOrder.php +++ b/app/Traits/Controllers/ChangesModelOrder.php @@ -15,6 +15,9 @@ use App\Services\FlashMessageService; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\RedirectResponse; +/** + * @mixin \Illuminate\Routing\Controller + */ trait ChangesModelOrder { public function changeOrder( @@ -24,6 +27,8 @@ trait ChangesModelOrder Executor $executor, FlashMessageService $flashMessageService ): RedirectResponse { + $this->authorize('update', $model); + $direction = $request->getSortDirection(); $changed = $executor->execute($action, new ChangeModelOrderInput($model, $direction)); @@ -46,6 +51,8 @@ trait ChangesModelOrder Executor $executor, FlashMessageService $flashMessageService ): RedirectResponse { + $this->authorize('update', $model); + $changed = $executor->execute( $action, $request->toChangeModelOrderPositionInput($model) diff --git a/app/Traits/Models/HasUuidV7AsPrimaryKey.php b/app/Traits/Models/HasUuidV7AsPrimaryKey.php index 3ab37bb1..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() @@ -38,8 +37,8 @@ trait HasUuidV7AsPrimaryKey protected function createdAt(): Attribute { return Attribute::make( - get: fn (): ?CarbonInterface => $this->{$this->getKeyName()} - ? CarbonImmutable::instance(UuidV7::fromString($this->{$this->getKeyName()})->getDateTime()) + get: fn (): ?CarbonInterface => is_string($this->{$this->getKeyName()}) + ? CarbonImmutable::instance(UuidHelper::toDateTime(UuidHelper::fromString($this->{$this->getKeyName()}))) : null, ); } diff --git a/app/Traits/Models/IsCachedAsCollection.php b/app/Traits/Models/IsCachedAsCollection.php index 212b618f..2c93ba09 100644 --- a/app/Traits/Models/IsCachedAsCollection.php +++ b/app/Traits/Models/IsCachedAsCollection.php @@ -9,11 +9,11 @@ use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Facades\Cache; /** - * ! Use this only on limited elements, (not on tags, or products, or posts for ex.) + * ! Use this only on limited elements (not on tags, products, or posts, for example). * * @template TModel of \Illuminate\Database\Eloquent\Model * - * @property array $cacheConditions + * @phpstan-require-extends \Illuminate\Database\Eloquent\Model * * @mixin \Illuminate\Database\Eloquent\Model */ @@ -21,30 +21,34 @@ trait IsCachedAsCollection { public static function bootIsCachedAsCollection(): void { - $flush = fn () => static::removeCached(); + $flush = static fn () => static::removeCached(); static::saved($flush); static::deleted($flush); } /** - * @return \Illuminate\Database\Eloquent\Collection + * @return Collection */ public static function getCached(): Collection { - /** @var \Illuminate\Database\Eloquent\Collection */ - return Cache::remember(static::getCacheKeyName(), 48 * 60 * 60, function () { - $query = static::query(); + return Cache::remember( + static::getCacheKeyName(), + 48 * 60 * 60, + function () { + $query = static::query(); - if (property_exists(static::class, 'cacheConditions')) { - // @phpstan-ignore property.staticAccess - $query->where(static::$cacheConditions); + $cacheConditions = static::getCacheConditions(); + + if ($cacheConditions !== []) { + $query->where($cacheConditions); + } + + $results = static::queryCached($query)->get(); + + return static::filterQuery($results); } - - $results = static::queryCached($query)->get(); - - return static::filterQuery($results); - }); + ); } public static function removeCached(): void @@ -53,8 +57,16 @@ trait IsCachedAsCollection } /** - * @param \Illuminate\Database\Eloquent\Builder $query - * @return \Illuminate\Database\Eloquent\Builder + * @return array + */ + protected static function getCacheConditions(): array + { + return []; + } + + /** + * @param Builder $query + * @return Builder */ protected static function queryCached(Builder $query): Builder { @@ -62,8 +74,8 @@ trait IsCachedAsCollection } /** - * @param \Illuminate\Database\Eloquent\Collection $results - * @return \Illuminate\Database\Eloquent\Collection + * @param Collection $results + * @return Collection */ protected static function filterQuery(Collection $results): Collection { diff --git a/app/Traits/Requests/ConvertsClientDatesToUtc.php b/app/Traits/Requests/ConvertsClientDatesToUtc.php new file mode 100644 index 00000000..89a31af8 --- /dev/null +++ b/app/Traits/Requests/ConvertsClientDatesToUtc.php @@ -0,0 +1,36 @@ +setTimezone('UTC')->format('Y-m-d H:i:s'); + } + + protected function mergeLocalDatetimeAsUtc(string $field, string $timezoneField = 'client_timezone', string $format = 'Y-m-d\TH:i'): void + { + if (! $this->filled($field)) { + return; + } + + $this->merge([ + $field => $this->convertLocalDatetimeToUtc( + value: $this->string($field)->value(), + timezone: $this->string($timezoneField)->value(), + format: $format, + ), + ]); + } +} 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/Traits/TracksPendingStoragePaths.php b/app/Traits/TracksPendingStoragePaths.php new file mode 100644 index 00000000..1fab0964 --- /dev/null +++ b/app/Traits/TracksPendingStoragePaths.php @@ -0,0 +1,75 @@ +> */ + private array $pendingUploadedPaths = []; + + /** @var array> */ + private array $pendingObsoletePaths = []; + + protected function trackUploadedPath(ActionInput $input, StorageFilePath $path): void + { + $key = spl_object_id($input); + $this->pendingUploadedPaths[$key][] = $path; + } + + protected function trackReplacedPath( + ActionInput $input, + ?StorageFilePath $oldPath, + ?StorageFilePath $newPath, + ): void { + if ($oldPath === null || $newPath === null || $oldPath->value === $newPath->value) { + return; + } + + $this->trackObsoletePath($input, $oldPath); + } + + protected function trackObsoletePath(ActionInput $input, ?StorageFilePath $path): void + { + if ($path === null) { + return; + } + + $key = spl_object_id($input); + $this->pendingObsoletePaths[$key][] = $path; + } + + /** + * @return list<\Uwil\Storage\Lib\ValueObjects\StorageFilePath> + */ + protected function pullUploadedPaths(ActionInput $input): array + { + $key = spl_object_id($input); + $paths = $this->pendingUploadedPaths[$key] ?? []; + $this->clearTrackedPaths($input); + + return $paths; + } + + /** + * @return list<\Uwil\Storage\Lib\ValueObjects\StorageFilePath> + */ + protected function pullObsoletePaths(ActionInput $input): array + { + $key = spl_object_id($input); + $paths = $this->pendingObsoletePaths[$key] ?? []; + $this->clearTrackedPaths($input); + + return $paths; + } + + protected function clearTrackedPaths(ActionInput $input): void + { + $key = spl_object_id($input); + unset($this->pendingUploadedPaths[$key], $this->pendingObsoletePaths[$key]); + } +} 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/bootstrap/jobs.php b/bootstrap/jobs.php index f83dddf0..065f1c06 100644 --- a/bootstrap/jobs.php +++ b/bootstrap/jobs.php @@ -3,10 +3,11 @@ 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; -use App\Jobs\UpsertShopsPickupExceptionsUsingApiForYear; use Domain\Services\PickupSchedulingService; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Support\Facades\Date; @@ -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'); @@ -34,7 +36,7 @@ return function (Schedule $schedule): void { return $now->isSameHour($pickupReminderAt); }); - $schedule->job(UpsertShopsPickupExceptionsUsingApiForYear::class) + $schedule->job(EnsurePublicHolidaysSyncedJob::class) ->onOneServer() - ->yearlyOn(11, 1, '7:30'); + ->dailyAt('07:30'); }; diff --git a/bootstrap/middlewares.php b/bootstrap/middlewares.php index c0a5e3e2..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) { @@ -44,11 +44,17 @@ $redirectUsers = function (Request $request) { 'backend' => route('bo.dashboard'), 'frontend' => route('fo.pages.home'), ]; - foreach ($request->route()->gatherMiddleware() as $middleware) { - if (\is_string($middleware) && str_contains($middleware, 'auth:')) { - $route = $logins[str_replace('auth:', '', $middleware)] ?? null; - if ($route) { - return $route; + foreach ($request->route()?->gatherMiddleware() ?? [] as $middleware) { + if (! \is_string($middleware)) { + continue; + } + + foreach (['auth:', 'guest:'] as $prefix) { + if (str_starts_with($middleware, $prefix)) { + $route = $logins[substr($middleware, strlen($prefix))] ?? null; + if ($route) { + return $route; + } } } } @@ -57,7 +63,10 @@ $redirectUsers = function (Request $request) { }; return function (Middleware $middleware) use ($redirectGuests, $redirectUsers): void { - $middleware->trustProxies(at: '*'); + $middleware->trustProxies( + at: '*', + headers: Request::HEADER_X_FORWARDED_TRAEFIK, + ); $middleware->redirectGuestsTo($redirectGuests); $middleware->redirectUsersTo($redirectUsers); diff --git a/composer.json b/composer.json index 8496325d..f0cd5fa9 100644 --- a/composer.json +++ b/composer.json @@ -11,22 +11,26 @@ "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", "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", "mews/purifier": "^3.3", "moneyphp/money": "^4.9", "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": "^7.0", + "uwil/sitemap-generator": "^8.1", + "uwil/storage-laravel": "^1.0", "webmozart/assert": "^2.4" }, "require-dev": { @@ -40,12 +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", - "phpunit/phpunit": "^12.5", + "phpstan/phpstan-mockery": "^2.0", + "phpstan/phpstan-webmozart-assert": "^2.0", + "phpunit/phpunit": "^13.0", "slevomat/coding-standard": "^8.30", "spatie/laravel-ignition": "^2.0" }, @@ -76,6 +83,9 @@ } }, "autoload": { + "files": [ + "app/helpers.php" + ], "psr-4": { "App\\": "app/", "Domain\\": "domain/", @@ -103,6 +113,7 @@ ], "analyse": "vendor/bin/phpstan analyse", "format": "vendor/bin/pint", + "lint": "vendor/bin/parallel-lint --exclude vendor --exclude storage --exclude bootstrap --exclude node_modules . && vendor/bin/phpcs && vendor/bin/phpstan analyse && vendor/bin/pint -p --test", "post-autoload-dump": [ "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump", "@php artisan package:discover --ansi" diff --git a/composer.lock b/composer.lock index 4a7eac48..7f59fa21 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": "fea842f5762664def28aca119e4486ac", "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.5", + "source": { + "type": "git", + "url": "https://github.com/aws/aws-sdk-php.git", + "reference": "6e52905dabd868c1bc7fd491e0deec6f78a0f7d1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/6e52905dabd868c1bc7fd491e0deec6f78a0f7d1", + "reference": "6e52905dabd868c1bc7fd491e0deec6f78a0f7d1", + "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.5" + }, + "time": "2026-11-12T19:40:30+00:00" + }, { "name": "axlon/laravel-postal-code-validation", "version": "v3.10.0", @@ -130,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", @@ -204,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", @@ -284,16 +437,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 +498,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 +510,7 @@ "type": "github" } ], - "time": "2026-10-05T13:12:12+00:00" + "time": "2026-10-29T09:13:34+00:00" }, { "name": "dflydev/dot-access-data", @@ -432,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", @@ -506,23 +660,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 +730,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 +746,8 @@ "type": "tidelift" } ], - "time": "2025-08-10T19:31:58+00:00" + "time": "2026-10-26T08:14:14+00:00", + "published-time": "2026-10-26T20:06:59+00:00" }, { "name": "doctrine/lexer", @@ -667,20 +822,21 @@ "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", - "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 +847,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 +879,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 +887,32 @@ "type": "github" } ], - "time": "2025-10-31T18:51:33+00:00" + "time": "2026-10-19T17:53:57+00:00", + "published-time": "2026-10-19T17:54:31+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 +935,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 +982,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", @@ -894,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", @@ -1079,20 +1237,21 @@ "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", - "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 +1316,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", @@ -1219,26 +1378,27 @@ "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", - "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 +1491,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 +1507,21 @@ "type": "tidelift" } ], - "time": "2026-08-24T09:21:06+00:00" + "time": "2026-10-25T21:35:21+00:00", + "published-time": "2026-10-25T21:37:23+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 +1576,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 +1592,21 @@ "type": "tidelift" } ], - "time": "2026-08-24T09:11:28+00:00" + "time": "2026-10-18T12:46:59+00:00", + "published-time": "2026-10-18T12:47:39+00:00" }, { "name": "guzzlehttp/psr7", - "version": "2.13.1", + "version": "2.13.3", "source": { "type": "git", "url": "https://github.com/guzzle/psr7.git", - "reference": "95e7828100de18b4e269fb1703be530082d5166d" + "reference": "6d3cd8285a97eaa352956a4ada92fa03ecce1c4e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/psr7/zipball/95e7828100de18b4e269fb1703be530082d5166d", - "reference": "95e7828100de18b4e269fb1703be530082d5166d", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/6d3cd8285a97eaa352956a4ada92fa03ecce1c4e", + "reference": "6d3cd8285a97eaa352956a4ada92fa03ecce1c4e", "shasum": "" }, "require": { @@ -1534,7 +1696,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.3" }, "funding": [ { @@ -1550,7 +1712,8 @@ "type": "tidelift" } ], - "time": "2026-08-24T09:13:11+00:00" + "time": "2026-11-12T15:57:42+00:00", + "published-time": "2026-11-12T15:58:42+00:00" }, { "name": "guzzlehttp/uri-template", @@ -1636,7 +1799,152 @@ "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", + "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", @@ -1696,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", @@ -1746,16 +2055,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 +2085,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 +2167,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 +2181,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 +2197,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 +2211,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 +2283,21 @@ "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", + "published-time": "2026-11-10T15:55:04+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 +2340,23 @@ ], "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", + "published-time": "2026-11-09T16:09:07+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 +2404,21 @@ "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", + "published-time": "2026-11-10T16:11:08+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 +2426,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 +2471,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 +2592,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 +2695,8 @@ "type": "tidelift" } ], - "time": "2026-09-21T13:07:34+00:00" + "time": "2026-10-31T13:35:37+00:00", + "published-time": "2026-10-31T13:35:57+00:00" }, { "name": "league/config", @@ -2465,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", @@ -2643,7 +2957,63 @@ "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", + "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", @@ -2692,7 +3062,54 @@ "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", + "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", @@ -2748,24 +3165,26 @@ "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", - "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 +3257,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 +3265,21 @@ "type": "github" } ], - "time": "2026-03-15T20:22:25+00:00" + "time": "2026-11-04T12:45:07+00:00", + "published-time": "2026-11-04T13:02:21+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 +3342,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 +3350,8 @@ "type": "github" } ], - "time": "2026-03-08T20:05:35+00:00" + "time": "2026-11-04T12:45:07+00:00", + "published-time": "2026-11-04T13:02:27+00:00" }, { "name": "maatwebsite/excel", @@ -2938,12 +3359,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 +3441,7 @@ "type": "github" } ], - "time": "2026-09-14T12:30:46+00:00" + "time": "2026-11-11T14:35:24+00:00" }, { "name": "maennchen/zipstream-php", @@ -3207,82 +3628,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", @@ -3363,16 +3708,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 +3751,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 +3800,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 +3847,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 +3895,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 +3943,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 +3991,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 +4036,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", @@ -3787,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": { @@ -3876,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": [ { @@ -3888,20 +4233,87 @@ "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": "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 +4323,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 +4406,38 @@ "type": "tidelift" } ], - "time": "2026-10-02T07:26:52+00:00" + "time": "2026-10-25T14:32:48+00:00", + "published-time": "2026-10-25T14:41:05+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 +4458,41 @@ { "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", + "published-time": "2026-10-22T02:14:45+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 +4564,10 @@ ], "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", + "published-time": "2026-10-20T17:48:30+00:00" }, { "name": "nikic/php-parser", @@ -4208,35 +4624,36 @@ "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", - "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 +4696,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 +4712,8 @@ "type": "github" } ], - "time": "2026-02-16T23:10:27+00:00" + "time": "2026-11-07T03:57:16+00:00", + "published-time": "2026-11-07T04:01:24+00:00" }, { "name": "nyholm/psr7", @@ -4443,36 +4861,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 +4934,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 +4959,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "1.0.x-dev" + "dev-main": "1.6.x-dev" } }, "autoload": { @@ -4568,29 +4992,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 +5023,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 +5048,7 @@ ] }, "branch-alias": { - "dev-main": "1.14.x-dev" + "dev-main": "1.16.x-dev" } }, "autoload": { @@ -4668,20 +5091,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 +5148,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 +5217,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", @@ -4844,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", @@ -4979,16 +5403,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 +5435,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 +5510,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", @@ -5161,20 +5639,21 @@ "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", - "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 +5734,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 +5750,7 @@ "type": "tidelift" } ], - "time": "2026-08-26T12:13:21+00:00" + "time": "2026-11-02T10:45:48+00:00" }, { "name": "propaganistas/laravel-phone", @@ -5391,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", @@ -5444,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", @@ -5494,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", @@ -5546,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", @@ -5601,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", @@ -5654,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", @@ -5704,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", @@ -5755,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", @@ -5878,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", @@ -5954,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": { @@ -5979,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.", @@ -6030,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", @@ -6207,16 +6696,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 +6734,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 +6777,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 +6789,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 +6823,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 +6869,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 +6881,7 @@ "type": "custom" } ], - "time": "2026-09-23T14:29:19+00:00" + "time": "2026-11-11T19:17:46+00:00" }, { "name": "spatie/crawler", @@ -6611,23 +7100,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 +7144,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 +7156,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 +7193,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 +7252,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 +7272,21 @@ "type": "tidelift" } ], - "time": "2026-05-29T05:06:50+00:00" + "time": "2026-10-12T14:32:04+00:00", + "published-time": "2026-10-14T06:48:32+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 +7353,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 +7373,21 @@ "type": "tidelift" } ], - "time": "2026-09-18T16:00:27+00:00" + "time": "2026-11-04T07:07:11+00:00", + "published-time": "2026-11-04T11:31:39+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 +7423,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 +7443,21 @@ "type": "tidelift" } ], - "time": "2026-08-23T10:06:25+00:00" + "time": "2026-10-18T14:56:39+00:00", + "published-time": "2026-10-28T18:24:46+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 +7470,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -7003,7 +7495,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 +7515,21 @@ "type": "tidelift" } ], - "time": "2026-06-05T06:23:12+00:00" + "time": "2026-09-16T14:15:10+00:00", + "published-time": "2026-11-04T11:25:34+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 +7566,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 +7586,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 +7647,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 +7667,8 @@ "type": "tidelift" } ], - "time": "2026-09-22T18:58:53+00:00" + "time": "2026-10-25T14:40:25+00:00", + "published-time": "2026-10-28T18:24:13+00:00" }, { "name": "symfony/event-dispatcher", @@ -7260,20 +7754,21 @@ "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", - "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 +7782,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -7320,7 +7815,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 +7835,92 @@ "type": "tidelift" } ], - "time": "2026-06-05T06:23:12+00:00" + "time": "2026-09-16T14:15:10+00:00", + "published-time": "2026-11-04T11:25:36+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 +7955,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 +7975,21 @@ "type": "tidelift" } ], - "time": "2026-09-26T06:33:49+00:00" + "time": "2026-11-02T10:58:30+00:00", + "published-time": "2026-11-04T11:31:20+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 +8037,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 +8057,21 @@ "type": "tidelift" } ], - "time": "2026-09-24T07:13:53+00:00" + "time": "2026-11-04T08:39:20+00:00", + "published-time": "2026-11-04T11:31:54+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 +8148,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 +8168,21 @@ "type": "tidelift" } ], - "time": "2026-09-29T14:08:01+00:00" + "time": "2026-11-04T11:29:46+00:00", + "published-time": "2026-11-04T11:32:19+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 +8229,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 +8249,21 @@ "type": "tidelift" } ], - "time": "2026-09-15T06:01:24+00:00" + "time": "2026-10-23T17:06:53+00:00", + "published-time": "2026-10-28T18:23:52+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 +8316,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 +8336,21 @@ "type": "tidelift" } ], - "time": "2026-09-04T11:02:17+00:00" + "time": "2026-10-28T17:58:38+00:00", + "published-time": "2026-10-28T18:23:55+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 +8388,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 +8408,7 @@ "type": "tidelift" } ], - "time": "2026-05-29T05:06:50+00:00" + "time": "2026-10-18T14:56:39+00:00" }, { "name": "symfony/polyfill-ctype", @@ -7919,20 +8491,21 @@ "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", - "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 +8554,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 +8574,8 @@ "type": "tidelift" } ], - "time": "2026-09-25T15:46:47+00:00" + "time": "2026-10-15T09:18:53+00:00", + "published-time": "2026-10-28T10:07:44+00:00" }, { "name": "symfony/polyfill-intl-idn", @@ -8088,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", @@ -8173,20 +8748,21 @@ "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", - "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 +8814,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 +8834,8 @@ "type": "tidelift" } ], - "time": "2026-09-24T15:19:04+00:00" + "time": "2026-10-28T09:35:49+00:00", + "published-time": "2026-10-28T10:07:45+00:00" }, { "name": "symfony/polyfill-php80", @@ -8342,87 +8919,8 @@ "type": "tidelift" } ], - "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" + "time": "2026-09-25T15:50:05+00:00", + "published-time": "2026-09-30T10:23:35+00:00" }, { "name": "symfony/polyfill-php84", @@ -8502,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": { @@ -8562,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": [ { @@ -8582,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", @@ -8662,7 +9162,92 @@ "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", + "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", + "published-time": "2026-08-24T11:45:15+00:00" }, { "name": "symfony/polyfill-uuid", @@ -8745,20 +9330,21 @@ "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", - "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 +9376,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 +9396,21 @@ "type": "tidelift" } ], - "time": "2026-09-02T12:40:29+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", - "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 +9464,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 +9484,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 +9544,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 +9564,21 @@ "type": "tidelift" } ], - "time": "2026-09-28T19:13:15+00:00" + "time": "2026-11-04T08:39:20+00:00", + "published-time": "2026-11-04T11:30:59+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 +9596,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -9044,7 +9632,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 +9652,21 @@ "type": "tidelift" } ], - "time": "2026-07-27T15:39:01+00:00" + "time": "2026-10-20T17:38:25+00:00", + "published-time": "2026-11-04T11:25:33+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 +9723,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 +9743,21 @@ "type": "tidelift" } ], - "time": "2026-09-11T14:51:16+00:00" + "time": "2026-10-23T17:06:53+00:00", + "published-time": "2026-10-28T18:24:27+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 +9817,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 +9837,21 @@ "type": "tidelift" } ], - "time": "2026-08-21T17:47:34+00:00" + "time": "2026-11-01T22:27:46+00:00", + "published-time": "2026-11-04T11:31:54+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 +9864,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -9309,7 +9900,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 +9920,21 @@ "type": "tidelift" } ], - "time": "2026-06-05T06:23:12+00:00" + "time": "2026-10-03T08:17:19+00:00", + "published-time": "2026-11-04T11:25:31+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 +9979,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 +9999,21 @@ "type": "tidelift" } ], - "time": "2026-09-23T17:45:45+00:00" + "time": "2026-10-12T14:32:04+00:00", + "published-time": "2026-10-14T06:48:53+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 +10067,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 +10087,8 @@ "type": "tidelift" } ], - "time": "2026-09-03T16:02:27+00:00" + "time": "2026-10-26T21:55:04+00:00", + "published-time": "2026-10-28T18:25:26+00:00" }, { "name": "tbachert/spi", @@ -9601,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", @@ -9715,67 +10310,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", @@ -9851,6 +10385,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", @@ -9911,27 +10518,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": { @@ -9945,20 +10563,160 @@ "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": "vlucas/phpdotenv", - "version": "v5.7.0", + "name": "uwil/storage-laravel", + "version": "1.0.3", "source": { "type": "git", - "url": "https://github.com/vlucas/phpdotenv.git", - "reference": "301c07936b16d88628b126b01d082ba153cf4c40" + "url": "git@lab.s-web.fr:ldc-web/projets/file-storage-service.git", + "reference": "516350ecf66e80d0ac8a7ef3198cce07e52d515a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/301c07936b16d88628b126b01d082ba153cf4c40", - "reference": "301c07936b16d88628b126b01d082ba153cf4c40", + "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", + "source": { + "type": "git", + "url": "https://github.com/phpdotenv/phpdotenv.git", + "reference": "96149103e62ac67e915f6d2ef59b72dee2e011e0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpdotenv/phpdotenv/zipball/96149103e62ac67e915f6d2ef59b72dee2e011e0", + "reference": "96149103e62ac67e915f6d2ef59b72dee2e011e0", "shasum": "" }, "require": { @@ -9985,7 +10743,7 @@ "forward-command": false }, "branch-alias": { - "dev-master": "5.6-dev" + "dev-master": "5.8-dev" } }, "autoload": { @@ -10016,8 +10774,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 +10787,8 @@ "type": "tidelift" } ], - "time": "2026-08-24T18:07:49+00:00" + "time": "2026-10-25T16:26:19+00:00", + "published-time": "2026-10-25T16:26:50+00:00" }, { "name": "voku/portable-ascii", @@ -10103,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": { @@ -10167,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": [ @@ -10279,16 +11040,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 +11086,7 @@ ] }, "branch-alias": { - "dev-master": "3.6-dev" + "dev-master": "3.7-dev" } }, "autoload": { @@ -10358,7 +11119,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 +11131,7 @@ "type": "github" } ], - "time": "2026-03-17T14:12:51+00:00" + "time": "2026-09-15T12:58:37+00:00" }, { "name": "barryvdh/reflection-docblock", @@ -10426,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": { @@ -10443,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", @@ -10503,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": [ { @@ -10515,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", @@ -10589,16 +11351,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 +11404,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,73 +11416,7 @@ "type": "github" } ], - "time": "2026-09-25T15:24: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" + "time": "2026-11-03T10:10:19+00:00" }, { "name": "dealerdirect/phpcodesniffer-composer-installer", @@ -10820,16 +11516,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 +11555,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 +11615,10 @@ "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", + "published-time": "2026-11-11T10:12:24+00:00" }, { "name": "dragon-code/contracts", @@ -10983,77 +11682,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 +11777,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 +11815,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 +11836,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.37", "source": { "type": "git", "url": "https://github.com/TomasVotruba/entropy.git", - "reference": "e2dfbd791ab7acea5aed40deefa00b12ad902ca2" + "reference": "57bd06e1652f3c38148944b4880ee3b6e6284da3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/TomasVotruba/entropy/zipball/e2dfbd791ab7acea5aed40deefa00b12ad902ca2", - "reference": "e2dfbd791ab7acea5aed40deefa00b12ad902ca2", + "url": "https://api.github.com/repos/TomasVotruba/entropy/zipball/57bd06e1652f3c38148944b4880ee3b6e6284da3", + "reference": "57bd06e1652f3c38148944b4880ee3b6e6284da3", "shasum": "" }, "require": { @@ -11253,9 +11896,10 @@ "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.37" }, - "time": "2026-10-08T07:55:55+00:00" + "time": "2026-11-14T16:57:42+00:00", + "published-time": "2026-11-14T16:57:58+00:00" }, { "name": "fakerphp/faker", @@ -11318,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", @@ -11380,20 +12025,21 @@ "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", - "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 +12089,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 +12097,8 @@ "type": "github" } ], - "time": "2026-10-03T17:03:57+00:00" + "time": "2026-11-09T23:30:17+00:00", + "published-time": "2026-11-09T23:32:45+00:00" }, { "name": "hamcrest/hamcrest-php", @@ -11551,16 +12198,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 +12220,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 +12275,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 +12283,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 +12364,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 +12427,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 +12439,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 +12470,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 +12536,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 +12752,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 +12822,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 +12966,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 +13055,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 +13219,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 +13293,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 +13368,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 +13474,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 +13566,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 +13627,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 +13639,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 +13663,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 +13709,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", @@ -13210,40 +13851,41 @@ "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", - "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 +13948,8 @@ "type": "patreon" } ], - "time": "2026-07-15T19:09:14+00:00" + "time": "2026-11-10T17:06:52+00:00", + "published-time": "2026-11-10T17:23:22+00:00" }, { "name": "nunomaduro/mock-final-classes", @@ -13458,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": [ @@ -13525,6 +14170,7 @@ "Pest\\Plugins\\Verbose", "Pest\\Plugins\\Version", "Pest\\Plugins\\Shard", + "Pest\\Plugins\\Tia", "Pest\\Plugins\\Parallel" ] }, @@ -13564,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": [ { @@ -13576,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": { @@ -13630,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": [ { @@ -13646,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": { @@ -13704,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": [ { @@ -13716,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": { @@ -13765,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": [ { @@ -13781,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": { @@ -13843,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": [ { @@ -13855,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": { @@ -13915,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": [ { @@ -13931,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": { @@ -13985,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": { @@ -14044,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": [ { @@ -14056,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", @@ -14123,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", @@ -14174,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", @@ -14293,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", @@ -14358,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", @@ -14416,20 +15188,21 @@ "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", - "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 +15234,18 @@ "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", + "published-time": "2026-10-30T19:37:11+00:00" }, { "name": "phpstan/phpstan", - "version": "2.3.0", + "version": "2.3.6", "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/b1f9890d9af53a25c58129e78f0aadd31f90d7f4", - "reference": "b1f9890d9af53a25c58129e78f0aadd31f90d7f4", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/00cedebb76cc82c1592414fa4f616cefdccda16f", + "reference": "00cedebb76cc82c1592414fa4f616cefdccda16f", "shasum": "" }, "require": { @@ -14527,37 +15301,141 @@ "type": "github" } ], - "time": "2026-10-06T06:15:36+00:00" + "time": "2026-11-15T19:58:26+00:00", + "published-time": "2026-11-15T19:58:39+00:00" }, { - "name": "phpunit/php-code-coverage", - "version": "12.5.8", + "name": "phpstan/phpstan-mockery", + "version": "2.0.0", "source": { "type": "git", - "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "7440368d94738d54f2c1de24dbd3871793bbb0dd" + "url": "https://github.com/phpstan/phpstan-mockery.git", + "reference": "89a949d0ac64298e88b7c7fa00caee565c198394" }, "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-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": "phpstan/phpstan-webmozart-assert", + "version": "2.0.0", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan-webmozart-assert.git", + "reference": "0c641817d2a8f05c7157f92d91986e74d3c8ab0c" + }, + "dist": { + "type": "zip", + "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", @@ -14566,7 +15444,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "12.5.x-dev" + "dev-main": "14.5.x-dev" } }, "autoload": { @@ -14595,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": [ { @@ -14615,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": { @@ -14668,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": [ { @@ -14688,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": "*" @@ -14717,7 +15597,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "6.0-dev" + "dev-main": "7.0-dev" } }, "autoload": { @@ -14744,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": { @@ -14804,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": [ { @@ -14824,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": { @@ -14876,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": { @@ -14907,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": [ @@ -14934,7 +15843,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "12.5-dev" + "dev-main": "13.4-dev" } }, "autoload": { @@ -14966,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": [ { @@ -14974,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", @@ -15050,21 +15960,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 +16005,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,32 +16013,32 @@ "type": "github" } ], - "time": "2026-10-06T08:46:45+00:00" + "time": "2026-11-03T18:48:08+00:00" }, { "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": { @@ -15152,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": [ { @@ -15172,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" @@ -15204,7 +16115,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "7.1-dev" + "dev-main": "8.4-dev" } }, "autoload": { @@ -15244,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": [ { @@ -15264,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": { @@ -15314,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": { @@ -15381,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": [ { @@ -15401,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": "*" @@ -15429,7 +16355,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "8.1-dev" + "dev-main": "9.3-dev" } }, "autoload": { @@ -15457,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": [ { @@ -15477,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": { @@ -15547,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": [ { @@ -15567,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": { @@ -15621,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": [ { @@ -15641,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": { @@ -15691,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": [ { @@ -15711,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": { @@ -15761,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": { @@ -15817,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": { @@ -15881,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": [ { @@ -15901,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": { @@ -15950,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": [ { @@ -15970,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.1", + "version": "7.1.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/version.git", - "reference": "9e935a16187e14f39b0e79910dabd614972cdb26" + "reference": "08e41d0c7e146bfc8cef7e63989b1294453a6d6a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/9e935a16187e14f39b0e79910dabd614972cdb26", - "reference": "9e935a16187e14f39b0e79910dabd614972cdb26", + "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": { @@ -16016,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.1" + "source": "https://github.com/sebastianbergmann/version/tree/7.1.0" }, "funding": [ { @@ -16036,36 +17133,37 @@ "type": "tidelift" } ], - "time": "2026-10-04T05:50:08+00:00" + "time": "2026-11-09T06:31:27+00:00", + "published-time": "2026-11-09T06:31:50+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 +17187,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 +17199,7 @@ "type": "tidelift" } ], - "time": "2026-07-31T10:42:43+00:00" + "time": "2026-10-28T16:34:46+00:00" }, { "name": "spatie/backtrace", @@ -16243,16 +17341,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 +17398,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 +17406,7 @@ "type": "github" } ], - "time": "2026-05-15T09:31:32+00:00" + "time": "2026-11-04T15:14:45+00:00" }, { "name": "spatie/ignition", @@ -16398,25 +17496,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 +17523,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 +17584,7 @@ "type": "github" } ], - "time": "2026-03-17T12:20:04+00:00" + "time": "2026-11-06T15:11:05+00:00" }, { "name": "squizlabs/php_codesniffer", @@ -16622,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", @@ -16741,70 +17840,21 @@ "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", - "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 +17869,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 +17900,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 +17912,8 @@ "type": "github" } ], - "time": "2026-10-05T20:07:08+00:00" + "time": "2026-10-09T19:09:05+00:00", + "published-time": "2026-10-09T19:09:39+00:00" } ], "aliases": [], @@ -16876,5 +17927,5 @@ "php": "^8.5" }, "platform-dev": {}, - "plugin-api-version": "2.9.0" + "plugin-api-version": "2.11.0" } diff --git a/config/cache.php b/config/cache.php new file mode 100644 index 00000000..ff21ecaf --- /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', 'lock'), + ], + + '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/database.php b/config/database.php new file mode 100644 index 00000000..91e6410c --- /dev/null +++ b/config/database.php @@ -0,0 +1,235 @@ + 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', 'cocotte') . ':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', 'cocotte') . ':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', '2'), + 'scheme' => env('REDIS_SCHEME') ?: 'tcp', + 'prefix' => env('REDIS_SESSION_DB_PREFIX', env('REDIS_PREFIX', 'cocotte') . ':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), + ], + + 'lock' => [ + '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_LOCK_DB', '4'), + 'scheme' => env('REDIS_SCHEME') ?: 'tcp', + 'prefix' => env('REDIS_LOCK_DB_PREFIX', env('REDIS_PREFIX', 'cocotte') . ':lock:'), + '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 a4956fe7..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', /* |-------------------------------------------------------------------------- @@ -32,20 +32,12 @@ return [ 'disks' => [ - 'public' => [ - 'driver' => 'local', - 'root' => storage_path('app/public'), - 'url' => rtrim((string) env('APP_URL', 'http://localhost'), '/') . '/storage', - 'visibility' => 'public', - 'throw' => false, - 'report' => false, - ], - - 'private' => [ - 'driver' => 'local', - 'root' => storage_path('app/private'), - 'visibility' => 'private', - 'throw' => false, + 'local' => [ + 'driver' => 'local', + 'root' => storage_path('app/private'), + 'serve' => false, + 'throw' => false, + 'report' => false, ], 's3' => [ @@ -61,41 +53,22 @@ return [ 'report' => false, ], - 'inco' => [ - 'driver' => 'local', - 'root' => storage_path('inco'), - 'visibility' => 'private', - 'throw' => true, + 's3-public' => [ + 'driver' => 'scoped', + 'disk' => 's3', + 'prefix' => 'public', + 'visibility' => 'public', + 'throw' => false, ], - 'employees' => [ - 'driver' => 'local', - 'root' => storage_path('salaries'), + 's3-private' => [ + 'driver' => 'scoped', + 'disk' => 's3', + 'prefix' => 'private', 'visibility' => 'private', - 'throw' => true, + 'throw' => false, ], - 'regate' => [ - 'driver' => 'local', - 'root' => storage_path('orders/in'), - 'visibility' => 'private', - 'throw' => true, - ], - ], - - /* - |-------------------------------------------------------------------------- - | 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/ldc.php b/config/ldc.php index f61e682c..e218cde1 100644 --- a/config/ldc.php +++ b/config/ldc.php @@ -4,4 +4,6 @@ declare(strict_types=1); return [ 'headquarters_phone_reception' => env('LDC_HEADQUARTERS_PHONE_RECEPTION') ?: '02 43 62 70 00', + 'max_order_amount_cents' => (int) env('LDC_MAX_ORDER_AMOUNT_CENTS', 20000), + 'max_weekly_amount_cents' => (int) env('LDC_MAX_WEEKLY_AMOUNT_CENTS', 20000), ]; 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, ], diff --git a/config/mail.php b/config/mail.php index 93171f62..22fe804d 100644 --- a/config/mail.php +++ b/config/mail.php @@ -46,7 +46,7 @@ return [ 'port' => env('MAIL_PORT', 2525), 'username' => env('MAIL_USERNAME'), 'password' => env('MAIL_PASSWORD'), - 'timeout' => null, + 'timeout' => (int) env('MAIL_TIMEOUT', 15), 'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)), ], diff --git a/config/purifier.php b/config/purifier.php index 19c70944..b416e30b 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' => [ @@ -48,7 +48,7 @@ return [ 'custom_definition' => [ 'id' => 'html5-definitions', 'rev' => 1, - 'debug' => true, + 'debug' => false, 'elements' => [ // * http://developers.whatwg.org/sections.html ['section', 'Block', 'Flow', 'Common'], diff --git a/config/queue.php b/config/queue.php new file mode 100644 index 00000000..eb079676 --- /dev/null +++ b/config/queue.php @@ -0,0 +1,134 @@ + 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' => true, + ], + + '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' => true, + ], + + '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/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/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), ]; 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/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/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/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/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 @@ -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/migrations/2026_05_22_102624_remove_timeslot_time.php b/database/migrations/2026_11_15_000001_add_reminded_at_to_orders_table.php similarity index 52% rename from database/migrations/2026_05_22_102624_remove_timeslot_time.php rename to database/migrations/2026_11_15_000001_add_reminded_at_to_orders_table.php index db7b17b7..2ff027bb 100644 --- a/database/migrations/2026_05_22_102624_remove_timeslot_time.php +++ b/database/migrations/2026_11_15_000001_add_reminded_at_to_orders_table.php @@ -8,21 +8,17 @@ use Illuminate\Support\Facades\Schema; return new class () extends Migration { - /** - * Run the migrations. - */ public function up(): void { - Schema::table('timeslots', function (Blueprint $table) { - $table->dropColumn('time'); + Schema::table('orders', function (Blueprint $table): void { + $table->timestamp('reminded_at')->nullable()->after('updated_at'); }); } - /** - * Reverse the migrations. - */ public function down(): void { - throw new \Error('WONT ROLLBACK'); + Schema::table('orders', function (Blueprint $table): void { + $table->dropColumn('reminded_at'); + }); } }; 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/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/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); diff --git a/domain/Builders/BasketOrderBuilder.php b/domain/Builders/BasketOrderBuilder.php new file mode 100644 index 00000000..a35e003a --- /dev/null +++ b/domain/Builders/BasketOrderBuilder.php @@ -0,0 +1,42 @@ +basket, + $this->shopperId, + $shopId, + $timeSlot, + ); + } + + #[\Override] + public function getBasket(): Basket + { + return $this->basket; + } + + #[\Override] + public function getShopperId(): ShopperId + { + return $this->shopperId; + } +} diff --git a/domain/Builders/CompletedOrderBuilder.php b/domain/Builders/CompletedOrderBuilder.php new file mode 100644 index 00000000..b68492f8 --- /dev/null +++ b/domain/Builders/CompletedOrderBuilder.php @@ -0,0 +1,56 @@ +basket, + $this->shopperId, + $shopId, + $timeSlot, + ); + } + + #[\Override] + public function getBasket(): Basket + { + return $this->basket; + } + + #[\Override] + public function getShopperId(): ShopperId + { + return $this->shopperId; + } + + #[\Override] + public function getShopId(): ShopId + { + return $this->shopId; + } + + #[\Override] + public function getPickupTimeSlot(): PickupTimeSlot + { + return $this->pickupTimeSlot; + } +} diff --git a/domain/Builders/OrderBuilder.php b/domain/Builders/OrderBuilder.php index 236fd41d..cc6f5c37 100644 --- a/domain/Builders/OrderBuilder.php +++ b/domain/Builders/OrderBuilder.php @@ -5,81 +5,16 @@ declare(strict_types=1); namespace Domain\Builders; use Domain\Models\Entities\Basket; -use Domain\Models\ValueObjects\Entities\ShopId; use Domain\Models\ValueObjects\Entities\ShopperId; -use Domain\Models\ValueObjects\PickupTimeSlot; -class OrderBuilder implements OrderBuilderCompleted, OrderBuilderWithBasket +final readonly class OrderBuilder { - private ShopId $shopId; - - private PickupTimeSlot $pickupTimeSlot; - - private function __construct( - private OrderBuilderType $type, - private Basket $basket, - public readonly ShopperId $shopperId, - ) { - } - - #[\Override] - public function isFromBasket(): bool + private function __construct() { - return in_array($this->type, [OrderBuilderType::FROM_BASKET, OrderBuilderType::WITH_PICKUP, OrderBuilderType::COMPLETED], true); - } - - #[\Override] - public function isCompleted(): bool - { - return in_array($this->type, [OrderBuilderType::WITH_PICKUP, OrderBuilderType::COMPLETED], true); - } - - #[\Override] - public function getBuilderType(): OrderBuilderType - { - return $this->type; - } - - #[\Override] - public function withPickupTimeSlot(ShopId $shopId, PickupTimeSlot $timeSlot): OrderBuilderCompleted - { - $this->type = OrderBuilderType::WITH_PICKUP; - $this->shopId = $shopId; - $this->pickupTimeSlot = $timeSlot; - - return $this; - } - - #[\Override] - public function getBasket(): Basket - { - return $this->basket; - } - - #[\Override] - public function getShopperId(): ShopperId - { - return $this->shopperId; - } - - #[\Override] - public function getShopId(): ShopId - { - return $this->shopId; - } - - #[\Override] - public function getPickupTimeSlot(): PickupTimeSlot - { - return $this->pickupTimeSlot; } public static function fromBasket(Basket $basket, ShopperId $shopperId): OrderBuilderWithBasket { - return new self( - OrderBuilderType::FROM_BASKET, - $basket, - $shopperId - ); + return new BasketOrderBuilder($basket, $shopperId); } } diff --git a/domain/Builders/OrderBuilderCompleted.php b/domain/Builders/OrderBuilderCompleted.php index 6278c8c3..1459d5a2 100644 --- a/domain/Builders/OrderBuilderCompleted.php +++ b/domain/Builders/OrderBuilderCompleted.php @@ -4,17 +4,11 @@ declare(strict_types=1); namespace Domain\Builders; -use Domain\Models\Entities\Basket; use Domain\Models\ValueObjects\Entities\ShopId; -use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Models\ValueObjects\PickupTimeSlot; -interface OrderBuilderCompleted extends OrderBuilderTyped +interface OrderBuilderCompleted extends OrderBuilderWithBasket { - public function getBasket(): Basket; - - public function getShopperId(): ShopperId; - public function getShopId(): ShopId; public function getPickupTimeSlot(): PickupTimeSlot; diff --git a/domain/Builders/OrderBuilderType.php b/domain/Builders/OrderBuilderType.php deleted file mode 100644 index a0451281..00000000 --- a/domain/Builders/OrderBuilderType.php +++ /dev/null @@ -1,12 +0,0 @@ - */ use BaseEnum; diff --git a/domain/Enums/DiscountType.php b/domain/Enums/DiscountType.php index 17cd7aee..1409898a 100644 --- a/domain/Enums/DiscountType.php +++ b/domain/Enums/DiscountType.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Domain\Enums; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum DiscountType: int +enum DiscountType: int implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; diff --git a/domain/Enums/EmployeeSite.php b/domain/Enums/EmployeeSite.php index ea39bade..bd212ec2 100644 --- a/domain/Enums/EmployeeSite.php +++ b/domain/Enums/EmployeeSite.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Domain\Enums; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum EmployeeSite: string +enum EmployeeSite: string implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; diff --git a/domain/Enums/Nutriscore.php b/domain/Enums/Nutriscore.php index 9c6f3372..c92ab3f0 100644 --- a/domain/Enums/Nutriscore.php +++ b/domain/Enums/Nutriscore.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Domain\Enums; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum Nutriscore: string +enum Nutriscore: string implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; diff --git a/domain/Enums/OrderStatus.php b/domain/Enums/OrderStatus.php index 5bd641a1..1801d2f9 100644 --- a/domain/Enums/OrderStatus.php +++ b/domain/Enums/OrderStatus.php @@ -5,15 +5,18 @@ declare(strict_types=1); namespace Domain\Enums; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum OrderStatus: int +enum OrderStatus: string implements HasBaseEnum { - /** @use \Shared\Enums\BaseEnum */ + /** @use \Shared\Enums\BaseEnum */ use BaseEnum; - case WAITING = 1; - case VALIDATED = 3; - case CANCELED = 7; + case WAITING = 'waiting'; + case PENDING = 'pending'; + case VALIDATED = 'validated'; + case FAILED = 'failed'; + case CANCELED = 'canceled'; /** * Optional labels definition @@ -21,8 +24,10 @@ enum OrderStatus: int * @phpstan-ignore-next-line classConstant.unused (Base enum usage) */ private const LABELS = [ - self::WAITING->name => 'En attente', - self::VALIDATED->name => 'Validé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/domain/Enums/Pagination/ItemsPerPaginationEnum.php b/domain/Enums/Pagination/ItemsPerPaginationEnum.php index 3743ad49..814baf23 100644 --- a/domain/Enums/Pagination/ItemsPerPaginationEnum.php +++ b/domain/Enums/Pagination/ItemsPerPaginationEnum.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Domain\Enums\Pagination; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum ItemsPerPaginationEnum: int +enum ItemsPerPaginationEnum: int implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; diff --git a/domain/Enums/PriceShowingMode.php b/domain/Enums/PriceShowingMode.php index 5f8bfbc1..2fc86448 100644 --- a/domain/Enums/PriceShowingMode.php +++ b/domain/Enums/PriceShowingMode.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Domain\Enums; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum PriceShowingMode: string +enum PriceShowingMode: string implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; diff --git a/domain/Enums/ProductBrand.php b/domain/Enums/ProductBrand.php index 92b6b0fc..d354ed99 100644 --- a/domain/Enums/ProductBrand.php +++ b/domain/Enums/ProductBrand.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Domain\Enums; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum ProductBrand: string +enum ProductBrand: string implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; diff --git a/domain/Enums/RepeatFrequency.php b/domain/Enums/RepeatFrequency.php index af1729ee..139d501b 100644 --- a/domain/Enums/RepeatFrequency.php +++ b/domain/Enums/RepeatFrequency.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Domain\Enums; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum RepeatFrequency: string +enum RepeatFrequency: string implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; diff --git a/domain/Enums/SellUnit.php b/domain/Enums/SellUnit.php index c5d95b3c..30ac59c2 100644 --- a/domain/Enums/SellUnit.php +++ b/domain/Enums/SellUnit.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Domain\Enums; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum SellUnit: string +enum SellUnit: string implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; diff --git a/domain/Enums/StaticPageSlug.php b/domain/Enums/StaticPageSlug.php index 87cfb14d..a7b736f8 100644 --- a/domain/Enums/StaticPageSlug.php +++ b/domain/Enums/StaticPageSlug.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Domain\Enums; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum StaticPageSlug: string +enum StaticPageSlug: string implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; diff --git a/domain/Enums/StatsCustomerType.php b/domain/Enums/StatsCustomerType.php index 2aa2ec93..3e3a7d43 100644 --- a/domain/Enums/StatsCustomerType.php +++ b/domain/Enums/StatsCustomerType.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Domain\Enums; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum StatsCustomerType: int +enum StatsCustomerType: int implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; diff --git a/domain/Enums/StatsShopType.php b/domain/Enums/StatsShopType.php index bbe65ce1..df274fbb 100644 --- a/domain/Enums/StatsShopType.php +++ b/domain/Enums/StatsShopType.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Domain\Enums; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum StatsShopType: int +enum StatsShopType: int implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; @@ -31,18 +32,18 @@ enum StatsShopType: int * @phpstan-ignore-next-line classConstant.unused (Base enum usage) */ private const LABELS = [ - self::nbActiveClients->name => 'Nombre de clients actifs', - self::nbValidateCmd->name => 'Commandes validées', - self::nbWaitingCmd->name => 'Commandes en attente', - self::nbCanceledCmd->name => 'Commandes annulées', - self::nbCmdWith7DayDelay->name => 'Nombre de commandes à J+7', - self::nbCmdWith14DayDelay->name => 'Nombre de commandes à J+14', - self::canceledRate->name => 'Taux d\'abandon', - self::orderFrequency->name => 'Fréquence de commande', - self::purchaseFrequency->name => 'Fréquence d\'achat', - self::averageBasketHt->name => 'Prix du panier moyen', - self::averageProductCountPerOrder->name => 'Nombre d\'article moyen par commande', - self::caHt->name => 'Montant total HT', - self::caTtc->name => 'Montant total TTC', + self::nbActiveClients->name => 'Number of active customers', + self::nbValidateCmd->name => 'Validated orders', + self::nbWaitingCmd->name => 'Pending orders', + self::nbCanceledCmd->name => 'Canceled orders', + self::nbCmdWith7DayDelay->name => 'Orders at D+7', + self::nbCmdWith14DayDelay->name => 'Orders at D+14', + self::canceledRate->name => 'Cancellation rate', + self::orderFrequency->name => 'Order frequency', + self::purchaseFrequency->name => 'Purchase frequency', + self::averageBasketHt->name => 'Average basket price', + self::averageProductCountPerOrder->name => 'Average number of items per order', + self::caHt->name => 'Total amount HT', + self::caTtc->name => 'Total amount TTC', ]; } diff --git a/domain/Enums/TaxRate.php b/domain/Enums/TaxRate.php index 6aef67a3..e3f05f82 100644 --- a/domain/Enums/TaxRate.php +++ b/domain/Enums/TaxRate.php @@ -7,8 +7,9 @@ namespace Domain\Enums; use Domain\Models\Entities\Product; use Money\Money; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum TaxRate: int +enum TaxRate: int implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; diff --git a/domain/Enums/Units/InvoicingUnit.php b/domain/Enums/Units/InvoicingUnit.php index 5086e247..f69c7c55 100644 --- a/domain/Enums/Units/InvoicingUnit.php +++ b/domain/Enums/Units/InvoicingUnit.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Domain\Enums\Units; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum InvoicingUnit: string +enum InvoicingUnit: string implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; diff --git a/domain/Enums/Units/OrderUnit.php b/domain/Enums/Units/OrderUnit.php index 6851cb0e..7c5cd304 100644 --- a/domain/Enums/Units/OrderUnit.php +++ b/domain/Enums/Units/OrderUnit.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Domain\Enums\Units; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum OrderUnit: string +enum OrderUnit: string implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; diff --git a/domain/Enums/UserRole.php b/domain/Enums/UserRole.php index 98f22189..248b9e3b 100644 --- a/domain/Enums/UserRole.php +++ b/domain/Enums/UserRole.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Domain\Enums; use Shared\Enums\BaseEnum; +use Shared\Enums\HasBaseEnum; -enum UserRole: int +enum UserRole: int implements HasBaseEnum { /** @use \Shared\Enums\BaseEnum */ use BaseEnum; diff --git a/domain/Events/BasketHasBeenModified.php b/domain/Events/BasketHasBeenModified.php new file mode 100644 index 00000000..e373adf4 --- /dev/null +++ b/domain/Events/BasketHasBeenModified.php @@ -0,0 +1,16 @@ +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::PENDING) { + throw new \DomainException('Only pending orders can be validated.'); + } + + $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::PENDING, + ); + } + public static function fromBasket( OrderId $id, OrderReference $reference, @@ -78,6 +123,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 +156,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/Models/Entities/PickupExceptionOnDate.php b/domain/Models/Entities/PickupExceptionOnDate.php index 225eae08..d2fafd7b 100644 --- a/domain/Models/Entities/PickupExceptionOnDate.php +++ b/domain/Models/Entities/PickupExceptionOnDate.php @@ -11,7 +11,7 @@ use Domain\Models\ValueObjects\Entities\PickupExceptionId; use Shared\DDD\Entity; /** @implements \Shared\DDD\Entity<\Domain\Models\ValueObjects\Entities\PickupExceptionId> */ -final readonly class PickupExceptionOnDate implements Entity +final class PickupExceptionOnDate implements Entity { public function __construct( public PickupExceptionId $id, diff --git a/domain/Models/Entities/Product.php b/domain/Models/Entities/Product.php index f73a2994..2da0b872 100644 --- a/domain/Models/Entities/Product.php +++ b/domain/Models/Entities/Product.php @@ -18,7 +18,7 @@ use Money\Money; use Shared\DDD\Entity; /** @implements \Shared\DDD\Entity<\Domain\Models\ValueObjects\Entities\ProductId> */ -final readonly class Product implements Entity +final class Product implements Entity { public const int ROUNDING = Money::ROUND_UP; @@ -52,7 +52,7 @@ final readonly class Product implements Entity if ($this->orderable_start && $target < $this->orderable_start) { return false; } - if ($this->orderable_end && $target > $this->orderable_end) { + if ($this->orderable_end && $target >= $this->orderable_end) { return false; } @@ -122,31 +122,7 @@ final readonly 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 readonly 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/domain/Models/Entities/Shop.php b/domain/Models/Entities/Shop.php index 20a0ad9f..76f8de9f 100644 --- a/domain/Models/Entities/Shop.php +++ b/domain/Models/Entities/Shop.php @@ -8,7 +8,7 @@ use Domain\Models\ValueObjects\Entities\ShopId; use Shared\DDD\Entity; /** @implements \Shared\DDD\Entity<\Domain\Models\ValueObjects\Entities\ShopId> */ -final readonly class Shop implements Entity +final class Shop implements Entity { public function __construct( public ShopId $id, diff --git a/domain/Models/Entities/Shopper.php b/domain/Models/Entities/Shopper.php index 0fb42b0a..cc9d595f 100644 --- a/domain/Models/Entities/Shopper.php +++ b/domain/Models/Entities/Shopper.php @@ -15,8 +15,10 @@ use Domain\Models\ValueObjects\ShopperSiteCode; use Shared\DDD\Entity; /** @implements \Shared\DDD\Entity<\Domain\Models\ValueObjects\Entities\ShopperId> */ -final readonly class Shopper implements Entity +final class Shopper implements Entity { + private const string BUSINESS_TIMEZONE = 'Europe/Paris'; + public function __construct( private readonly ShopperId $id, public readonly Email $email, @@ -45,6 +47,12 @@ final readonly class Shopper implements Entity public function isActive(): bool { - return $this->endDate === null || $this->endDate->greaterThan(CarbonImmutable::now()); + $todayParis = CarbonImmutable::now(self::BUSINESS_TIMEZONE)->format('Y-m-d'); + + if ($this->startDate->format('Y-m-d') > $todayParis) { + return false; + } + + return $this->endDate === null || $this->endDate->format('Y-m-d') > $todayParis; } } 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/ContactFormData.php b/domain/Models/ValueObjects/ContactFormData.php index f006984a..cca6a11d 100644 --- a/domain/Models/ValueObjects/ContactFormData.php +++ b/domain/Models/ValueObjects/ContactFormData.php @@ -12,7 +12,7 @@ final readonly class ContactFormData public string $email, public string $subject, public string $message, - public ?string $orderRef = null, + public ?OrderReference $orderRef = null, public ?AttachedFile $file = null, ) { if (trim($lastName) === '') { @@ -30,8 +30,5 @@ final readonly class ContactFormData if (trim($message) === '') { throw new \DomainException('message cannot be empty'); } - if ($orderRef !== null && trim($orderRef) === '') { - throw new \DomainException('orderRef cannot be empty if provided'); - } } } 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/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/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/domain/Models/ValueObjects/IcsContent.php b/domain/Models/ValueObjects/IcsContent.php new file mode 100644 index 00000000..942b94db --- /dev/null +++ b/domain/Models/ValueObjects/IcsContent.php @@ -0,0 +1,26 @@ +value; + } +} 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/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/Models/ValueObjects/PhoneNumber.php b/domain/Models/ValueObjects/PhoneNumber.php index 25938e79..746123b8 100644 --- a/domain/Models/ValueObjects/PhoneNumber.php +++ b/domain/Models/ValueObjects/PhoneNumber.php @@ -4,10 +4,9 @@ declare(strict_types=1); namespace Domain\Models\ValueObjects; -use Stringable; use Webmozart\Assert\Assert; -final readonly class PhoneNumber implements Stringable +final readonly class PhoneNumber implements \Stringable { public function __construct(public string $value) { diff --git a/domain/Models/ValueObjects/PickupWindow.php b/domain/Models/ValueObjects/PickupWindow.php new file mode 100644 index 00000000..c5b491cb --- /dev/null +++ b/domain/Models/ValueObjects/PickupWindow.php @@ -0,0 +1,16 @@ +maxOrderAmountCents, $this->currency ?? new Currency('EUR')); + return new Money($this->maxOrderAmountCents, $this->currency); } private function getMaxWeeklyAmount(): Money { - return new Money($this->maxWeeklyAmountCents, $this->currency ?? new Currency('EUR')); + return new Money($this->maxWeeklyAmountCents, $this->currency); } } 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/Ports/Repositories/ProductRepository.php b/domain/Ports/Repositories/ProductRepository.php index 9449d305..635fd435 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,9 +17,22 @@ 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; + /** + * @throws \Domain\Exceptions\OrderTunnel\UnorderableProductException + */ public function getBasketProduct(ProductId $id, int $qty): BasketProduct; } diff --git a/domain/Ports/Services/CrmCustomerGatewayService.php b/domain/Ports/Services/CrmCustomerGatewayService.php new file mode 100644 index 00000000..f687307d --- /dev/null +++ b/domain/Ports/Services/CrmCustomerGatewayService.php @@ -0,0 +1,21 @@ +repository->find($basketId) ?? new Basket($basketId, []); } + public function hasItems(): bool + { + return $this->getBasket()->countItems() > 0; + } + public function add(ProductId $productId, int $qty = 1): void { $basketProduct = $this->productRepository->getBasketProduct($productId, $qty); @@ -34,7 +43,7 @@ class BasketService $basket->addOrUpdate($basketProduct); - $this->repository->persist($basket); + $this->persistBasket($basket); } public function remove(ProductId $productId, int $qty = 1): void @@ -42,7 +51,7 @@ class BasketService $basket = $this->getBasket(); $basket->remove($productId, $qty); - $this->repository->persist($basket); + $this->persistBasket($basket); } public function removeLine(ProductId $productId): void @@ -50,26 +59,26 @@ class BasketService $basket = $this->getBasket(); $basket->removeLine($productId); - $this->repository->persist($basket); - } - - public function revalidateBasket(Basket $basket): Basket - { - $refreshedItems = []; - - foreach ($basket->items() as $item) { - $refreshedItems[] = $this->productRepository->getBasketProduct($item->id, $item->qty); - } - - $refreshedBasket = new Basket($basket->id, $refreshedItems); - $this->repository->persist($refreshedBasket); - - return $refreshedBasket; + $this->persistBasket($basket); } public function empty(): void { - $this->repository->delete($this->getBasket()); + $basket = $this->getBasket(); + + $this->deleteBasket($basket); + } + + private function persistBasket(Basket $basket): void + { + $this->repository->persist($basket); + $this->eventDispatcher->dispatch(new BasketHasBeenModified($basket->id)); + } + + private function deleteBasket(Basket $basket): void + { + $this->repository->delete($basket); + $this->eventDispatcher->dispatch(new BasketRemoved($basket->id)); } private function getBasketId(): BasketId diff --git a/domain/Services/OrderService.php b/domain/Services/OrderService.php index a0736665..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 { @@ -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, @@ -39,17 +55,45 @@ 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 + { + $order = $this->orderRepository->findForUpdate($id); + + if (! $order) { + throw new \DomainException('Order not found'); + } + + $order->validate(); + + $this->orderRepository->persist($order); + + 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 0a149fae..738f8298 100644 --- a/domain/Services/OrderTunnelService.php +++ b/domain/Services/OrderTunnelService.php @@ -9,23 +9,31 @@ use Carbon\CarbonInterface; use Domain\Builders\OrderBuilder; use Domain\Builders\OrderBuilderCompleted; use Domain\Builders\OrderBuilderWithBasket; -use Domain\Enums\OrderTunnelStep; +use Domain\Exceptions\OrderTunnel\BasketPriceChangedException; +use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException; +use Domain\Exceptions\OrderTunnel\InactiveShopperException; use Domain\Exceptions\OrderTunnel\MissingOrderBuilderException; 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\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; use Domain\Ports\Repositories\OrderRepository; +use Domain\Ports\Repositories\ProductRepository; use Domain\Ports\Repositories\ShopperRepository; use Domain\Ports\Repositories\ShopRepository; use Domain\Ports\Services\EmployeeStatisticsService; use Domain\Ports\Services\OrderBuilderSessionManager; -use Domain\Ports\Services\TransactionManager; +use Domain\Ports\Services\RegateService; +use Domain\Ports\Services\TunnelAttemptTrackerService; use Shared\DDD\DomainEventDispatcher; class OrderTunnelService @@ -33,37 +41,36 @@ class OrderTunnelService private const TIMESLOTS_DAY_TARGET = 28; public function __construct( - private readonly BasketService $basketService, private readonly DomainEventDispatcher $eventDispatcher, private readonly ShopperService $shopperService, private readonly OrderBuilderSessionManager $orderBuilderSessionManager, private readonly PickupSchedulingService $pickupService, private readonly OrderRepository $orderRepository, + private readonly ProductRepository $productRepository, private readonly CustomerOrderLimitPolicy $orderLimitPolicy, - private readonly TransactionManager $transactionManager, private readonly ShopRepository $shopRepository, private readonly ShopperRepository $shopperRepository, private readonly OrderService $orderService, private readonly EmployeeStatisticsService $employeeStatisticsService, + private readonly RegateService $regateService, + private readonly TunnelAttemptTrackerService $tunnelAttemptTracker, ) { } - public function hasValidBasket(): bool - { - return $this->basketService->getBasket()->countItems() > 0; - } - - public function canAccessStep(OrderTunnelStep $step): bool + public function canAccessBooking(): bool { $builder = $this->orderBuilderSessionManager->get(); - $hasValidBasket = $this->hasValidBasket(); + return $builder instanceof OrderBuilderWithBasket + && $builder->getBasket()->countItems() > 0; + } - return match ($step) { - OrderTunnelStep::REVIEW => $hasValidBasket, - OrderTunnelStep::BOOKING => $this->hasValidBasket() && $builder !== null && $builder->isFromBasket(), - OrderTunnelStep::CONFIRMATION => $this->hasValidBasket() && $builder !== null && $builder->isCompleted(), - }; + public function canAccessConfirmation(): bool + { + $builder = $this->orderBuilderSessionManager->get(); + + return $builder instanceof OrderBuilderCompleted + && $builder->getBasket()->countItems() > 0; } /** @@ -79,7 +86,7 @@ class OrderTunnelService ); } - /** @return array */ + /** @return array */ public function getAvailableTimeSlots(Shop $shop): array { return $this->pickupService->getTimeSlotsFor( @@ -90,10 +97,10 @@ class OrderTunnelService public function initializeFromBasket(Basket $basket, ShopperId $customerId): void { - /** @var OrderBuilder $builder */ $builder = OrderBuilder::fromBasket($basket, $customerId); $this->orderBuilderSessionManager->save($builder); + $this->tunnelAttemptTracker->recordEntry($customerId); } /** @@ -103,11 +110,10 @@ class OrderTunnelService { $builder = $this->orderBuilderSessionManager->get(); - if ($builder === null || ! $builder->isFromBasket()) { + if (! $builder instanceof OrderBuilderWithBasket || $builder->getBasket()->countItems() === 0) { throw new MissingOrderBuilderException(); } - /** @var OrderBuilderWithBasket $builder */ return $builder; } @@ -118,18 +124,17 @@ class OrderTunnelService { $builder = $this->orderBuilderSessionManager->get(); - if ($builder === null || ! $builder->isCompleted()) { + if (! $builder instanceof OrderBuilderCompleted || $builder->getBasket()->countItems() === 0) { throw new MissingOrderBuilderException(); } - /** @var OrderBuilderCompleted $builder */ return $builder; } /** * Validate that the selected date matches an available slot and apply it to the builder. * - * @param array $availableSlots + * @param array $availableSlots */ public function applyTimeSlot( OrderBuilderWithBasket $builder, @@ -149,7 +154,6 @@ class OrderTunnelService return null; } - /** @var OrderBuilder $completed */ $completed = $builder->withPickupTimeSlot($shop->id(), $matchedSlot); $this->orderBuilderSessionManager->save($completed); @@ -157,6 +161,130 @@ 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->tunnelAttemptTracker->markConverted($order->id()); + $this->eventDispatcher->dispatch($order->toPlacedEvent()); + + return $order; + } + + /** + * Step 2c (on Regate failure): marks the PENDING order as FAILED without emptying the basket. + */ + public function failPendingOrder(OrderId $orderId): void + { + $this->orderService->failOrder($orderId); + } + + /** + * @throws WeeklyLimitExceededException + * @throws OrderLimitExceededException + * @throws ExpiredPickupTimeSlotException + * @throws BasketPriceChangedException + * @throws UnorderableProductException + * @throws InactiveShopperException + * @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()); + $pickupTimeSlot = $builder->getPickupTimeSlot(); + $shopId = $builder->getShopId(); + $shopper = $this->shopperRepository->getByIdOrFail($shopperId); + + if (! $shopper->isActive()) { + throw new InactiveShopperException(); + } + + $this->assertBasketAmountWithinLimit($basket); + $this->assertBasketWeeklyAmountWithinLimitFor( + $shopper, + $basket, + $pickupTimeSlot->getAt() + ); + + $shop = $this->shopRepository->find($shopId); + if (! $shop) { + throw new \DomainException("Shop with id '{$shopId->value}' not found."); + } + + $this->assertPickupTimeSlotIsAvailable($shop, $pickupTimeSlot); + + return $pending + ? $this->orderService->createPendingOrderFromBasket($basket, $pickupTimeSlot, $shopper, $shop) + : $this->orderService->createOrderFromBasket($basket, $pickupTimeSlot, $shopper, $shop); + } + /** @throws \Domain\Exceptions\OrderTunnel\OrderLimitExceededException */ public function assertBasketAmountWithinLimit(Basket $basket): void { @@ -181,47 +309,52 @@ class OrderTunnelService $this->orderLimitPolicy->assertCanPlaceWeeklyOrder($withBasket->totalTaxIncluded(), $weekTotal); } - /** - * @throws WeeklyLimitExceededException - * @throws OrderLimitExceededException - */ - public function finalizeOrder(OrderBuilderCompleted $builder): Order + private function revalidateBasket(Basket $basket): Basket { - $shopperId = $builder->getShopperId(); - $basket = $this->basketService->revalidateBasket($builder->getBasket()); - $pickupTimeSlot = $builder->getPickupTimeSlot(); - $shopId = $builder->getShopId(); - $shopper = $this->shopperRepository->getByIdOrFail($shopperId); + $refreshedItems = []; + $priceChanged = false; - $this->assertBasketAmountWithinLimit($basket); - $this->assertBasketWeeklyAmountWithinLimitFor( - $shopper, - $basket, - $pickupTimeSlot->getAt() - ); + foreach ($basket->items() as $item) { + $refreshed = $this->productRepository->getBasketProduct($item->id, $item->qty); - return $this->transactionManager->execute(function () use ($basket, $shopId, $shopper, $pickupTimeSlot) { - $shop = $this->shopRepository->find($shopId); - if (! $shop) { - throw new \DomainException("Shop with id '{$shopId->value}' not found."); + if ($this->hasItemPricingChanged($item, $refreshed)) { + $priceChanged = true; } - $order = $this->orderService->createOrderFromBasket( - $basket, - $pickupTimeSlot, - $shopper, - $shop - ); + $refreshedItems[] = $refreshed; + } - $this->orderRepository->persist($order); + $refreshedBasket = new Basket($basket->id, $refreshedItems); - $this->eventDispatcher->dispatch($order->toPlacedEvent()); + if ($priceChanged || ! $refreshedBasket->totalTaxIncluded()->equals($basket->totalTaxIncluded())) { + throw new BasketPriceChangedException($refreshedBasket); + } - $this->basketService->empty(); - $this->orderBuilderSessionManager->clear(); + return $refreshedBasket; + } - return $order; - }); + 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()); + } + + /** + * @throws \Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException + */ + private function assertPickupTimeSlotIsAvailable(Shop $shop, PickupTimeSlot $pickupTimeSlot): void + { + $availableSlots = $this->getAvailableTimeSlots($shop); + + foreach ($availableSlots as $slot) { + if (CarbonImmutable::instance($pickupTimeSlot->getAt())->isSameDay($slot->getAt())) { + return; + } + } + + throw new ExpiredPickupTimeSlotException(); } private function getTimeslotsUntil(): CarbonInterface diff --git a/domain/Services/PickupSchedulingService.php b/domain/Services/PickupSchedulingService.php index 4fe2a588..c9bcab35 100644 --- a/domain/Services/PickupSchedulingService.php +++ b/domain/Services/PickupSchedulingService.php @@ -12,6 +12,7 @@ use Domain\Models\Entities\PickupExceptionOnDate; use Domain\Models\Entities\Shop; use Domain\Models\ValueObjects\EditablePickupExceptionForShop; use Domain\Models\ValueObjects\PickupTimeSlot; +use Domain\Models\ValueObjects\PickupWindow; use Domain\Models\ValueObjects\ShopPickupOverride; use Domain\Ports\Repositories\PickupExceptionRepository; @@ -51,19 +52,21 @@ class PickupSchedulingService public function nextPickup(): CarbonInterface { - $systemTz = $this->getNow()->getTimezone(); - $now = $this->getNow()->setTimezone(self::CUTOFF_TIME_ZONE); - $startOfThisDay = $now->copy()->startOfDay(); + $systemTz = $this->getNow()->getTimezone(); + $nowInParis = $this->getNow()->setTimezone(self::CUTOFF_TIME_ZONE); + $monday = $nowInParis->startOfWeek(CarbonInterface::MONDAY); - if ($startOfThisDay->isDayOfWeek(self::PICKUP_DAY->value) && $now->hour < self::CUTOFF_HOUR) { - return $startOfThisDay->addHours(self::CUTOFF_HOUR) - ->setTimezone($systemTz); - } + $thisWeekPickup = $monday + ->addDays(self::PICKUP_DAY->value - 1) + ->setTime(self::CUTOFF_HOUR, 0); - return $startOfThisDay - ->next(self::PICKUP_DAY->value) - ->addHours(self::CUTOFF_HOUR) - ->setTimezone($systemTz); + $thisWeekDeadline = $this->getDefaultDeadline($thisWeekPickup)->setTimezone(self::CUTOFF_TIME_ZONE); + + $targetPickup = $nowInParis->lessThanOrEqualTo($thisWeekDeadline) + ? $thisWeekPickup + : $thisWeekPickup->addWeek(); + + return $targetPickup->setTimezone($systemTz); } public function getPeriodFromPickUpDay(): CarbonPeriod @@ -75,10 +78,14 @@ class PickupSchedulingService public function getPeriodForPickupDate(CarbonInterface $pickupDate): CarbonPeriod { - $pickupDate = CarbonImmutable::createFromInterface($pickupDate); - $defaultDeadLine = $this->getDefaultDeadline($pickupDate); + $systemTz = $this->getNow()->getTimezone(); + $pickupInCutoff = CarbonImmutable::createFromInterface($pickupDate)->setTimezone(self::CUTOFF_TIME_ZONE); + $defaultDeadLine = $this->getDefaultDeadline($pickupInCutoff); - return CarbonPeriod::create($defaultDeadLine, $pickupDate->endOfDay()); + return CarbonPeriod::create( + $defaultDeadLine, + $pickupInCutoff->endOfDay()->setTimezone($systemTz), + ); } /** @return \Domain\Models\ValueObjects\EditablePickupExceptionForShop[] */ @@ -98,7 +105,10 @@ class PickupSchedulingService $isChecked = $associated !== null; $isPickupDay = $pickupException->isPickupDay(self::PICKUP_DAY); - $defaultDeadline = $this->getDefaultDeadline($pickupException->date); + $defaultDeadline = $this->getDefaultDeadline( + CarbonImmutable::createFromFormat('!Y-m-d', $pickupException->date->format('Y-m-d'), self::CUTOFF_TIME_ZONE) + ?? $pickupException->date + ); $isBlocked = $associated !== null && ! $associated->hasReplacement(); $isPastDeadline = $associated !== null && $associated->isDeadlinePassed($this->getNow(), $defaultDeadline); @@ -111,10 +121,27 @@ class PickupSchedulingService }, $allExceptions); } + public function getPickupWindowFor(Shop $shop, CarbonInterface $targetPickupDay): ?PickupWindow + { + $todayDate = $this->getNow()->setTimezone(self::CUTOFF_TIME_ZONE)->startOfDay(); + $targetDate = CarbonImmutable::createFromInterface($targetPickupDay) + ->setTimezone(self::CUTOFF_TIME_ZONE) + ->startOfDay(); + + if ($targetDate->lessThanOrEqualTo($todayDate)) { + return null; + } + + $coveredPeriod = CarbonPeriod::create($todayDate, $targetDate); + $pickupExceptionList = $this->pickupExceptionRepository->getExceptionsForShop($shop->id(), $coveredPeriod); + + return $this->resolveWindowForDate($targetDate, $pickupExceptionList); + } + /** @return \Domain\Models\ValueObjects\PickupTimeSlot[] */ public function getTimeSlotsFor(Shop $shop, \DateTimeInterface $until): array { - $todayDate = $this->getNow()->startOfDay(); + $todayDate = $this->getNow()->setTimezone(self::CUTOFF_TIME_ZONE)->startOfDay(); $untilDayDate = CarbonImmutable::createFromInterface($until)->setTimezone(self::CUTOFF_TIME_ZONE)->startOfDay(); $coveredPeriod = CarbonPeriod::create($todayDate, $untilDayDate); @@ -129,21 +156,10 @@ class PickupSchedulingService fn (CarbonInterface $date) => $date->isDayOfWeek(self::PICKUP_DAY->value) ); - $mappedSlots = array_map(function (CarbonInterface $date) use ($pickupExceptionList) { - $pickupDayDate = CarbonImmutable::createFromInterface($date); - - $shopPickupExceptionForTheDate = null; - foreach ($pickupExceptionList as $ex) { - if ($pickupDayDate->isSameDay($ex->exception->date)) { - $shopPickupExceptionForTheDate = $ex; - break; - } - } - - return $shopPickupExceptionForTheDate !== null - ? $this->getTimeSlotForException($shopPickupExceptionForTheDate) - : $this->getTimeSlotForPickupDay($pickupDayDate); - }, $filteredDates); + $mappedSlots = array_map( + fn (CarbonInterface $date): ?PickupTimeSlot => $this->resolveWindowForDate($date, $pickupExceptionList)?->timeSlot, + $filteredDates, + ); $validSlots = array_filter($mappedSlots); usort($validSlots, fn (PickupTimeSlot $a, PickupTimeSlot $b) => $a->getAt() <=> $b->getAt()); @@ -151,31 +167,67 @@ class PickupSchedulingService return $validSlots; } - protected function getTimeSlotForPickupDay(CarbonInterface $pickupDayDate): ?PickupTimeSlot + /** + * @param \Domain\Models\ValueObjects\ShopPickupOverride[] $pickupExceptionList + */ + protected function resolveWindowForDate(CarbonInterface $pickupDayDate, array $pickupExceptionList): ?PickupWindow + { + $date = CarbonImmutable::createFromInterface($pickupDayDate); + + $shopPickupExceptionForTheDate = null; + foreach ($pickupExceptionList as $ex) { + if ($date->format('Y-m-d') === $ex->exception->date->format('Y-m-d')) { + $shopPickupExceptionForTheDate = $ex; + break; + } + } + + return $shopPickupExceptionForTheDate !== null + ? $this->resolveWindowForException($shopPickupExceptionForTheDate) + : $this->resolveWindowForPickupDay($date); + } + + protected function resolveWindowForPickupDay(CarbonInterface $pickupDayDate): ?PickupWindow { $defaultDeadline = $this->getDefaultDeadline($pickupDayDate); // ? Have we reached the default standard deadline ? return $this->isBefore($defaultDeadline) // * Nominal pipeline: timeslot matches standard pickup day - ? $this->createTimeSlot($pickupDayDate) + ? new PickupWindow($this->createTimeSlot($pickupDayDate), $defaultDeadline) : null; } - protected function getTimeSlotForException(ShopPickupOverride $shopPickupException): ?PickupTimeSlot + protected function resolveWindowForException(ShopPickupOverride $shopPickupException): ?PickupWindow { if (! $shopPickupException->hasReplacement() || $shopPickupException->replacementDate === null) { return null; } - $defaultDeadline = $this->getDefaultDeadline(CarbonImmutable::createFromInterface($shopPickupException->exception->date)); + $exceptionDate = CarbonImmutable::createFromFormat( + '!Y-m-d', + $shopPickupException->exception->date->format('Y-m-d'), + self::CUTOFF_TIME_ZONE + ) ?? CarbonImmutable::createFromInterface($shopPickupException->exception->date); + + $defaultDeadline = $this->getDefaultDeadline($exceptionDate); $deadline = $shopPickupException->effectiveDeadline($defaultDeadline); return $this->isBefore($deadline) - ? $this->createTimeSlot($shopPickupException->replacementDate->toImmutable()) + ? new PickupWindow($this->createTimeSlot($shopPickupException->replacementDate->toImmutable()), $deadline) : null; } + protected function getTimeSlotForPickupDay(CarbonInterface $pickupDayDate): ?PickupTimeSlot + { + return $this->resolveWindowForPickupDay($pickupDayDate)?->timeSlot; + } + + protected function getTimeSlotForException(ShopPickupOverride $shopPickupException): ?PickupTimeSlot + { + return $this->resolveWindowForException($shopPickupException)?->timeSlot; + } + protected function createTimeSlot(CarbonInterface $forDate): PickupTimeSlot { return new PickupTimeSlot( @@ -211,6 +263,6 @@ class PickupSchedulingService protected function getNow(): CarbonImmutable { - return CarbonImmutable::createFromInterface(new \DateTimeImmutable()); + return CarbonImmutable::now(); } } diff --git a/domain/Services/RegateService.php b/domain/Services/RegateService.php deleted file mode 100644 index 96758aad..00000000 --- a/domain/Services/RegateService.php +++ /dev/null @@ -1,79 +0,0 @@ -productIncoId->value, - $employeeMatricule->value, - (string) $line->productIncoId->value, - 'commande ferme', - (string) $line->productOrderUnit->value, - $line->productOrderUnit->toRegateCode(), - '', - $pickupDay->format('d/m/Y'), - (string) $line->quantity, - (string) $reference, - ] - ); - } - - $csvContent = $this->csvGenerator->generate($this->header, $rows); - - $now = CarbonImmutable::now(); - $fileName = sprintf( - 'BTQ-%s-%s%s.csv', - $reference, - $now->format('Ymd_His'), - \microtime(true) - ); - - $this->dispatcher->dispatch( - new RegateOrderCsvGenerated($csvContent, $fileName) - ); - } -} diff --git a/infra/Adapters/Events/LaravelDomainEventDispatcher.php b/infra/Adapters/Events/LaravelDomainEventDispatcher.php index dbc03a42..858df4b6 100644 --- a/infra/Adapters/Events/LaravelDomainEventDispatcher.php +++ b/infra/Adapters/Events/LaravelDomainEventDispatcher.php @@ -10,8 +10,58 @@ use Shared\DDD\Event as LibEvent; class LaravelDomainEventDispatcher implements DomainEventDispatcher { + private int $bufferDepth = 0; + + /** @var list<\Shared\DDD\Event> */ + private array $bufferedEvents = []; + + public function beginBuffering(): void + { + $this->bufferDepth++; + } + + #[\Override] public function dispatch(LibEvent $event): void { + if ($this->bufferDepth > 0) { + $this->bufferedEvents[] = $event; + + return; + } + Event::dispatch($event); } + + public function flush(): void + { + if ($this->bufferDepth === 0) { + return; + } + + $this->bufferDepth--; + + if ($this->bufferDepth > 0) { + return; + } + + $events = $this->bufferedEvents; + $this->bufferedEvents = []; + + foreach ($events as $event) { + Event::dispatch($event); + } + } + + public function discard(): void + { + if ($this->bufferDepth === 0) { + return; + } + + $this->bufferDepth--; + + if ($this->bufferDepth === 0) { + $this->bufferedEvents = []; + } + } } diff --git a/infra/Adapters/Locks/LaravelCacheLock.php b/infra/Adapters/Locks/LaravelCacheLock.php new file mode 100644 index 00000000..340d3c32 --- /dev/null +++ b/infra/Adapters/Locks/LaravelCacheLock.php @@ -0,0 +1,53 @@ +cache->getStore(); + + if (! $store instanceof LockProvider) { + throw new \UnexpectedValueException('Cache store does not implement LockProvider.'); + } + + $lock = $store->lock($key, $ttlSeconds); + + try { + return $lock->block($waitSeconds, $callback); + } catch (LaravelLockTimeoutException $e) { + throw new LockTimeoutException( + message: $e->getMessage(), + code: (int) $e->getCode(), + previous: $e, + ); + } + } +} diff --git a/infra/Adapters/Repositories/EloquentOrderRepository.php b/infra/Adapters/Repositories/EloquentOrderRepository.php index 4bb5a236..23d3c094 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; @@ -15,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 { @@ -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(UuidHelper::fromString($id)), + $ids, + ); + } + #[\Override] public function persist(DomainOrder $order): void { @@ -131,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/EloquentPickupExceptionRepository.php b/infra/Adapters/Repositories/EloquentPickupExceptionRepository.php index ae9d8cfb..b150d16d 100644 --- a/infra/Adapters/Repositories/EloquentPickupExceptionRepository.php +++ b/infra/Adapters/Repositories/EloquentPickupExceptionRepository.php @@ -59,8 +59,8 @@ class EloquentPickupExceptionRepository implements PickupExceptionRepository ->firstOrFail(); return $shop->pickupExceptions() - ->where('date', '>', $period->getStartDate()->toImmutable()) - ->where('date', '<=', $period->getEndDate()?->toImmutable()) + ->where('date', '>=', $period->getStartDate()->format('Y-m-d')) + ->where('date', '<=', $period->getEndDate()?->format('Y-m-d')) ->get() ->map(fn (PickupException $ex) => $this->toShopDomain($ex, $ex->pivot)) ->all(); diff --git a/infra/Adapters/Repositories/EloquentProductRepository.php b/infra/Adapters/Repositories/EloquentProductRepository.php index 10e3884b..b1aaafee 100644 --- a/infra/Adapters/Repositories/EloquentProductRepository.php +++ b/infra/Adapters/Repositories/EloquentProductRepository.php @@ -7,12 +7,14 @@ namespace Infrastructure\Adapters\Repositories; use App\Models\Product; use Carbon\CarbonImmutable; 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 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 { @@ -27,6 +29,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 { @@ -63,6 +96,10 @@ class EloquentProductRepository implements ProductRepository ->delete(); } + /** + * @throws \Domain\Exceptions\OrderTunnel\UnorderableProductException + */ + #[\Override] public function getBasketProduct(ProductId $id, int $qty): BasketProduct { $product = Product::query() @@ -71,7 +108,12 @@ class EloquentProductRepository implements ProductRepository ->firstOrFail(); $domainProduct = $this->toEntity($product); - $pricing = $domainProduct->pricing(); + + if (! $domainProduct->isOrderable()) { + throw new UnorderableProductException(); + } + + $pricing = $domainProduct->pricing(); return new BasketProduct( id: $id, @@ -97,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/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; } } } diff --git a/infra/Adapters/Serializers/BasketSerializer.php b/infra/Adapters/Serializers/BasketSerializer.php index 5d8f3fa4..16a9121c 100644 --- a/infra/Adapters/Serializers/BasketSerializer.php +++ b/infra/Adapters/Serializers/BasketSerializer.php @@ -16,7 +16,9 @@ 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; class BasketSerializer { @@ -58,75 +60,72 @@ 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', []); - - 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 !== '' ? $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( - id: new BasketId(Uuid::fromString($basketId)), + id: new BasketId(UuidHelper::fromString($basketId)), items: $hydratedItems ); } + /** + * @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(UuidHelper::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/infra/Adapters/Services/AppAdminAuthService.php b/infra/Adapters/Services/AppAdminAuthService.php index e19ed67a..65b0dd3e 100644 --- a/infra/Adapters/Services/AppAdminAuthService.php +++ b/infra/Adapters/Services/AppAdminAuthService.php @@ -4,9 +4,9 @@ declare(strict_types=1); namespace Infrastructure\Adapters\Services; -use App\Exceptions\AuthServiceException; use App\Models\User; use Domain\Contracts\AdminDetails; +use Domain\Exceptions\AuthServiceException; use Domain\Ports\Services\AdminAuthenticationService; use Illuminate\Contracts\Auth\StatefulGuard; diff --git a/infra/Adapters/Services/AppCustomerAuthService.php b/infra/Adapters/Services/AppCustomerAuthService.php index 4e4ad4fe..9007d199 100644 --- a/infra/Adapters/Services/AppCustomerAuthService.php +++ b/infra/Adapters/Services/AppCustomerAuthService.php @@ -4,12 +4,11 @@ declare(strict_types=1); namespace Infrastructure\Adapters\Services; -use App\Exceptions\AuthServiceException; -use App\Exceptions\CrmServiceException; use App\Models\Customer; -use App\Services\CrmService; use Domain\Contracts\CustomerDetails; +use Domain\Exceptions\AuthServiceException; use Domain\Models\ValueObjects\CrmCustomer; +use Domain\Ports\Services\CrmCustomerGatewayService; use Domain\Ports\Services\CustomerAuthenticationService; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\StatefulGuard; @@ -19,7 +18,7 @@ class AppCustomerAuthService implements CustomerAuthenticationService { public function __construct( private readonly StatefulGuard $guard, - private readonly CrmService $crmService + private readonly CrmCustomerGatewayService $crmService ) { } @@ -108,7 +107,7 @@ class AppCustomerAuthService implements CustomerAuthenticationService { $crmCustomer = $this->crmService->getCustomerFromHashCode($customer->hashcode); - if ($crmCustomer instanceof CrmServiceException) { + if ($crmCustomer instanceof \Exception) { report($crmCustomer); throw $crmCustomer; 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)); } } diff --git a/infra/Adapters/Services/CsvGeneratorImpl.php b/infra/Adapters/Services/CsvGeneratorImpl.php index aabefc38..81677acc 100644 --- a/infra/Adapters/Services/CsvGeneratorImpl.php +++ b/infra/Adapters/Services/CsvGeneratorImpl.php @@ -5,7 +5,6 @@ declare(strict_types=1); namespace Infrastructure\Adapters\Services; use Domain\Ports\Services\CsvGenerator; -use SplTempFileObject; class CsvGeneratorImpl implements CsvGenerator { @@ -15,7 +14,7 @@ class CsvGeneratorImpl implements CsvGenerator */ public function generate(array $header, array $rows): string { - $file = new SplTempFileObject(); + $file = new \SplTempFileObject(); $file->fputcsv( $header, 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/infra/Adapters/Services/EloquentEmployeeStatisticsService.php b/infra/Adapters/Services/EloquentEmployeeStatisticsService.php index f0b28152..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) - ->where('status', OrderStatus::VALIDATED) + ->whereIn('status', [OrderStatus::VALIDATED, OrderStatus::PENDING]) ->whereBetween('pickup_day', [$start, $end]) ->sum('total'); diff --git a/infra/Adapters/Services/SessionOrderBuilderManager.php b/infra/Adapters/Services/SessionOrderBuilderManager.php index 0639972f..6cc316eb 100644 --- a/infra/Adapters/Services/SessionOrderBuilderManager.php +++ b/infra/Adapters/Services/SessionOrderBuilderManager.php @@ -4,8 +4,7 @@ declare(strict_types=1); namespace Infrastructure\Adapters\Services; -use Domain\Builders\OrderBuilder; -use Domain\Builders\OrderBuilderTyped; +use Domain\Builders\OrderBuilderWithBasket; use Domain\Ports\Services\OrderBuilderSessionManager; use Illuminate\Contracts\Session\Session; @@ -22,22 +21,25 @@ class SessionOrderBuilderManager implements OrderBuilderSessionManager ); } - public function get(): ?OrderBuilderTyped + #[\Override] + public function get(): ?OrderBuilderWithBasket { $orderBuilder = $this->session->get($this->sessionKey); - if ($orderBuilder !== null && ! ($orderBuilder instanceof OrderBuilder)) { + if ($orderBuilder !== null && ! ($orderBuilder instanceof OrderBuilderWithBasket)) { throw new \UnexpectedValueException('Invalid session data for order builder'); } return $orderBuilder; } - public function save(OrderBuilder $builder): void + #[\Override] + public function save(OrderBuilderWithBasket $builder): void { $this->session->put($this->sessionKey, $builder); } + #[\Override] public function clear(): void { $this->session->forget($this->sessionKey); diff --git a/lang/en.json b/lang/en.json index 131a3f6d..7d667910 100644 --- a/lang/en.json +++ b/lang/en.json @@ -1,4 +1,5 @@ { + "(:extensions, :maxSize MB max)": "(:extensions, :maxSize MB max)", "(and :count more error)": "(and :count more error)", "(and :count more errors)": "(and :count more error)|(and :count more errors)|(and :count more errors)", "- at least one lowercase letter": "- at least one lowercase letter", @@ -16,6 +17,7 @@ ":title Freshness & Quality :/title :desc Your order is carefully prepared, with strict adherence to the cold chain :/desc": ":title Freshness & Quality :/title :desc Your order is carefully prepared, with strict adherence to the cold chain :/desc", ":title Pick up your order :/title :desc :/desc": ":title Pick up your order :/title :desc :/desc", ":title Save money :/title :desc Get even more out of our gourmet products by buying directly :/desc": ":title Save money :/title :desc Get even more out of our gourmet products by buying directly :/desc", + ":title Select :/title :desc your pickup day :/desc": ":title Select :/title :desc your pickup day :/desc", ":title Select :/title :desc your products online :/desc": ":title Select :/title :desc your products online :/desc", ":title Select :/title :desc your time slot :/desc": ":title Select :/title :desc your time slot :/desc", "A confirmation has just been sent to the email address": "A confirmation has just been sent to the email address", @@ -50,6 +52,7 @@ "All products have been selected.": "All products have been selected.", "All rights reserved.": "All rights reserved.", "Allergens": "Allergens", + "Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px": "Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px", "Already registered?": "Already registered?", "Already Reported": "Already Reported", "An account is already associated with this email address": "An account is already associated with this email address", @@ -57,6 +60,7 @@ "An error has occurred.": "An error has occurred.", "An error has occurred. Please try again later": "An error occurred, please try again later.", "An error occurred while fetching the preview.": "An error occurred while fetching the preview.", + "An error occurred while validating your order. Please try again later.": "An error occurred while validating your order. Please try again later.", "An error occurred, please try again later.": "An error occurred, please try again later.", "An error occurred, please try again with a new activation link.": "An error occurred, please try again with a new activation link.", "An order was placed": "An order was placed", @@ -83,6 +87,8 @@ "Automated message": "Automated message", "Available days": "Available days", "Available products": "Available products", + "Average basket price": "Average basket price", + "Average number of items per order": "Average number of items per order", "Average nutritional values": "Average nutritional values", "Average product weight": "Average product weight", "Back": "Back", @@ -106,6 +112,8 @@ "Call the :phone": "Call the :phone", "Cancel": "Cancel", "Cancel the order": "Cancel the order", + "Canceled orders": "Canceled orders", + "Cancellation rate": "Cancellation rate", "Carbohydrates": "Carbohydrates", "Catalog": "Catalog", "Change my password": "Change my password", @@ -357,9 +365,6 @@ "Item removed from basket": "Item removed from basket", "jj": "jj", "joinedfile": "joinedfile", - "JPEG/PNG, 2MB max.": "JPEG/PNG, 2MB max.", - "JPEG/PNG, 2MB max. Recommended dimensions: :width px by :height px": "JPEG/PNG, 2MB max. Recommended dimensions: :width px by :height px", - "JPEG/PNG, 2Mo max.": "JPEG/PNG, 2Mo max.", "Kcal": "Kcal", "Keyword information": "Keyword information", "Keywords associated with the product": "Keywords associated with the product", @@ -470,6 +475,7 @@ "Not Implemented": "Not Implemented", "Not Modified": "Not Modified", "Not visible": "Not visible", + "Number of active customers": "Number of active customers", "Number of employees": "Number of employees", "Number of registered employees": "Number of registered employees", "Nutrient": "Nutrient", @@ -488,6 +494,7 @@ "OK": "OK", "Old password": "Old password", "On": "On", + "One or more products in your basket are no longer available for order.": "One or more products in your basket are no longer available for order.", "Oops! An error occurred...": "Oops! An error occurred...", "Open": "Open", "Open in a current window": "Open in a current window", @@ -501,6 +508,7 @@ "Order detail of :date": "Order detail of :date", "Order details": "Order details", "Order details:": "Order details:", + "Order frequency": "Order frequency", "Order number": "Order number", "Order period": "Order period", "Order Reference": "Order Reference", @@ -509,6 +517,8 @@ "Order status": "Order status", "Order summary": "Order summary", "Order validation": "Order validation", + "Orders at D+14": "Orders at D+14", + "Orders at D+7": "Orders at D+7", "Origin Is Unreachable": "Origin Is Unreachable", "Original price": "Original price", "Our team will do their best to reply as soon as possible.": "Our team will do their best to reply as soon as possible.", @@ -520,6 +530,7 @@ "Password updated": "Password updated", "Payload Too Large": "Payload Too Large", "Payment Required": "Payment Required", + "Pending orders": "Pending orders", "Per": "Per", "Per 100g / Ref": "Per 100g / Ref", "Per Serving": "Per Serving", @@ -584,6 +595,7 @@ "Proxy Authentication Required": "Proxy Authentication Required", "Publication period": "Publication period", "Published": "Published", + "Purchase frequency": "Purchase frequency", "Quantity": "Quantity", "Quantity controls": "Quantity controls", "Quantity in Basket": "Quantity in Basket", @@ -600,6 +612,7 @@ "Reference Weight": "Reference Weight", "Regards,": "Regards,", "Register": "Register", + "Registration is already in progress. Please try again in a moment.": "Registration is already in progress. Please try again in a moment.", "Registration procedure for the shop.": "Registration procedure for the shop.", "Remember Me": "Remember Me", "Remember to validate your order before :closureTime on :url": "Remember to validate your order before :closureTime on :url", @@ -751,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.", @@ -766,6 +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 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", @@ -780,6 +796,8 @@ "Total": "Total", "Total %": "Total %", "Total (including tax)": "Total (including tax)", + "Total amount HT": "Total amount HT", + "Total amount TTC": "Total amount TTC", "Total for this product: :total": "Total for this product: :total", "Total in €": "Total in €", "Total Price (excluding tax)": "Total Price (excluding tax)", @@ -816,6 +834,7 @@ "User": "User", "Validate my basket": "Validate my basket", "Validate my basket and proceed to reservation": "Validate my basket and proceed to reservation", + "Validated orders": "Validated orders", "Validation of your order.": "Validation of your order.", "Validity period": "Validity period", "Variable weight product": "Variable weight product", @@ -869,6 +888,7 @@ "Your old password does not match.": "Your old password does not match.", "Your order": "Your order", "Your order - :appname": "Your order - :appname", + "Your order is already being processed. Please wait a moment and try again.": "Your order is already being processed. Please wait a moment and try again.", "Your order is ready for collection today at your collection point!": "Your order is ready for collection today at your collection point!", "Your order is registered!": "Your order is registered!", "Your order session has expired or is invalid. Please review your basket.": "Your order session has expired or is invalid. Please review your basket.", 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/en/validation.php b/lang/en/validation.php index c5f8ae1b..d9a5722f 100644 --- a/lang/en/validation.php +++ b/lang/en/validation.php @@ -288,4 +288,11 @@ return [ 'work' => 'work', 'year' => 'year', ], + 'custom' => [ + 'birth_date' => [ + 'before_or_equal' => 'You must be of legal age to register.', + 'date' => 'Please enter a valid birth date.', + 'date_format' => 'Please enter a valid birth date.', + ], + ], ]; diff --git a/lang/fr.json b/lang/fr.json index 81e5292d..a65f0975 100644 --- a/lang/fr.json +++ b/lang/fr.json @@ -1,4 +1,5 @@ { + "(:extensions, :maxSize MB max)": "(:extensions, :maxSize Mo max)", "(and :count more error)": "(et :count erreur en plus)", "(and :count more errors)": "(et :count erreur en plus)|(et :count erreurs en plus)|(et :count erreurs en plus)", "- at least one lowercase letter": "- au moins une minuscule", @@ -18,6 +19,8 @@ ":title Save money :/title :desc Get even more out of our gourmet products by buying directly :/desc": ":title Des économies :/title :desc Profitez encore plus de nos produits gourmands en achetant en direct :/desc", ":title Select :/title :desc your pickup day :/desc": ":title Choisissez :/title :desc votre jour de retrait :/desc", ":title Select :/title :desc your products online :/desc": ":title Sélectionnez :/title :desc vos produits en ligne :/desc", + ":title Select :/title :desc your time slot :/desc": ":title Choisissez :/title :desc votre créneau :/desc", + "A confirmation has just been sent to the email address": "Une confirmation vient d'être envoyée à l'adresse e-mail", "A confirmation has just been sent to your email address": "Une confirmation vient de vous être envoyée sur votre adresse e-mail", "A decryption key is required.": "Une clé de déchiffrement est requise.", "A fresh verification link has been sent to your email address.": "Un nouveau lien de vérification a été envoyé à votre adresse e-mail.", @@ -49,6 +52,7 @@ "All products have been selected.": "Tous les produits ont été sélectionnés.", "All rights reserved.": "Tous droits réservés.", "Allergens": "Allergènes", + "Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px": "Extensions autorisées : :extensions (:maxSize Mo max). Dimensions requises : :width px par :height px", "Already registered?": "Déjà inscrit ?", "Already Reported": "Déjà rapporté", "An account is already associated with this email address": "Un compte est déjà associé à cette adresse e-mail", @@ -56,6 +60,7 @@ "An error has occurred.": "Une erreur est survenue.", "An error has occurred. Please try again later": "Une erreur est survenue, merci de réessayer ultérieurement", "An error occurred while fetching the preview.": "Une erreur est survenue lors de la récupération de la prévisualisation.", + "An error occurred while validating your order. Please try again later.": "Une erreur est survenue lors de la validation de votre commande, merci de réessayer ultérieurement.", "An error occurred, please try again later.": "Une erreur est survenue, merci de réessayer ultérieurement", "An error occurred, please try again with a new activation link.": "Une erreur est survenue, veuillez réessayer avec un nouveau lien d'activation.", "An order was placed": "Une commande a été passée", @@ -82,6 +87,8 @@ "Automated message": "Message automatisé", "Available days": "Jours disponibles", "Available products": "Produits disponibles", + "Average basket price": "Prix du panier moyen", + "Average number of items per order": "Nombre d'article moyen par commande", "Average nutritional values": "Valeurs nutritionnelles moyennes", "Average product weight": "Poids moyen du produit", "Back": "Retour", @@ -105,6 +112,8 @@ "Call the :phone": "Appeler le :phone", "Cancel": "Annuler", "Cancel the order": "Annuler la commande", + "Canceled orders": "Commandes annulées", + "Cancellation rate": "Taux d'abandon", "Carbohydrates": "Glucides", "Catalog": "Catalogue", "Change my password": "Changer mon mot de passe", @@ -140,6 +149,7 @@ "Collapse": "Réduire", "Collapse All": "Réduire tout", "Collection date": "Date de collecte", + "Collection date:": "Date de collecte :", "Collection details": "Détails du retrait", "Collection information": "Informations de retrait", "Collection point": "Point de retrait", @@ -223,6 +233,7 @@ "Edit :name": "Modifier :name", "email": "E-mail", "Email Address": "Adresse e-mail", + "Email:": "E-mail :", "Employee site codes (Arcadia)": "Codes des sites des salariés (Arcadia)", "Employee sites": "Sites des salariés", "Employees Sync": "Syncronisation des salariés", @@ -307,6 +318,7 @@ "Gone": "Disparu", "GPS & Maps Coordinates": "Coordonnées GPS & Maps", "Hello": "Bonjour", + "Hello :fullname": "Bonjour :fullname", "Hello!": "Bonjour !", "Here is a message sent from :app_name.": "Voici un message envoyé depuis :app_name.", "Here, the arrows are used to sort and not to filter": "Ici, les flèches servent à trier et non pas à filtrer", @@ -353,9 +365,6 @@ "Item removed from basket": "Article retiré du panier", "jj": "jj", "joinedfile": "Pièce jointe", - "JPEG/PNG, 2MB max.": "JPEG/PNG, 2Mo max.", - "JPEG/PNG, 2MB max. Recommended dimensions: :width px by :height px": "JPEG/PNG, 2Mo max. Dimensions conseillées : :width px par :height px", - "JPEG/PNG, 2Mo max.": "JPEG/PNG, 2Mo max.", "Kcal": "Kcal", "Keyword information": "Informations du mot clé", "Keywords associated with the product": "Les mots clés associés au produit", @@ -384,6 +393,7 @@ "Localize": "Localiser", "Location": "Emplacement", "Location on the map": "Emplacement sur la carte", + "Location:": "Emplacement :", "Locked": "Verrouillé", "Log In": "Se connecter", "Log in": "Connectez-vous", @@ -406,6 +416,7 @@ "Merchandising": "Merchandising", "Message": "Message", "Message subject": "Objet du message", + "Message:": "Message :", "message_contact_failed": "Une erreur est survenue durant l'envoi de votre message. Veuillez réessayer ultèrieurement.", "message_contact_send": "Votre message a été envoyé avec succès.", "Method Not Allowed": "Méthode non autorisée", @@ -464,6 +475,7 @@ "Not Implemented": "Non implémenté", "Not Modified": "Non modifié", "Not visible": "Non visible", + "Number of active customers": "Nombre de clients actifs", "Number of employees": "Nombre de salariés", "Number of registered employees": "Nombre de salariés inscrits", "Nutrient": "Nutriment", @@ -482,6 +494,7 @@ "OK": "OK", "Old password": "Ancien mot de passe", "On": "Le", + "One or more products in your basket are no longer available for order.": "Un ou plusieurs produits de votre panier ne sont plus disponibles à la commande.", "Oops! An error occurred...": "Oups ! Une erreur s'est produite...", "Open": "Ouvrir", "Open in a current window": "Ouvrir dans une fenêtre actuelle", @@ -494,13 +507,18 @@ "Order data": "Données de la commande", "Order detail of :date": "Détail de votre commande du :date", "Order details": "Détails de la commande", + "Order details:": "Détails de la commande :", + "Order frequency": "Fréquence de commande", "Order number": "Numéro de commande", "Order period": "Période de commande", "Order Reference": "Référence de commande", + "Order Reference:": "Référence de commande :", "Order reservation": "Réservation de commande", "Order status": "Etat de votre commande", "Order summary": "Récapitulatif de commande", "Order validation": "Validation de commande", + "Orders at D+14": "Nombre de commandes à J+14", + "Orders at D+7": "Nombre de commandes à J+7", "Origin Is Unreachable": "L'origine est inaccessible", "Original price": "Prix d'origine", "Our team will do their best to reply as soon as possible.": "Nos services mettent tout en oeuvre pour y répondre au plus vite.", @@ -512,6 +530,7 @@ "Password updated": "Mot de passe mis à jour", "Payload Too Large": "Charge utile trop grande", "Payment Required": "Paiement requis", + "Pending orders": "Commandes en attente", "Per": "Pour", "Per 100g / Ref": "Pour 100g / Réf", "Per Serving": "Par portion", @@ -522,6 +541,7 @@ "Phone": "Téléphone", "Pickup day": "Jour de retrait", "Pickup Locations": "Point de retrait|Points de retraits", + "Pickup on :day at :time, at the following address:": "À retirer le :day à :time, à l'adresse suivante :", "Pickup on :day, at the following address:": "A retirer le :day, à l'adresse suivante :", "Pickup point name": "Nom du point de retrait", "Place my order :appname": "Passer ma commande :appname", @@ -575,6 +595,7 @@ "Proxy Authentication Required": "Authentification proxy requise", "Publication period": "Période de parution", "Published": "Publié", + "Purchase frequency": "Fréquence d'achat", "Quantity": "Quantité", "Quantity controls": "Contrôle de la quantité", "Quantity in Basket": "Quantité dans le panier", @@ -591,11 +612,13 @@ "Reference Weight": "Poids de référence", "Regards,": "Cordialement,", "Register": "Inscription", + "Registration is already in progress. Please try again in a moment.": "Une inscription est déjà en cours. Veuillez réessayer dans un instant.", "Registration procedure for the shop.": "Procédure d'inscription à la boutique.", "Remember Me": "Se souvenir de moi", "Remember to validate your order before :closureTime on :url": "Pensez à valider votre commande avant :closureTime sur :url", "Remember to validate your order on :url": "Pensez à bien valider votre commande sur :url", "Reminder of your order ref: :ref": "Rappel de votre commande ref: :ref", + "Reminder of your order ref: :ref:": "Rappel de votre commande ref : :ref :", "Remove from Basket": "Retirer du panier", "Removed :amount from basket": ":amount retiré(s) du panier", "Repeatable": "Répétable", @@ -651,6 +674,7 @@ "Send": "Envoyer", "Send Password Reset Link": "Envoyer le lien de réinitialisation du mot de passe", "Sender": "Expéditeur", + "Sender:": "Expéditeur :", "Server Error": "Erreur serveur", "Service": "Service", "Service Unavailable": "Service indisponible", @@ -740,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.", @@ -755,12 +780,15 @@ "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 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": "à", "To be collected on": "À retirer le", "To date": "Jusqu'au", "To update your personal information, fill in the new data below": "Pour modifier vos informations personnelles, renseignez vos nouvelles données ci-dessous", + "To update your personal information, fill in the new data below:": "Pour modifier vos informations personnelles, renseignez vos nouvelles données ci-dessous :", "Today's Orders": "Commandes du jour", "Toggle navigation": "Afficher / masquer le menu de navigation", "Too Early": "Trop tôt", @@ -768,11 +796,14 @@ "Total": "Total", "Total %": "Total %", "Total (including tax)": "Total TTC", + "Total amount HT": "Montant total HT", + "Total amount TTC": "Montant total TTC", "Total for this product: :total": "Total pour ce produit : :total", "Total in €": "Total en €", "Total Price (excluding tax)": "Prix Total HT", "Total to pay": "Total à payer", "Total TTC": "Total TTC", + "Total TTC:": "Total TTC :", "town": "Ville", "Translate": "Traduire", "Translate It": "Traduis le", @@ -803,6 +834,7 @@ "User": "Utilisateur", "Validate my basket": "Valider mon panier", "Validate my basket and proceed to reservation": "Valider mon panier et passer à la réservation", + "Validated orders": "Commandes validées", "Validation of your order.": "Validation de votre commande.", "Validity period": "Période de validité", "Variable weight product": "Produit à poids variable", @@ -856,6 +888,7 @@ "Your old password does not match.": "L'ancien mot de passe ne correspond pas.", "Your order": "Votre commande", "Your order - :appname": "Votre commande - :appname", + "Your order is already being processed. Please wait a moment and try again.": "Votre commande est déjà en cours de traitement. Veuillez patienter un instant et réessayer.", "Your order is ready for collection today at your collection point!": "Votre commande est à récupérer aujourd\\u0027hui dans votre point de retrait !", "Your order is registered!": "Votre commande est enregistrée !", "Your order session has expired or is invalid. Please review your basket.": "Votre session de commande a expiré ou est invalide. Veuillez vérifier votre panier.", 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/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/manifest.yaml b/manifest.yaml index 65ea3535..5d7c09cb 100644 --- a/manifest.yaml +++ b/manifest.yaml @@ -3,81 +3,159 @@ 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" + LOG_LEVEL: "warning" 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_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: {} + - name: laravel-logs + emptyDir: {} + - name: tmp + 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 + - name: laravel-logs + mountPath: /app/srcs/storage/logs + - name: tmp + mountPath: /tmp + 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 +163,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: @@ -109,19 +189,19 @@ spec: - 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 + - 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 + # TODO : a priori incompatible avec PVC + # allowPrivilegeEscalation: false --- apiVersion: v1 kind: Service @@ -131,8 +211,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 +231,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 +295,66 @@ 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: {} + - name: laravel-logs + emptyDir: {} + - name: tmp + 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 + - name: laravel-logs + mountPath: /app/srcs/storage/logs + - name: tmp + mountPath: /tmp + 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 diff --git a/phpcs.xml b/phpcs.xml index 28974ae0..e5858019 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -11,13 +11,15 @@ app/ config/ database/ + domain/ + infra/ routes/ + shared/ tests/ */vendor/* */storage/* _ide_helper.php - */tests/* @@ -69,4 +71,8 @@ */database/migrations/* + + */tests/* + + diff --git a/phpstan.neon b/phpstan.neon index 49120889..d8f5f013 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,15 +1,19 @@ includes: - vendor/larastan/larastan/extension.neon - vendor/nesbot/carbon/extension.neon + - vendor/pestphp/pest-plugin-phpstan/extension.neon + - vendor/phpstan/phpstan-mockery/extension.neon + - vendor/phpstan/phpstan-webmozart-assert/extension.neon parameters: paths: - app/ - domain/ - infra/ + - shared/ + - tests/ - # Level 9 is the highest level - level: 9 + level: 10 # Enforce strict types analysis treatPhpDocTypesAsCertain: false diff --git a/phpunit.xml b/phpunit.xml index c3216a6a..57548422 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -19,7 +19,7 @@ - + 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 diff --git a/resources/ts/bo/components/ImageInputComponent.vue b/resources/ts/bo/components/ImageInputComponent.vue index 0afdfa08..8c3b23b7 100644 --- a/resources/ts/bo/components/ImageInputComponent.vue +++ b/resources/ts/bo/components/ImageInputComponent.vue @@ -31,17 +31,10 @@ @change="pictureInputHasChanged" type="file" class="d-none" - :name="`${fileParamIsFile ? parameters.name : ''}`" - accept=".jpg,.jpeg,.gif,.png" + :name="fileParamIsFile ? parameters.name : undefined" + :accept="parameters.accept" :aria-describedby="`Help${parameters.id}`" > - { + if (!val) { + return ""; + } + if (/^https?:\/\//i.test(val) || val.startsWith("data:")) { + return val; + } + return val.replace(/^\/|^/, "/"); +}; + +const getFileName = (val: string): string => { + if (!val) { + return ""; + } + const clean = val.split("?")[0].split("#")[0]; + const lastSlash = clean.lastIndexOf("/"); + return lastSlash !== -1 ? decodeURIComponent(clean.substring(lastSlash + 1)) : clean; +}; + defineOptions({ name: "ImageInputComponent" }); // * EMITS @@ -496,6 +508,10 @@ const props = defineProps({ type: String, default: "" }, + accept: { + type: String, + default: ".jpg,.jpeg,.png" + }, required: { type: Boolean, default: false @@ -537,6 +553,7 @@ const parameters = reactive<{ id: string, name: string, helper: string, + accept: string, required: boolean, showLabels: boolean, preview: boolean, @@ -550,6 +567,7 @@ const parameters = reactive<{ id: props.id, name: props.name, helper: props.helper, + accept: props.accept, required: props.required, showLabels: props.showLabels, preview: props.preview, @@ -574,7 +592,7 @@ const fileParameters = reactive<{ }>({ file: null, filePath: "", - fileName: "", + fileName: __("vue.ImageInputComponent.choose_a_file"), dimensions: { height: 0, width: 0, @@ -585,10 +603,10 @@ const fileParameters = reactive<{ const fileDataUrl = ref(null); /** - * The file we shall output : - * - String when having an already stored picture - * - File when we have a File fron the input or cropped component - * - null when noting +- The file we shall output : +- String when having an already stored picture +- File when we have a File fron the input or cropped component +- null when noting */ const fileOutput = ref(null); @@ -637,14 +655,14 @@ onMounted(() => { parameters.required = Boolean(data.required); parameters.showLabels = Boolean(data.showLabels); parameters.browseEvent = Boolean(data.browseEvent); - const value = data.value; - if (typeof value === "string" && value.length) { - fileParameters.filePath = value.replace(/^\/|^/, ""); - fileParameters.fileName = value.replace(/^\/|^/, ""); - fileOutput.value = fileParameters.filePath; + const value = String(data.value ?? ""); + if (value.length) { + fileParameters.filePath = formatUrl(value); + fileParameters.fileName = getFileName(value); + fileDataUrl.value = fileParameters.filePath; + hasPicture.value = true; } } - fetchPictureFromPath(fileParameters.filePath); initTooltips(); }); @@ -659,14 +677,23 @@ watch(props, (newValue: typeof props) => { assignFromProps(); previousPropValue.value = newValue.value; }, { deep: true }); -watch(previousPropValue, () => { +watch(previousPropValue, (newValue: string) => { // * Ignore non prop usage. if (!isUsedWithProps.value) { return; } + if (!newValue.length) { + resetComponent(); + return; + } cropperReset(); hasCroppedPicture.value = false; - fetchPictureFromPath(fileParameters.filePath)!.then((file) => useThis(file)); + if (parameters.browseEvent) { + fetchPictureFromPath(fileParameters.filePath)?.then((file) => { + useThis(file); + fileOutput.value = file; + }); + } }); /** Crop parameters changes. */ watch(cropperParameters, (newValue: CropperParameters) => { @@ -708,14 +735,22 @@ watch(fileDataUrl, (newValue) => { // * METHODS function assignFromProps(): void { - fileParameters.filePath = props.value.replace(/^\/|^/, ""); - fileParameters.fileName = props.value.replace(/^\/|^/, ""); - fileOutput.value = fileParameters.filePath; + if (props.value.length) { + fileParameters.filePath = formatUrl(props.value); + fileParameters.fileName = getFileName(props.value); + fileDataUrl.value = fileParameters.filePath; + hasPicture.value = true; + } else if (!fileParamIsFile.value) { + fileParameters.filePath = ""; + fileParameters.fileName = __("vue.ImageInputComponent.choose_a_file"); + fileDataUrl.value = null; + hasPicture.value = false; + } const mapParam = (dest: T, prop: keyof T, value: ValueOf) => { dest[prop] = value; }; - for (const key of ["id", "name", "helper", "required", "showLabels", "preview", "browseEvent"]) { + for (const key of ["id", "name", "helper", "accept", "required", "showLabels", "preview", "browseEvent"]) { const paramKey = key as keyof typeof parameters; mapParam(parameters, paramKey, props[paramKey as never]); } @@ -752,6 +787,28 @@ function cropperReset(): void { lastAppliedRotation = 0; } +/** Replace the filename extension so it matches the encoded MIME type. */ +function replaceFileExtension(fileName: string, extension: string): string { + const cleanName = fileName.trim(); + if (!cleanName || cleanName === __("vue.ImageInputComponent.choose_a_file")) { + return `image.${extension}`; + } + const dotIndex = cleanName.lastIndexOf("."); + if (dotIndex <= 0) { + return `${cleanName}.${extension}`; + } + + return `${cleanName.slice(0, dotIndex)}.${extension}`; +} + +function isJpegFile(file: File | null, fileName: string): boolean { + if (file?.type) { + return file.type === "image/jpeg"; + } + + return /\.(jpe?g)$/i.test(fileName); +} + /** Export cropped file from cropper. */ async function exportCropperFile(): Promise { const selection = cropperInstance.value?.getCropperSelection(); @@ -760,12 +817,15 @@ async function exportCropperFile(): Promise { } const outputWidth = Math.max(1, Math.trunc(parameters.dimensions.width)); const outputHeight = Math.max(1, Math.trunc(parameters.dimensions.height)); + const useJpeg = isJpegFile(fileParameters.file, fileParameters.fileName); + const outputMime = useJpeg ? "image/jpeg" : "image/png"; + const outputExtension = useJpeg ? "jpg" : "png"; hasCroppedPicture.value = true; const canvas = await selection.$toCanvas({ width: outputWidth, height: outputHeight, beforeDraw: (context: CanvasRenderingContext2D) => { - context.fillStyle = "rgba(0, 0, 0, 0)"; + context.fillStyle = useJpeg ? "#ffffff" : "rgba(0, 0, 0, 0)"; context.imageSmoothingEnabled = true; context.imageSmoothingQuality = "high"; }, @@ -780,15 +840,22 @@ async function exportCropperFile(): Promise { } normalizedCtx.imageSmoothingEnabled = true; normalizedCtx.imageSmoothingQuality = "high"; - normalizedCtx.clearRect(0, 0, outputWidth, outputHeight); + if (useJpeg) { + normalizedCtx.fillStyle = "#ffffff"; + normalizedCtx.fillRect(0, 0, outputWidth, outputHeight); + } else { + normalizedCtx.clearRect(0, 0, outputWidth, outputHeight); + } normalizedCtx.drawImage(canvas, 0, 0, outputWidth, outputHeight); - fileDataUrl.value = normalizedCanvas.toDataURL("image/png"); + fileDataUrl.value = useJpeg + ? normalizedCanvas.toDataURL("image/jpeg") + : normalizedCanvas.toDataURL("image/png"); const file = new File( [dataUrltoBlob(fileDataUrl.value)], - fileParameters.fileName, + replaceFileExtension(fileParameters.fileName, outputExtension), { - type: "image/png", + type: outputMime, lastModified: Date.now(), } ); @@ -821,14 +888,14 @@ function fetchPictureFromPath(filePath: string): Promise | void { return; } return new Promise((accept, deny) => nextTick(() => { - const prefixedFilePath: string = filePath.replace(/^\/|^/, "/"), - stringFileName: string = prefixedFilePath.substring(prefixedFilePath.lastIndexOf("/")).replace(/^\/|^/, ""); + const prefixedFilePath: string = formatUrl(filePath), + stringFileName: string = getFileName(prefixedFilePath); fetch(prefixedFilePath) .then((response) => response.blob()) .then((blob: Blob) => { const file = new File([blob], stringFileName, { - type: "image/png", + type: blob.type || "image/png", lastModified: Date.now(), }); setFileAsDataUrl(file); @@ -904,12 +971,7 @@ function prepareImageEditor(): void { lastAppliedRotation = 0; }; - if (fileParameters.file === null) { - throw new Error("File nust not be null"); - } - const editorImg = imgEditor.value!; - const blobUrl = URL.createObjectURL(fileParameters.file); const initCropperAfterLoad = () => { editorImg.removeEventListener("load", initCropperAfterLoad); @@ -922,8 +984,23 @@ function prepareImageEditor(): void { }); }; - editorImg.addEventListener("load", initCropperAfterLoad); - editorImg.src = blobUrl; + if (fileParameters.file !== null) { + editorImg.addEventListener("load", initCropperAfterLoad); + editorImg.src = URL.createObjectURL(fileParameters.file); + return; + } + + if (fileDataUrl.value) { + fetch(formatUrl(fileDataUrl.value)) + .then((response) => response.blob()) + .then((blob: Blob) => { + editorImg.addEventListener("load", initCropperAfterLoad); + editorImg.src = URL.createObjectURL(blob); + }); + return; + } + + throw new Error("File must not be null"); } /** Reset the entire component state. */ @@ -992,8 +1069,8 @@ function setupCropperViewer(): boolean { } /** - * Cropper peut injecter sa sélection de manière asynchrone. - * On retente quelques frames pour éviter un preview blanc intermittent. +- Cropper peut injecter sa sélection de manière asynchrone. +- On retente quelques frames pour éviter un preview blanc intermittent. */ function setupCropperViewerWithRetry(maxAttempts = 10): void { let attempts = 0; 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('create', \App\Models\Slide::class) + @can('create', \App\Models\PickupException::class) diff --git a/resources/views/bo/products/form.blade.php b/resources/views/bo/products/form.blade.php index d44b6014..f44050b2 100644 --- a/resources/views/bo/products/form.blade.php +++ b/resources/views/bo/products/form.blade.php @@ -23,11 +23,11 @@ @@ -41,11 +41,11 @@
@@ -62,7 +62,7 @@ $data = [ 'name' => 'tags', 'allowNew' => true, - 'value' => $product->tags ?? [], + 'value' => old('tags', $product->tags ?? []), 'itemsList' => $tags, 'placeholder' => __('Add :name', [ 'name' => trans_choice('models.classes.tags', 1), @@ -130,15 +130,14 @@
@include('bo.modules.input-error', ['inputName' => 'picture']) @php - $jsonPic = [ - 'name' => 'picture', - 'single' => true, - 'width' => 200, - 'height' => 200, - 'preview' => false, - 'helper' => __('JPEG/PNG, 2Mo max.'), - 'value' => $product->picture ?? '', - ]; + $jsonPic = \App\Lib\Helpers\RequestHelper::imageInputConfig( + name: 'picture', + width: \App\Http\Requests\Bo\Products\StoreProductRequest::PICTURE_WIDTH, + height: \App\Http\Requests\Bo\Products\StoreProductRequest::PICTURE_HEIGHT, + maxSizeKb: \App\Http\Requests\Bo\Products\StoreProductRequest::MAX_FILE_SIZE_KB, + allowedExtensions: \App\Http\Requests\Bo\Products\StoreProductRequest::ALLOWED_EXTENSIONS, + value: $product->picture ?? '', + ); @endphp
@@ -187,15 +186,14 @@
@include('bo.modules.input-error', ['inputName' => 'picture_large']) @php - $jsonPicLarge = [ - 'name' => 'picture_large', - 'single' => true, - 'width' => 500, - 'height' => 500, - 'preview' => false, - 'helper' => __('JPEG/PNG, 2MB max.'), - 'value' => $product->picture_large ?? '', - ]; + $jsonPicLarge = \App\Lib\Helpers\RequestHelper::imageInputConfig( + name: 'picture_large', + width: \App\Http\Requests\Bo\Products\StoreProductRequest::PICTURE_LARGE_WIDTH, + height: \App\Http\Requests\Bo\Products\StoreProductRequest::PICTURE_LARGE_HEIGHT, + maxSizeKb: \App\Http\Requests\Bo\Products\StoreProductRequest::MAX_FILE_SIZE_KB, + allowedExtensions: \App\Http\Requests\Bo\Products\StoreProductRequest::ALLOWED_EXTENSIONS, + value: $product->picture_large ?? '', + ); @endphp
@@ -260,11 +258,11 @@
@@ -289,11 +287,11 @@ @@ -311,11 +309,11 @@ @@ -334,11 +332,11 @@ + value="{{ old('weight', isset($product?->product_weight) ? round($product->product_weight->toGrams() / 1000, 3) : '') }}" step="0.001"> @include('bo.modules.input-error', ['inputName' => 'weight'])
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/form.blade.php b/resources/views/bo/ranges/form.blade.php index b80486df..500cd70a 100644 --- a/resources/views/bo/ranges/form.blade.php +++ b/resources/views/bo/ranges/form.blade.php @@ -67,18 +67,14 @@ 'inputName' => 'picture', ]) @php - $json = [ - 'name' => 'picture', - 'single' => true, - 'width' => 500, - 'height' => 500, - 'preview' => false, - 'helper' => __('JPEG/PNG, 2MB max. Recommended dimensions: :width px by :height px', [ - 'width' => 500, - 'height' => 500, - ]), - 'value' => $range->picture ?? '', - ]; + $json = \App\Lib\Helpers\RequestHelper::imageInputConfig( + name: 'picture', + width: \App\Http\Requests\Bo\Ranges\StoreRangeRequest::PICTURE_WIDTH, + height: \App\Http\Requests\Bo\Ranges\StoreRangeRequest::PICTURE_HEIGHT, + maxSizeKb: \App\Http\Requests\Bo\Ranges\StoreRangeRequest::MAX_FILE_SIZE_KB, + allowedExtensions: \App\Http\Requests\Bo\Ranges\StoreRangeRequest::ALLOWED_EXTENSIONS, + value: $range->picture ?? '', + ); @endphp
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/ranges/index.blade.php b/resources/views/bo/ranges/index.blade.php index 288a4256..9192ad15 100644 --- a/resources/views/bo/ranges/index.blade.php +++ b/resources/views/bo/ranges/index.blade.php @@ -15,7 +15,7 @@

- @can('create', \App\Models\Tag::class) + @can('create', \App\Models\Range::class) diff --git a/resources/views/bo/shops/index-filters.blade.php b/resources/views/bo/shops/index-filters.blade.php index c9dd8d58..64a5116d 100644 --- a/resources/views/bo/shops/index-filters.blade.php +++ b/resources/views/bo/shops/index-filters.blade.php @@ -13,7 +13,7 @@ @foreach ($pickupExceptions as $pickupException) @endforeach diff --git a/resources/views/bo/shops/pickup-exceptions.blade.php b/resources/views/bo/shops/pickup-exceptions.blade.php index 7b542fd0..6a921f30 100644 --- a/resources/views/bo/shops/pickup-exceptions.blade.php +++ b/resources/views/bo/shops/pickup-exceptions.blade.php @@ -42,14 +42,14 @@ {!! clean( __('The usual pickup day is :date', [ - 'date' => '' . $pickupPeriod->getEndDate()->translatedFormat('l') . '', + 'date' => '' . $pickupPeriod->getEndDate()->copy()->setTimezone('Europe/Paris')->translatedFormat('l') . '', ]), ) !!}
{!! clean( __('The usual limit to pass an order is :date', [ - 'date' => '' . $pickupPeriod->getStartDate()->translatedFormat('l H\h:i') . '', + 'date' => '' . $pickupPeriod->getStartDate()->copy()->setTimezone('Europe/Paris')->translatedFormat('l H\h:i') . '', ]), ) !!} @@ -82,7 +82,7 @@ ); $order_deadline_at = old( "order_deadline_at.{$exception->id}", - $associatedException?->pivot?->order_deadline_at?->format('Y-m-d\TH:i'), + Date::toLocalInput($associatedException?->pivot?->order_deadline_at), ); $noReplacement = $isChecked && empty($associatedException?->pivot?->replacement_date); @@ -110,7 +110,7 @@ - {{ Date::forHumans(\Carbon\Carbon::parse($exception->date)) }} + {{ Date::forHumansDate($exception->date) }} @if ($dto->isPickupDay) {{ __('Pickup day') }} @@ -131,7 +131,7 @@ {{ __('Replacement date :date', [ - 'date' => Date::forHumans(\Carbon\Carbon::parse($associatedException?->pivot?->replacement_date)), + 'date' => Date::forHumansDate($associatedException?->pivot?->replacement_date), ]) }} @endif @@ -185,7 +185,7 @@
id}" }}" name="order_deadline_at[{{ $exception->id }}]" type="datetime-local" - value="{{ Date::toLocalInput($order_deadline_at) }}"> + value="{{ $order_deadline_at }}"> diff --git a/resources/views/bo/slides/form.blade.php b/resources/views/bo/slides/form.blade.php index 4f9d7dac..ade5b938 100644 --- a/resources/views/bo/slides/form.blade.php +++ b/resources/views/bo/slides/form.blade.php @@ -53,18 +53,14 @@ 'inputName' => 'picture', ]) @php - $json = [ - 'name' => 'picture', - 'single' => true, - 'width' => 1440, - 'height' => 960, - 'preview' => false, - 'helper' => __('JPEG/PNG, 2MB max. Recommended dimensions: :width px by :height px', [ - 'width' => 1440, - 'height' => 960, - ]), - 'value' => $slide->picture ?? '', - ]; + $json = \App\Lib\Helpers\RequestHelper::imageInputConfig( + name: 'picture', + width: \App\Http\Requests\Bo\Slides\StoreSlideRequest::PICTURE_WIDTH, + height: \App\Http\Requests\Bo\Slides\StoreSlideRequest::PICTURE_HEIGHT, + maxSizeKb: \App\Http\Requests\Bo\Slides\StoreSlideRequest::MAX_FILE_SIZE_KB, + allowedExtensions: \App\Http\Requests\Bo\Slides\StoreSlideRequest::ALLOWED_EXTENSIONS, + value: $slide->picture ?? '', + ); @endphp
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/discounts.blade.php b/resources/views/fo/home-parts/sliders/discounts.blade.php index f4c3c75d..476c8389 100644 --- a/resources/views/fo/home-parts/sliders/discounts.blade.php +++ b/resources/views/fo/home-parts/sliders/discounts.blade.php @@ -1,8 +1,8 @@
-

- {!! Str::limit(strip_tags($productWithPricing->product->description), 85, '...') !!} + {{ Str::limit(html_entity_decode(strip_tags($productWithPricing->product->description), ENT_QUOTES | ENT_HTML5, 'UTF-8'), 85, '...') }}
@@ -58,18 +58,18 @@ {{ __('Current price') }} :  @include('fo.modules.guarded-currency', [ 'money' => $productWithPricing->pricing->hasDiscount - ? $productWithPricing->pricing->discountedPriceTtc() - : $productWithPricing->pricing->basePriceTtc(), - 'product' => $productWithPricing->product, + ? $productWithPricing->pricing->discountedPriceTtc + : $productWithPricing->pricing->basePriceTtc, + 'productWithPricing' => $productWithPricing, ]) - @if ($productWithPricing->pricing->hasDiscount && $productWithPricing->product->validDiscount?->is_old_price_displayed) + @if ($productWithPricing->pricing->hasDiscount && $productWithPricing->product->discount?->is_old_price_displayed) {{ __('Original price') }} :  @include('fo.modules.guarded-currency', [ - 'money' => $productWithPricing->pricing->basePriceTtc(), - 'product' => $productWithPricing->product, + 'money' => $productWithPricing->pricing->basePriceTtc, + 'productWithPricing' => $productWithPricing, ]) @endif @@ -79,13 +79,13 @@ @if ($productWithPricing->product->weight_variable) *{{ __('Product sold by the kilo') }} : @include('fo.modules.guarded-currency', [ - 'money' => $productWithPricing->pricing->priceKgTtc(), - 'product' => $productWithPricing->product, + 'money' => $productWithPricing->pricing->priceKgTtc, + 'productWithPricing' => $productWithPricing, ])/kg @else {{ __('Price per kilo') }} : @include('fo.modules.guarded-currency', [ - 'money' => $productWithPricing->pricing->priceKgTtc(), - 'product' => $productWithPricing->product, + 'money' => $productWithPricing->pricing->priceKgTtc, + 'productWithPricing' => $productWithPricing, ])/kg @endif @@ -99,7 +99,7 @@ alt="{{ __('Nutriscore') }} {{ Str::upper($productWithPricing->product->inco->nutriscore->label()) }}"> @endif - @can('addToBasket', $productWithPricing->product) + @can('addToBasket', $productWithPricing)
$productWithPricing->product->id])'>
@endcan @@ -114,14 +114,14 @@
@if (count($starProductList) > 3) - - 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/resources/views/fo/modules/guarded-currency.blade.php b/resources/views/fo/modules/guarded-currency.blade.php index 14e9c1f9..ca69327a 100644 --- a/resources/views/fo/modules/guarded-currency.blade.php +++ b/resources/views/fo/modules/guarded-currency.blade.php @@ -1,9 +1,12 @@ @php /** @var \Money\Money $money */ - /** @var \App\Models\Product $product */ + + if (! isset($productWithPricing) || ! $productWithPricing instanceof \App\Dto\ProductWithPricingDto) { + throw new \InvalidArgumentException('Product must be an instance of ProductWithPricingDto to view prices.'); + } @endphp -@if (Gate::allows('viewPrices', $product)) +@if (Gate::allows('viewPrices', $productWithPricing)) @money($money) @else {{ '-.--' }} diff --git a/resources/views/fo/pages/contact.blade.php b/resources/views/fo/pages/contact.blade.php index 61e9bab0..00f25005 100644 --- a/resources/views/fo/pages/contact.blade.php +++ b/resources/views/fo/pages/contact.blade.php @@ -104,12 +104,19 @@
+ @php + $contactExtensions = array_map( + static fn (string $ext): string => '.' . ltrim($ext, '.'), + \App\Http\Requests\Fo\ContactFormRequest::ALLOWED_EXTENSIONS, + ); + $contactMaxSizeMb = \App\Http\Requests\Fo\ContactFormRequest::MAX_FILE_SIZE_KB / 1024; + @endphp + accept="{{ implode(',', $contactExtensions) }}" /> @error('file')
{{ $message }}
@enderror diff --git a/resources/views/fo/pages/products/show-info.blade.php b/resources/views/fo/pages/products/show-info.blade.php index 0e806de6..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) class=" opacity-75" @endorderable> +
product->is_orderable) class="opacity-75" @endif>

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

diff --git a/resources/views/fo/pages/products/show-picture.blade.php b/resources/views/fo/pages/products/show-picture.blade.php index 29e63d3f..7653e78a 100644 --- a/resources/views/fo/pages/products/show-picture.blade.php +++ b/resources/views/fo/pages/products/show-picture.blade.php @@ -1,15 +1,15 @@ -
- @unlessorderable($productWithPricing->product) +
+ @if (!$productWithPricing->product->is_orderable) {{ __('Coming soon') }} - @endorderable + @endif @if ($productWithPricing->product->picture_large) - {{ $productWithPricing->product->picture_alt }} @elseif($productWithPricing->product->picture) - {{ $productWithPricing->product->picture_alt }} @else {{ __('Current price') }} :  @include('fo.modules.guarded-currency', [ 'money' => $productWithPricing->pricing->hasDiscount - ? $productWithPricing->pricing->discountedPriceTtc() - : $productWithPricing->pricing->basePriceTtc(), - 'product' => $productWithPricing->product, + ? $productWithPricing->pricing->discountedPriceTtc + : $productWithPricing->pricing->basePriceTtc, + 'productWithPricing' => $productWithPricing, ]) - @if ($productWithPricing->pricing->hasDiscount && $productWithPricing->product->validDiscount?->is_old_price_displayed) + @if ($productWithPricing->pricing->hasDiscount && $productWithPricing->product->discount?->is_old_price_displayed) {{ __('Original price') }} :  @include('fo.modules.guarded-currency', [ - 'money' => $productWithPricing->pricing->basePriceTtc(), - 'product' => $productWithPricing->product, + 'money' => $productWithPricing->pricing->basePriceTtc, + 'productWithPricing' => $productWithPricing, ]) @endif @@ -32,14 +32,14 @@

{{ $productWithPricing->product->weight_variable ? '*' . __('Product sold by the kilo') : __('Price per kilo') }} : @include('fo.modules.guarded-currency', [ - 'money' => $productWithPricing->pricing->priceKgTtc(), - 'product' => $productWithPricing->product, + 'money' => $productWithPricing->pricing->priceKgTtc, + 'productWithPricing' => $productWithPricing, ]) /kg

- @can('addToBasket', $productWithPricing->product) + @can('addToBasket', $productWithPricing)
$productWithPricing->product->id])'>
diff --git a/resources/views/fo/pages/products/show.blade.php b/resources/views/fo/pages/products/show.blade.php index 39eabb47..86069096 100644 --- a/resources/views/fo/pages/products/show.blade.php +++ b/resources/views/fo/pages/products/show.blade.php @@ -9,7 +9,7 @@
-
-
+ @csrf
@@ -74,3 +74,22 @@
@endsection + +@push('scripts') + +@endpush diff --git a/routes/ajax-fo.php b/routes/ajax-fo.php index a5d3e922..df0f25f0 100644 --- a/routes/ajax-fo.php +++ b/routes/ajax-fo.php @@ -13,11 +13,14 @@ Route::get('products/filter', ProductsController::class)->name('products.filter' // * BASKET Route::name('basket.')->prefix('basket')->group(function (): void { Route::get('get', [BasketController::class, 'get'])->name('get'); - Route::post('add', [BasketController::class, 'add'])->name('add'); - Route::post('remove', [BasketController::class, 'remove'])->name('remove'); - Route::post('empty', [BasketController::class, 'empty'])->name('empty'); + Route::middleware('throttle:30,1')->group(function (): void { + Route::post('add', [BasketController::class, 'add'])->name('add'); + Route::post('remove', [BasketController::class, 'remove'])->name('remove'); + Route::post('empty', [BasketController::class, 'empty'])->name('empty'); + }); }); // * ORDERS TUNNEL Route::get('/shops/{shop}/pickup-timeslots', [PickupController::class, 'getAvailableTimeslots']) + ->middleware(['auth:frontend', 'verified', 'is-employed']) ->name('shops.pickup-timeslots'); diff --git a/routes/breadcrumbs-bo.php b/routes/breadcrumbs-bo.php index 294cc549..6eaca4c8 100644 --- a/routes/breadcrumbs-bo.php +++ b/routes/breadcrumbs-bo.php @@ -3,21 +3,14 @@ declare(strict_types=1); use App\Dto\DiscountDto; +use App\Dto\FaqDto; use App\Dto\PageDto; use App\Dto\PickupExceptionDto; use App\Dto\ProductDto; use App\Dto\RangeDto; use App\Dto\ShopDto; use App\Dto\SlideDto; -use App\Models\Discount; -use App\Models\Faq; -use App\Models\Page; -use App\Models\PickupException; -use App\Models\Product; -use App\Models\Range; -use App\Models\Shop; -use App\Models\Slide; -use App\Models\Tag; +use App\Dto\TagDto; use Diglactic\Breadcrumbs\Breadcrumbs; use Diglactic\Breadcrumbs\Generator; use Illuminate\Support\Str; @@ -40,7 +33,7 @@ Breadcrumbs::for('bo.slides.create', function (Generator $trail) use ($creationL $trail->parent('bo.slides.index'); $trail->push($creationLabel); }); -Breadcrumbs::for('bo.slides.edit', function (Generator $trail, Slide | SlideDto $slide) use ($editionLabel): void { +Breadcrumbs::for('bo.slides.edit', function (Generator $trail, SlideDto $slide) use ($editionLabel): void { $trail->parent('bo.slides.index'); $trail->push($editionLabel, route('bo.slides.edit', $slide)); }); @@ -54,7 +47,7 @@ Breadcrumbs::for('bo.tags.create', function (Generator $trail) use ($creationLab $trail->parent('bo.tags.index'); $trail->push($creationLabel); }); -Breadcrumbs::for('bo.tags.edit', function (Generator $trail, Tag $tag) use ($editionLabel): void { +Breadcrumbs::for('bo.tags.edit', function (Generator $trail, TagDto $tag) use ($editionLabel): void { $trail->parent('bo.tags.index'); $trail->push($editionLabel, route('bo.tags.edit', $tag)); }); @@ -68,7 +61,7 @@ Breadcrumbs::for('bo.ranges.create', function (Generator $trail) use ($creationL $trail->parent('bo.ranges.index'); $trail->push($creationLabel); }); -Breadcrumbs::for('bo.ranges.edit', function (Generator $trail, Range | RangeDto $range) use ($editionLabel): void { +Breadcrumbs::for('bo.ranges.edit', function (Generator $trail, RangeDto $range) use ($editionLabel): void { $trail->parent('bo.ranges.index'); $trail->push($editionLabel, route('bo.ranges.edit', $range)); }); @@ -82,7 +75,7 @@ Breadcrumbs::for('bo.pages.create', function (Generator $trail) use ($creationLa $trail->parent('bo.pages.index'); $trail->push($creationLabel); }); -Breadcrumbs::for('bo.pages.edit', function (Generator $trail, Page | PageDto $page) use ($editionLabel): void { +Breadcrumbs::for('bo.pages.edit', function (Generator $trail, PageDto $page) use ($editionLabel): void { $trail->parent('bo.pages.index'); $trail->push("{$editionLabel} {$page->slug->label()}", route('bo.pages.edit', $page->slug->value())); }); @@ -96,7 +89,7 @@ Breadcrumbs::for('bo.faqs.create', function (Generator $trail) use ($creationLab $trail->parent('bo.faqs.index'); $trail->push($creationLabel); }); -Breadcrumbs::for('bo.faqs.edit', function (Generator $trail, Faq $faq) use ($editionLabel): void { +Breadcrumbs::for('bo.faqs.edit', function (Generator $trail, FaqDto $faq) use ($editionLabel): void { $trail->parent('bo.faqs.index'); $trail->push($editionLabel, route('bo.faqs.edit', $faq)); }); @@ -110,18 +103,18 @@ Breadcrumbs::for('bo.products.create', function (Generator $trail) use ($creatio $trail->parent('bo.products.index'); $trail->push($creationLabel); }); -Breadcrumbs::for('bo.products.edit', function (Generator $trail, Product | ProductDto $product) use ($editionLabel): void { +Breadcrumbs::for('bo.products.edit', function (Generator $trail, ProductDto $product) use ($editionLabel): void { $trail->parent('bo.products.index'); $trail->push($editionLabel, route('bo.products.edit', $product)); }); // * Product Incos -Breadcrumbs::for('bo.products.incos.create', function (Generator $trail, Product | ProductDto $product) use ($creationLabel): void { +Breadcrumbs::for('bo.products.incos.create', function (Generator $trail, ProductDto $product) use ($creationLabel): void { $trail->parent('bo.products.edit', $product); $trail->push(Str::ucfirst(trans_choice('models.classes.product_incos', 1))); $trail->push($creationLabel); }); -Breadcrumbs::for('bo.products.incos.edit', function (Generator $trail, Product | ProductDto $product) use ($editionLabel): void { +Breadcrumbs::for('bo.products.incos.edit', function (Generator $trail, ProductDto $product) use ($editionLabel): void { $trail->parent('bo.products.edit', $product); $trail->push(Str::ucfirst(trans_choice('models.classes.product_incos', 1))); $trail->push($editionLabel); @@ -145,7 +138,7 @@ Breadcrumbs::for('bo.discounts.create', function (Generator $trail) use ($creati $trail->parent('bo.discounts.index'); $trail->push($creationLabel); }); -Breadcrumbs::for('bo.discounts.edit', function (Generator $trail, Discount | DiscountDto $discount) use ($editionLabel): void { +Breadcrumbs::for('bo.discounts.edit', function (Generator $trail, DiscountDto $discount) use ($editionLabel): void { $trail->parent('bo.discounts.index'); $trail->push($editionLabel, route('bo.discounts.edit', $discount)); }); @@ -159,11 +152,11 @@ Breadcrumbs::for('bo.shops.create', function (Generator $trail) use ($creationLa $trail->parent('bo.shops.index'); $trail->push($creationLabel); }); -Breadcrumbs::for('bo.shops.edit', function (Generator $trail, Shop | ShopDto $shop) use ($editionLabel): void { +Breadcrumbs::for('bo.shops.edit', function (Generator $trail, ShopDto $shop) use ($editionLabel): void { $trail->parent('bo.shops.index'); $trail->push($editionLabel, route('bo.shops.edit', $shop)); }); -Breadcrumbs::for('bo.shops.pickup-exceptions.edit', function (Generator $trail, Shop | ShopDto $shop): void { +Breadcrumbs::for('bo.shops.pickup-exceptions.edit', function (Generator $trail, ShopDto $shop): void { $trail->parent('bo.shops.edit', $shop); $trail->push( Str::ucfirst(trans_choice('models.classes.pickup-exceptions', \INF)), @@ -185,7 +178,7 @@ Breadcrumbs::for('bo.pickup-exceptions.create', function (Generator $trail) use }); Breadcrumbs::for( 'bo.pickup-exceptions.edit', - function (Generator $trail, PickupException | PickupExceptionDto $pickupException) use ($editionLabel): void { + function (Generator $trail, PickupExceptionDto $pickupException) use ($editionLabel): void { $trail->parent('bo.pickup-exceptions.index'); $trail->push($editionLabel, route('bo.pickup-exceptions.edit', $pickupException)); } diff --git a/routes/breadcrumbs-fo.php b/routes/breadcrumbs-fo.php index 85a1e9cc..b4da0981 100644 --- a/routes/breadcrumbs-fo.php +++ b/routes/breadcrumbs-fo.php @@ -4,9 +4,9 @@ declare(strict_types=1); use App\Dto\OrderDto; use App\Dto\PageDto; +use App\Dto\ProductDto; use App\Models\Order; use App\Models\Page; -use App\Models\Product; use Diglactic\Breadcrumbs\Breadcrumbs; use Diglactic\Breadcrumbs\Generator; use Illuminate\Auth\Events\Login; @@ -43,14 +43,14 @@ Breadcrumbs::for('fo.products.index', function (Generator $trail): void { $trail->parent('fo.pages.home'); $trail->push(trans('All aisles'), route('fo.products.index')); }); -Breadcrumbs::for('fo.ranges.show', function (Generator $trail, Product $product): void { +Breadcrumbs::for('fo.ranges.show', function (Generator $trail, ProductDto $product): void { $trail->parent('fo.products.index'); $trail->push( str($product->range->name)->title()->value(), route('fo.products.index', ['ranges[]' => $product->range->id]) ); }); -Breadcrumbs::for('fo.products.show', function (Generator $trail, Product $product): void { +Breadcrumbs::for('fo.products.show', function (Generator $trail, ProductDto $product): void { $trail->parent('fo.ranges.show', $product); $trail->push($product->name, route('fo.products.show', $product)); }); diff --git a/routes/web-fo.php b/routes/web-fo.php index de7ce398..64663b3d 100644 --- a/routes/web-fo.php +++ b/routes/web-fo.php @@ -92,7 +92,9 @@ Route::group([], function (): void { // * CONTACT PAGE Route::get('contactez-nous', [ContactController::class, 'showForm'])->name('pages.contact'); - Route::post('contactez-nous', [ContactController::class, 'submitForm'])->name('pages.contact.submit'); + Route::post('contactez-nous', [ContactController::class, 'submitForm']) + ->middleware('throttle:5,2') + ->name('pages.contact.submit'); // * PRODUCTS Route::get('produits', [ProductsController::class, 'index'])->name('products.index'); diff --git a/shared/Concurrency/Lock.php b/shared/Concurrency/Lock.php new file mode 100644 index 00000000..dc9306e8 --- /dev/null +++ b/shared/Concurrency/Lock.php @@ -0,0 +1,23 @@ +value)) { + throw new \DomainException('value must be a valid UUID v7'); + } + } #[\Override] public function __toString(): string 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; } } diff --git a/shared/Enums/HasBaseEnum.php b/shared/Enums/HasBaseEnum.php new file mode 100644 index 00000000..4070170f --- /dev/null +++ b/shared/Enums/HasBaseEnum.php @@ -0,0 +1,14 @@ +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)) { + if (is_file($baseTempPath)) { + 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/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/Architecture/ApplicationTest.php b/tests/Architecture/ApplicationTest.php index 35859915..438de8fe 100644 --- a/tests/Architecture/ApplicationTest.php +++ b/tests/Architecture/ApplicationTest.php @@ -2,82 +2,125 @@ declare(strict_types=1); +namespace Tests\Architecture; + +use App\Casts\CalendarDateCast; +use App\Casts\UtcDatetimeCast; use App\Contracts\Action; use App\Contracts\ActionInput; use App\Contracts\Query; 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\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\Entities'); +arch('No Domain Entities are used in Policies') + ->expect('App\Policies') + ->not->toUse('Domain\Models\Entities'); - arch('App Repositories implement App\Contracts\Repository') - ->expect('App\Repositories') - ->toImplement('App\Contracts\Repository'); +arch('App DTOs are final readonly classes') + ->expect('App\Dto') + ->classes() + ->toBeFinal() + ->toBeReadonly(); - arch('App Directories implement App\Contracts\Directory') - ->expect('App\Directories') - ->toImplement('App\Contracts\Directory'); +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 DTOs are final readonly classes') - ->expect('App\Dto') - ->classes() - ->toBeFinal() - ->toBeReadonly(); + foreach ($files as $file) { + $subPath = $file->getRelativePathname(); + $className = 'App\\Cqs\\Actions\\' . str_replace(['/', '.php'], ['\\', ''], $subPath); - 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); - $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); - $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('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 27932164..cf802d14 100644 --- a/tests/Architecture/CodingStandardsTest.php +++ b/tests/Architecture/CodingStandardsTest.php @@ -2,51 +2,126 @@ declare(strict_types=1); -describe('coding standards', function (): void { - arch()->preset()->php(); - arch()->preset()->security(); +namespace Tests\Architecture; - arch('it has no shell execution functions are used') - ->expect(['exec', 'shell_exec', 'system', 'passthru', 'proc_open']) - ->not->toBeUsed(); +use Shared\Filesystem\TemporaryFileFactory; +use Shared\Helpers\UuidHelper; +use Symfony\Component\Finder\Finder; - arch('it has no eval usage') - ->expect(['eval']) - ->not->toBeUsed(); +// Coding standards +arch()->preset()->php(); +arch()->preset()->security()->ignoring([ + TemporaryFileFactory::class, +]); - arch('it has no dangerous file functions') - ->expect(['file_get_contents', 'file_put_contents', 'fopen']) - ->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 globals are used') - ->expect(['$GLOBALS', 'global']) - ->not->toBeUsed(); +arch('it has no eval usage') + ->expect(['eval']) + ->not->toBeUsed(); - arch('it has no singletons') - ->expect(['getInstance', 'instance']) - ->not->toBeUsed(); +arch('it has no dangerous file functions') + ->expect(['file_get_contents', 'file_put_contents', 'fopen']) + ->not->toBeUsed(); - arch('it has no insecure hashing') - ->expect(['md5', 'sha1']) - ->not->toBeUsed(); +arch('it has no globals are used') + ->expect(['$GLOBALS', 'global']) + ->not->toBeUsed(); - arch('it has no sleep function are used') - ->expect(['sleep', 'usleep']) - ->not->toBeUsed(); +arch('it has no singletons') + ->expect(['getInstance', 'instance']) + ->not->toBeUsed(); - arch('it has no debug globals are used') - ->expect(['var_dump', 'die', 'print_r']) - ->not->toBeUsed(); +arch('it has no insecure hashing') + ->expect(['md5', 'sha1']) + ->not->toBeUsed(); - arch('all app source files use strict types') - ->expect('App') - ->toUseStrictTypes(); +arch('it has no sleep function are used') + ->expect(['sleep', 'usleep']) + ->not->toBeUsed(); - arch('all domain source files use strict types') - ->expect('Domain') - ->toUseStrictTypes(); +arch('it has no debug globals are used') + ->expect(['var_dump', 'die', 'print_r']) + ->not->toBeUsed(); - arch('all shared source files use strict types') - ->expect('Shared') - ->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 shared source files use strict types') + ->expect('Shared') + ->toUseStrictTypes(); + +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__); + $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('); + + 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'); + } + } +}); + +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/Architecture/DomainTest.php b/tests/Architecture/DomainTest.php index 792fde76..59765932 100644 --- a/tests/Architecture/DomainTest.php +++ b/tests/Architecture/DomainTest.php @@ -2,88 +2,88 @@ declare(strict_types=1); +namespace Tests\Architecture; + use Shared\DDD\Directory; use Shared\DDD\Entity; use Shared\DDD\Repository; -describe('domain coding rules', function (): void { - arch('Entities implements Entity') - ->expect("Domain\Entities") - ->toImplement(Entity::class); +// Domain coding rules +arch('Entities implements Entity') + ->expect("Domain\Models\Entities") + ->toImplement(Entity::class); - arch('Entities are immutable (disabled due to mock-final-classes conflict)') - ->expect("Domain\Entities") - ->toBeReadonly() - ->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 8dc70ca5..6d00a418 100644 --- a/tests/Architecture/InfraTest.php +++ b/tests/Architecture/InfraTest.php @@ -2,8 +2,10 @@ declare(strict_types=1); -describe('infra coding rules', function (): void { - arch('No App classes are used in Infra') - ->expect('Infra') - ->not->toUse('App'); -}); +namespace Tests\Architecture; + +// 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 647d95b4..76923cad 100644 --- a/tests/Architecture/NamingConventionsTest.php +++ b/tests/Architecture/NamingConventionsTest.php @@ -2,120 +2,129 @@ declare(strict_types=1); +namespace Tests\Architecture; + use App\Exceptions\GlobalHandler; 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\Cast") - ->toHaveSuffix('Cast'); +// Naming conventions in app +arch('casts have Cast suffix') + ->expect("App\Casts") + ->toHaveSuffix('Cast'); - arch('adapters repositories have Repository suffix') - ->expect("App\Adapters\Repositories") - ->toHaveSuffix('Repository'); +arch('adapters repositories have Repository suffix') + ->expect("Infrastructure\Adapters\Repositories") + ->toHaveSuffix('Repository'); - arch('dtos have Dto suffix') - ->expect("App\Dtos") - ->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('dtos have Dto suffix') - ->expect("Domain\Dto") - ->toHaveSuffix('Dto'); - - 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 implement an interface from their domain ports', function (string $folder, string $infraNs, string $domainNs): void { - $path = __DIR__ . '/../../infra/' . $folder; - $files = (new Finder())->files()->in($path)->name('*.php'); - - foreach ($files as $file) { - $className = $infraNs . '\\' . $file->getFilenameWithoutExtension(); - $interfaces = (new \ReflectionClass($className))->getInterfaceNames(); - $hasDomainPort = ! empty(array_filter( - $interfaces, - fn ($interface) => str_starts_with($interface, $domainNs) - )); - - expect($hasDomainPort) - ->toBeTrue(message: "La classe {$className} n'implémente aucune interface de {$domainNs}."); - } - })->with([ - 'Directories' => ['Adapters/Directories', 'Infrastructure\Adapters\Directories', 'Domain\Ports\Directories\\'], - '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\\'], +]); diff --git a/tests/CreatesApplication.php b/tests/CreatesApplication.php index df084d1e..4ab0f5bd 100644 --- a/tests/CreatesApplication.php +++ b/tests/CreatesApplication.php @@ -15,6 +15,7 @@ trait CreatesApplication */ public function createApplication() { + /** @var \Illuminate\Foundation\Application $app */ $app = require __DIR__ . '/../bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); diff --git a/tests/Feature/App/Console/Commands/UpsertEmployeesFormFileTest.php b/tests/Feature/App/Console/Commands/UpsertEmployeesFormFileTest.php index ead64501..40217ae5 100644 --- a/tests/Feature/App/Console/Commands/UpsertEmployeesFormFileTest.php +++ b/tests/Feature/App/Console/Commands/UpsertEmployeesFormFileTest.php @@ -2,7 +2,11 @@ declare(strict_types=1); +namespace Tests\Feature\App\Console\Commands; + use Illuminate\Console\Command; +use Illuminate\Testing\PendingCommand; +use Webmozart\Assert\Assert; afterEach(function (): void { \Mockery::close(); @@ -20,6 +24,8 @@ describe('UpsertEmployeesFormFile command', function (): void { 'file' => $filePath, ]); + Assert::isInstanceOf($result, PendingCommand::class); + // THEN $result->assertExitCode(Command::FAILURE); }); @@ -32,11 +38,12 @@ describe('UpsertEmployeesFormFile command', function (): void { file_put_contents($filePath, "ColA;ColB\n1;2\n"); // WHEN - /** @var \Illuminate\Testing\PendingCommand $result */ $result = $this->artisan('uwil:employees:upsert', [ 'file' => $filePath, ]); + Assert::isInstanceOf($result, PendingCommand::class); + // THEN $result->expectsOutputToContain('Errors occurred during import:') ->expectsOutputToContain('ColA, ColB') @@ -57,11 +64,12 @@ describe('UpsertEmployeesFormFile command', function (): void { ])); // WHEN - /** @var \Illuminate\Testing\PendingCommand $result */ $result = $this->artisan('uwil:employees:upsert', [ 'file' => $filePath, ]); + Assert::isInstanceOf($result, PendingCommand::class); + // THEN $result->expectsOutputToContain('Errors occurred during import:') ->expectsOutputToContain('Line 2: Invalid date format') diff --git a/tests/Feature/App/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptionsTest.php b/tests/Feature/App/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptionsTest.php new file mode 100644 index 00000000..51910ba1 --- /dev/null +++ b/tests/Feature/App/Console/Commands/UpsertPublicHolydaysOnShopsPickupExceptionsTest.php @@ -0,0 +1,64 @@ +artisan('uwil:upsert-shops-hollydays'); + Assert::isInstanceOf($command, PendingCommand::class); + + // THEN + $command->assertSuccessful()->execute(); + + Bus::assertDispatched(UpsertShopsPickupExceptionsUsingApiForYear::class); +}); + +it('dispatches the job for the specified numeric year', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + Bus::fake(); + + // WHEN + $command = $this->artisan('uwil:upsert-shops-hollydays', ['year' => '2027']); + Assert::isInstanceOf($command, PendingCommand::class); + + // THEN + $command->assertSuccessful()->execute(); + + Bus::assertDispatched(UpsertShopsPickupExceptionsUsingApiForYear::class); +}); + +it('fails when year argument is not numeric', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + Bus::fake(); + + // WHEN + $command = $this->artisan('uwil:upsert-shops-hollydays', ['year' => 'abc']); + Assert::isInstanceOf($command, PendingCommand::class); + + // THEN + $command + ->expectsOutput('The year must be a number') + ->assertFailed() + ->execute(); + + Bus::assertNotDispatched(UpsertShopsPickupExceptionsUsingApiForYear::class); +}); diff --git a/tests/Feature/App/Console/Commands/UserCreateTest.php b/tests/Feature/App/Console/Commands/UserCreateTest.php new file mode 100644 index 00000000..d130bfae --- /dev/null +++ b/tests/Feature/App/Console/Commands/UserCreateTest.php @@ -0,0 +1,39 @@ +value() . ' : ' . UserRole::Admin->label(); + + // WHEN / THEN + $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') + ->expectsQuestion('What is the password?', 'Str0ng!Password') + ->expectsQuestion('Confirm : What is the password?', 'Str0ng!Password') + ->expectsQuestion('What is the role ?', $roleChoice) + ->expectsOutput('User created.') + ->assertSuccessful() + ->execute(); + + $user = User::query()->where('email', 'alice.martin@ldc.fr')->first(); + expect($user)->not->toBeNull() + ->and($user?->firstname)->toBe('Alice') + ->and($user?->lastname)->toBe('Martin') + ->and($user?->role)->toBe(UserRole::Admin) + ->and(Hash::check('Str0ng!Password', (string) $user?->password))->toBeTrue(); +}); diff --git a/tests/Feature/Bo/AuthTest.php b/tests/Feature/App/Http/Controllers/Bo/AuthTest.php similarity index 86% rename from tests/Feature/Bo/AuthTest.php rename to tests/Feature/App/Http/Controllers/Bo/AuthTest.php index 59c1e897..9d353cf4 100644 --- a/tests/Feature/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 af9bc0b8..7d8ff10c 100644 --- a/tests/Feature/App/Http/Controllers/Bo/DashboardControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/DashboardControllerTest.php @@ -2,10 +2,16 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Models\User; +use Domain\Enums\StatsShopType; use Domain\Enums\UserRole; +use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Auth; +use function Pest\Laravel\get; + describe('Bo\DashboardController', function (): void { beforeEach(function (): void { /** @var \Tests\TestCase $this */ @@ -54,4 +60,22 @@ describe('Bo\DashboardController', function (): void { // THEN $response->assertRedirect('/bo/login'); }); + + it('translates shop stat enum labels in fr and en', function (): void { + // GIVEN + App::setLocale('fr'); + $frLabel = __(StatsShopType::nbActiveClients->label()); + + // WHEN + App::setLocale('en'); + $enLabel = __(StatsShopType::nbActiveClients->label()); + $response = get('/bo?start=2026-01-01&end=2026-01-31'); + + // THEN + expect($frLabel)->toBe('Nombre de clients actifs') + ->and($enLabel)->toBe('Number of active customers'); + $response->assertOk(); + $response->assertSee('Number of active customers'); + App::setLocale('fr'); + }); }); 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/Bo/Employees/EmployeeSyncFeatureTest.php b/tests/Feature/App/Http/Controllers/Bo/EmployeeSyncFeatureTest.php similarity index 80% rename from tests/Feature/Bo/Employees/EmployeeSyncFeatureTest.php rename to tests/Feature/App/Http/Controllers/Bo/EmployeeSyncFeatureTest.php index afb38eef..70fa5cf2 100644 --- a/tests/Feature/Bo/Employees/EmployeeSyncFeatureTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/EmployeeSyncFeatureTest.php @@ -2,34 +2,27 @@ declare(strict_types=1); -use App\Contracts\Repositories\EmployeeRepository; +namespace Tests\Feature\App\Http\Controllers\Bo; + +use App\Cqs\Queries\Settings\GetSettingsQuery; use App\Models\Employee; use App\Models\Setting; use App\Models\User; use App\Services\ArcadiaEmployee; use App\Services\ArcadiaEmployeeService; use App\Services\EmployeeSyncService; +use App\Services\EmployeeUpsertService; use Carbon\CarbonImmutable; use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); - -afterEach(function (): void { - \Mockery::close(); -}); +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 { - - // FIXME: Arcadia API is offline renablethis this test when up. - expect(true)->toBeTruthy(); - - return; - /** @var \Tests\TestCase $this */ // GIVEN @@ -80,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') @@ -93,10 +87,19 @@ describe('Employee Sync Feature E2E', function (): void { ->and($employee->last_sync)->not->toBeNull(); // Verify sync timestamps - $syncService = resolve(EmployeeSyncService::class); + $syncService = new EmployeeSyncService( + new NullLogger(), + $this->app->make(CacheRepository::class), + $mockArcadia, + $this->app->make(EmployeeUpsertService::class), + new GetSettingsQuery(), + ); expect($syncService->getLastSync())->not->toBeNull(); - $employeeRepo = resolve(EmployeeRepository::class); - expect($employeeRepo->getMostRecentSyncDate())->not->toBeNull(); - }); + $mostRecentSyncDate = Employee::query() + ->orderBy('last_sync', 'desc') + ->limit(1) + ->first('last_sync')?->last_sync; + expect($mostRecentSyncDate)->not->toBeNull(); + })->skip('Arcadia API is offline; SettingPolicy and EmployeePolicy currently return false.'); }); diff --git a/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php index e918f8f2..f1e60699 100644 --- a/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php @@ -2,41 +2,51 @@ declare(strict_types=1); +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; -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 - /** @var \Tests\TestCase $this */ - auth()->guard('backend')->logout(); + Queue::fake(); // WHEN - $response = $this->post('/bo/settings/employees/sync'); + $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 + Auth::guard('backend')->logout(); + + // WHEN + $response = post('/bo/settings/employees/sync'); // THEN $response->assertRedirect('/bo/login'); diff --git a/tests/Feature/App/Http/Controllers/Bo/FaqsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/FaqsControllerTest.php index 17c95989..c784d470 100644 --- a/tests/Feature/App/Http/Controllers/Bo/FaqsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/FaqsControllerTest.php @@ -2,9 +2,17 @@ declare(strict_types=1); +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 { @@ -123,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/OrdersControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/OrdersControllerTest.php index 5d6d26e7..b2d9076b 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; @@ -9,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; @@ -26,27 +29,47 @@ 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; 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 $shop = Shop::factory()->create(['name' => 'Boutique Test']); - Order::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + Order::query()->forceCreate([ + '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(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(), ]); @@ -67,13 +90,20 @@ describe('Bo\OrdersController', function (): void { // GIVEN $shop = Shop::factory()->create(['name' => 'Boutique Pagination']); for ($i = 0; $i < 30; $i++) { - Order::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + Order::query()->forceCreate([ + '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(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(), ]); @@ -93,17 +123,24 @@ 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::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, '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(), ]); @@ -125,23 +162,37 @@ describe('Bo\OrdersController', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $shop = Shop::factory()->create(); - $olderOrder = Order::forceCreate([ - 'id' => Uuid::uuid7(Date::now()->subHours(2))->toString(), + $olderOrder = Order::query()->forceCreate([ + '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(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(), ]); - $newerOrder = Order::forceCreate([ - 'id' => Uuid::uuid7(Date::now())->toString(), + $newerOrder = Order::query()->forceCreate([ + '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(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(), ]); @@ -161,23 +212,37 @@ describe('Bo\OrdersController', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $shop = Shop::factory()->create(); - $todayOrder = Order::forceCreate([ - 'id' => Uuid::uuid7(Date::now())->toString(), + $todayOrder = Order::query()->forceCreate([ + '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(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(), ]); - $pastOrder = Order::forceCreate([ - 'id' => Uuid::uuid7(Date::now()->subDays(3))->toString(), + $pastOrder = Order::query()->forceCreate([ + '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(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(), ]); @@ -198,12 +263,12 @@ describe('Bo\OrdersController', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $shop = Shop::factory()->create(); - $customer = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('customer@example.com'), ]); - Employee::forceCreate([ + Employee::query()->forceCreate([ 'id' => 9991, 'customer_id' => $customer->id, 'matricule' => new Matricule('1000999'), @@ -221,13 +286,20 @@ describe('Bo\OrdersController', function (): void { $crmMock->shouldReceive('getCustomerFromHashCode')->andReturn(null); App::instance(CrmService::class, $crmMock); - $order = Order::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + $order = Order::query()->forceCreate([ + '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(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(), ]); @@ -245,13 +317,20 @@ describe('Bo\OrdersController', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $shop = Shop::factory()->create(); - $order = Order::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + $order = Order::query()->forceCreate([ + '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(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(), ]); @@ -284,13 +363,20 @@ describe('Bo\OrdersController', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $shop = Shop::factory()->create(); - $order = Order::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + $order = Order::query()->forceCreate([ + '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(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(), ]); @@ -301,4 +387,77 @@ 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 { + // GIVEN + $shop = Shop::factory()->create(); + $validated = Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(UuidHelper::v7()), + '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(), + ]); + $failed = Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(UuidHelper::v7()), + '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 = get('/bo/orders?status=validated'); + + // THEN + $response->assertOk() + ->assertSessionHas('orders.filter.status', OrderStatus::VALIDATED) + ->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/Feature/App/Http/Controllers/Bo/PageControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/PageControllerTest.php index 7588c270..9fc0e33b 100644 --- a/tests/Feature/App/Http/Controllers/Bo/PageControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/PageControllerTest.php @@ -2,11 +2,17 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Dto\PageDto; 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 { @@ -84,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 bc70e6a1..32f2c074 100644 --- a/tests/Feature/App/Http/Controllers/Bo/PickupExceptionsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/PickupExceptionsControllerTest.php @@ -2,10 +2,20 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Models\PickupException; +use App\Models\Slide; 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; +use function Pest\Laravel\post; +use function Pest\Laravel\postJson; describe('PickupExceptionsController', function () { beforeEach(function () { @@ -50,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); @@ -108,4 +119,106 @@ describe('PickupExceptionsController', function () { expect(PickupException::query()->find($pickupException->id))->toBeNull(); $response->assertRedirect('/bo/pickup-exceptions'); }); + + it('checks PickupExceptionPolicy create permission instead of SlidePolicy on index', function (): void { + // GIVEN + $deniedSlidePolicy = new class () + { + public function create(): bool + { + return false; + } + }; + Gate::policy(Slide::class, $deniedSlidePolicy::class); + + // WHEN + $responseWhenSlideCreateDenied = get(route('bo.pickup-exceptions.index')); + + // THEN + $responseWhenSlideCreateDenied->assertOk(); + $responseWhenSlideCreateDenied->assertSee(route('bo.pickup-exceptions.create')); + + // GIVEN + $pickupExceptionPolicyWithoutCreate = new class () + { + public function viewAny(): bool + { + return true; + } + + public function create(): bool + { + return false; + } + }; + Gate::policy(PickupException::class, $pickupExceptionPolicyWithoutCreate::class); + + // WHEN + $responseWhenPickupExceptionCreateDenied = get(route('bo.pickup-exceptions.index')); + + // THEN + $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/ProductIncosControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/ProductIncosControllerTest.php index 790c8a94..2335788b 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; @@ -19,10 +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); +use Webmozart\Assert\Assert; describe('ProductIncosController', function () { beforeEach(function () { @@ -207,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) @@ -266,4 +267,60 @@ describe('ProductIncosController', function () { ])); $response->assertSessionHas('success'); }); + + it('flashes danger when associating fails due to Arcadia API error', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + $arcadiaService = \Mockery::mock(ArcadiaIncoService::class); + $arcadiaService->shouldReceive('fetchInco') + ->once() + ->with(99999) + ->andReturnNull(); + + $this->app->instance(ArcadiaIncoService::class, $arcadiaService); + + // WHEN + $response = $this->from(route('bo.products.incos.create', $this->product)) + ->post(route('bo.products.incos.associate', $this->product), [ + 'no_art' => 99999, + ]); + + // THEN + $response->assertRedirect(route('bo.products.incos.create', $this->product)); + $response->assertSessionHas('danger', __('Arcadia API error: :error', [ + 'error' => 'INCO sheet #99999 was not found on Arcadia API.', + ])); + }); + + it('flashes danger when synchronizing fails due to Arcadia API error', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + $inco = new ProductInco(); + $inco->no_art = 27996; + $inco->product()->associate($this->product); + $inco->save(); + + $arcadiaService = \Mockery::mock(ArcadiaIncoService::class); + $arcadiaService->shouldReceive('fetchInco') + ->once() + ->with(27996) + ->andThrow(new \RuntimeException('Gateway timeout')); + + $this->app->instance(ArcadiaIncoService::class, $arcadiaService); + + // WHEN + $response = $this->from(route('bo.products.incos.edit', [ + 'product' => $this->product, + 'inco' => $inco, + ]))->post(route('bo.products.incos.sync', $this->product)); + + // THEN + $response->assertRedirect(route('bo.products.incos.edit', [ + 'product' => $this->product, + 'inco' => $inco, + ])); + $response->assertSessionHas('danger', __('Arcadia API error: :error', [ + 'error' => 'Gateway timeout', + ])); + }); }); diff --git a/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php index 25793f4c..a392a759 100644 --- a/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php @@ -2,12 +2,17 @@ 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; 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; @@ -16,17 +21,35 @@ use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; use Domain\Enums\UserRole; 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; +use function Pest\Laravel\postJson; 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(); @@ -137,11 +160,31 @@ describe('ProductsController', function () { }); it('can access create', function () { + /** @var \Tests\TestCase $this */ // WHEN $response = $this->get('/bo/products/create'); // THEN expect($response->status())->toBe(200); + $extensions = implode(', ', array_map( + static fn (string $ext): string => '.' . ltrim($ext, '.'), + StoreProductRequest::ALLOWED_EXTENSIONS, + )); + $expectedPictureHelper = __('Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px', [ + 'extensions' => $extensions, + 'maxSize' => StoreProductRequest::MAX_FILE_SIZE_KB / 1024, + 'width' => StoreProductRequest::PICTURE_WIDTH, + 'height' => StoreProductRequest::PICTURE_HEIGHT, + ]); + $expectedLargePictureHelper = __('Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px', [ + 'extensions' => $extensions, + 'maxSize' => StoreProductRequest::MAX_FILE_SIZE_KB / 1024, + 'width' => StoreProductRequest::PICTURE_LARGE_WIDTH, + 'height' => StoreProductRequest::PICTURE_LARGE_HEIGHT, + ]); + + $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 () { @@ -205,29 +248,45 @@ describe('ProductsController', function () { // THEN $response->assertSessionHasNoErrors(); expect($response->status())->toBe(302); - $product = Product::where('name', 'New Product')->first(); + $product = Product::query()->where('name', 'New Product')->first(); + Assert::notNull($product); expect($product)->not->toBeNull(); $response->assertRedirect("/bo/products/{$product->slug}/edit"); }); it('can access edit', function () { + /** @var \Tests\TestCase $this */ // GIVEN + $otherRange = new Range(); + $otherRange->name = 'Other Range ' . uniqid(); + $otherRange->status = true; + $otherRange->order = random_int(1, 4999); + $otherRange->picture_alt = 'alt'; + $otherRange->picture_title = 'title'; + $otherRange->save(); + $range = new Range(); $range->name = 'Test Range ' . uniqid(); $range->status = true; - $range->order = random_int(1, 9999); + $range->order = random_int(5000, 9999); $range->picture_alt = 'alt'; $range->picture_title = 'title'; $range->save(); + $tag = new Tag(['label' => 'Bio ' . uniqid(), 'status' => true]); + $tag->save(); + + $orderableStart = Date::now()->startOfMinute()->subDay(); + $orderableEnd = Date::now()->startOfMinute()->addWeek(); + $product = new Product([ 'range_id' => $range->id, 'name' => 'Test Product', - 'brand' => ProductBrand::loue, - 'invoicing_unit' => InvoicingUnit::PCE, - 'sell_unit' => SellUnit::PCE, - 'order_unit' => OrderUnit::PCE, - 'tax_rate' => TaxRate::TVA_20, + 'brand' => ProductBrand::legaulois, + 'invoicing_unit' => InvoicingUnit::KGM, + 'sell_unit' => SellUnit::KGM, + 'order_unit' => OrderUnit::COLIS, + 'tax_rate' => TaxRate::TVA_5_5, 'description' => 'Test description', 'status' => true, ]); @@ -237,13 +296,30 @@ describe('ProductsController', function () { $product->picture_title = 'test title'; $product->picture_large_alt = 'test alt'; $product->picture_large_title = 'test title'; + $product->weight = 1500; + $product->orderable_start = $orderableStart; + $product->orderable_end = $orderableEnd; $product->save(); + $product->tags()->attach($tag->id); // WHEN $response = $this->get("/bo/products/{$product->slug}/edit"); // THEN expect($response->status())->toBe(200); + $content = (string) $response->getContent(); + expect($content) + ->toMatch('/]+id="product-brand"[^>]*>.*?toMatch('/]+id="product-range"[^>]*>.*?id . '"\s+selected/s') + ->toMatch('/]+id="product-tax"[^>]*>.*?value . '"\s+selected/s') + ->toMatch('/]+id="product-sell-unit"[^>]*>.*?toMatch('/]+id="product-order-unit"[^>]*>.*?toMatch('/]+id="product-invoicing-unit"[^>]*>.*?toContain('"value":[{"id":' . $tag->id) + ->toMatch('/id="product-weight"[^>]+value="1\.5"/') + ->toContain('id="orderable-start" name="orderable_start" type="datetime-local"') + ->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 () { @@ -350,7 +426,7 @@ describe('ProductsController', function () { $response = $this->delete("/bo/products/{$product->slug}"); // THEN - expect(Product::find($product->id))->toBeNull(); + expect(Product::query()->find($product->id))->toBeNull(); }); it('can toggle star', function (): void { @@ -649,5 +725,76 @@ describe('ProductsController', function () { $response = $this->get('/bo/products'); $response->assertRedirect('/bo/login'); }); + + it('forbids changeSelectedOrder when update policy denies access', function (): void { + // GIVEN + $range = new Range(); + $range->name = 'Test Range ' . 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' => 'Test Product', + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Test description', + 'status' => true, + ]); + $product->price = Money::EUR(1000); + $product->short_description = 'Short test description'; + $product->picture_alt = 'test alt'; + $product->picture_title = 'test title'; + $product->picture_large_alt = 'test alt'; + $product->picture_large_title = 'test title'; + $product->save(); + + $productPolicyWithoutUpdate = new class () + { + public function update(): bool + { + return false; + } + }; + Gate::policy(Product::class, $productPolicyWithoutUpdate::class); + + // WHEN + $response = patch(route('bo.products.change-selected-order', $product), [ + 'order' => 1, + ]); + + // THEN + $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 05aa6f2d..4c291084 100644 --- a/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/RangesControllerTest.php @@ -2,13 +2,22 @@ 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; 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; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; -uses(RefreshDatabase::class); +use function Pest\Laravel\from; +use function Pest\Laravel\get; +use function Pest\Laravel\patch; +use function Pest\Laravel\postJson; describe('RangesController', function () { beforeEach(function () { @@ -16,6 +25,10 @@ describe('RangesController', function () { // GIVEN $this->user = User::factory()->create(['role' => UserRole::SuperAdmin]); $this->actingAs($this->user, 'backend'); + $storageMock = $this->mock(StorageService::class); + $storageMock->shouldIgnoreMissing(); + $storageMock->shouldReceive('storeFileOntoDisk') + ->andReturn(new StorageFilePath('ranges/picture.jpg')); }); it('can access index', function () { @@ -34,6 +47,18 @@ describe('RangesController', function () { // THEN expect($response->status())->toBe(200); + $extensions = implode(', ', array_map( + static fn (string $ext): string => '.' . ltrim($ext, '.'), + StoreRangeRequest::ALLOWED_EXTENSIONS, + )); + $expectedHelper = __('Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px', [ + 'extensions' => $extensions, + 'maxSize' => StoreRangeRequest::MAX_FILE_SIZE_KB / 1024, + 'width' => StoreRangeRequest::PICTURE_WIDTH, + 'height' => StoreRangeRequest::PICTURE_HEIGHT, + ]); + + $response->assertSee(json_encode($expectedHelper, JSON_THROW_ON_ERROR), false); }); it('can store a range', function () { @@ -166,4 +191,106 @@ describe('RangesController', function () { $range->refresh(); expect($range->status)->toBeTrue(); }); + + it('checks RangePolicy create permission instead of TagPolicy on index', function (): void { + // GIVEN + $deniedTagPolicy = new class () + { + public function create(): bool + { + return false; + } + }; + Gate::policy(Tag::class, $deniedTagPolicy::class); + + // WHEN + $responseWhenTagCreateDenied = get(route('bo.ranges.index')); + + // THEN + $responseWhenTagCreateDenied->assertOk(); + $responseWhenTagCreateDenied->assertSee(route('bo.ranges.create')); + + // GIVEN + $rangePolicyWithoutCreate = new class () + { + public function viewAny(): bool + { + return true; + } + + public function create(): bool + { + return false; + } + }; + Gate::policy(Range::class, $rangePolicyWithoutCreate::class); + + // WHEN + $responseWhenRangeCreateDenied = get(route('bo.ranges.index')); + + // THEN + $responseWhenRangeCreateDenied->assertOk(); + $responseWhenRangeCreateDenied->assertDontSee(route('bo.ranges.create')); + }); + + it('forbids changeOrder when update policy denies access', function (): void { + // GIVEN + $range = new Range(); + $range->name = 'My Range'; + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + $rangePolicyWithoutUpdate = new class () + { + public function update(): bool + { + return false; + } + }; + Gate::policy(Range::class, $rangePolicyWithoutUpdate::class); + + // WHEN + $response = patch(route('bo.ranges.change-order', [$range, 'up'])); + + // 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/SettingsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/SettingsControllerTest.php new file mode 100644 index 00000000..379a0730 --- /dev/null +++ b/tests/Feature/App/Http/Controllers/Bo/SettingsControllerTest.php @@ -0,0 +1,106 @@ +createOne(); + $route = route('bo.settings.edit'); + + // WHEN + $response = actingAs($user, 'backend')->get($route); + + // THEN + $response->assertForbidden(); + }); + + it('forbids updating employee sites while SettingPolicy is disabled', 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->assertForbidden(); + }); + + 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 { + // 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('rejects invalid site code formats', function (): void { + // GIVEN + $user = User::factory()->createOne(); + $route = route('bo.settings.update'); + $formData = [ + 'employee_sites' => ['PA', '123', 'INVALID!'], + ]; + + // WHEN + $response = actingAs($user, 'backend')->put($route, $formData); + + // THEN + $response->assertSessionHasErrors(['employee_sites.1', 'employee_sites.2']); + }); +}); diff --git a/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php index cdef77ef..c0365671 100644 --- a/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/ShopsControllerTest.php @@ -2,11 +2,20 @@ 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; 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; +use function Pest\Laravel\post; +use function Pest\Laravel\postJson; describe('ShopsController', function () { @@ -85,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"); }); @@ -143,14 +153,26 @@ describe('ShopsController', function () { it('can access pickup exceptions form', function () { /** @var \Tests\TestCase $this */ // GIVEN - $shop = Shop::factory()->create(); + $shop = Shop::factory()->create(); + $exception = PickupException::factory()->create([ + 'date' => '2026-05-08', + 'label' => 'Victoire 1945', + ]); + $shop->pickupExceptions()->attach($exception->id, [ + 'replacement_date' => '2026-05-07', + 'order_deadline_at' => '2026-05-04 16:00:00', + ]); // WHEN $response = $this->get("/bo/shops/{$shop->id}/pickup-exceptions"); // THEN expect($response->status())->toBe(200); - $response->assertViewIs('bo.shops.pickup-exceptions'); + $response->assertViewIs('bo.shops.pickup-exceptions') + ->assertSee('lundi 14h:00', false) + ->assertSee('vendredi', false) + ->assertSee('2026-05-04T18:00', false) + ->assertDontSee('à 02:00'); }); it('can submit pickup exceptions', function () { @@ -192,4 +214,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/Controllers/Bo/SlidesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php index e3187fee..2207c8e2 100644 --- a/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/SlidesControllerTest.php @@ -2,10 +2,21 @@ 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; 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; +use function Pest\Laravel\post; +use function Pest\Laravel\postJson; describe('SlidesController', function (): void { beforeEach(function (): void { @@ -26,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')); }); @@ -38,6 +53,18 @@ describe('SlidesController', function (): void { // THEN expect($response->status())->toBe(200); $response->assertViewIs('bo.slides.create'); + $extensions = implode(', ', array_map( + static fn (string $ext): string => '.' . ltrim($ext, '.'), + StoreSlideRequest::ALLOWED_EXTENSIONS, + )); + $expectedHelper = __('Allowed extensions: :extensions (:maxSize MB max). Required dimensions: :width px by :height px', [ + 'extensions' => $extensions, + 'maxSize' => StoreSlideRequest::MAX_FILE_SIZE_KB / 1024, + 'width' => StoreSlideRequest::PICTURE_WIDTH, + 'height' => StoreSlideRequest::PICTURE_HEIGHT, + ]); + + $response->assertSee(json_encode($expectedHelper, JSON_THROW_ON_ERROR), false); }); it('can store a slide', function (): void { @@ -60,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"); }); @@ -127,7 +155,75 @@ 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'); }); + + 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 2e71e3dc..f165722e 100644 --- a/tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/TagsControllerTest.php @@ -2,9 +2,18 @@ declare(strict_types=1); +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 { @@ -113,14 +122,75 @@ 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'); + }); + + 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/Controllers/Fo/Ajax/BasketControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php index 13768fed..421dbed1 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Ajax/BasketControllerTest.php @@ -2,10 +2,34 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Ajax; + +use App\Models\Customer; use App\Models\Page; +use App\Models\Product; +use App\Models\Range; use Database\Seeders\ContentSeeder; +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\BasketProduct; +use Domain\Models\ValueObjects\DiscountRate; +use Domain\Models\ValueObjects\Email; +use Domain\Models\ValueObjects\Entities\ProductId; +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 Shared\Helpers\UuidHelper; describe('BasketController', function () { it('can access post /ajax/basket/add', function () { @@ -75,4 +99,100 @@ describe('BasketController', function () { // THEN $response->assertStatus(302); }); + + it('serializes multi-item basket without N+1 queries and respects product publication status', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'email' => new Email('basket-nplusone@example.com'), + 'hashcode' => UuidHelper::v4()->toString(), + ]); + + $range = new Range(); + $range->name = 'Gamme Test Panier'; + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + /** @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([ + 'range_id' => $range->id, + 'name' => "Produit Panier {$i}", + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Description', + 'status' => $i !== 5, + ]); + $product->order = $i; + $product->price = Money::EUR(1000); + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt'; + $product->picture_large_title = 'title'; + $product->save(); + + $basket->addOrUpdate(new BasketProduct( + id: new ProductId(UuidHelper::fromString((string) $product->id)), + name: $product->name, + qty: 1, + unitPriceHt: Money::EUR(1000), + unitDiscount: Money::EUR(0), + taxRate: TaxRate::TVA_20, + weightGrams: 1000, + brand: ProductBrand::loue, + incoId: null, + orderUnit: OrderUnit::PCE, + slug: $product->slug, + picture: null, + description: 'Description', + weightVariable: false, + discountRate: DiscountRate::zero(), + priceKgTtc: Money::EUR(1200), + )); + } + + $basketRepository->persist($basket); + + // WHEN + $this->actingAs($customer, 'frontend'); + DB::flushQueryLog(); + DB::enableQueryLog(); + $response = $this->getJson('/ajax/basket/get'); + $queries = DB::getQueryLog(); + DB::disableQueryLog(); + + // THEN + $response->assertStatus(200) + ->assertJsonCount(5, 'data.items'); + + /** @var list> $items */ + $items = $response->json('data.items'); + expect($items[0]['unitPriceHt'])->not->toBeNull() + ->and($items[4]['unitPriceHt'])->toBeNull() + ->and(count($queries))->toBe(1); + }); }); diff --git a/tests/Feature/App/Http/Controllers/Fo/Ajax/PickupControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Ajax/PickupControllerTest.php index cd4d61bd..27a0feaf 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Ajax/PickupControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Ajax/PickupControllerTest.php @@ -2,13 +2,22 @@ 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; use App\Models\Page; +use App\Models\Shop; use Database\Seeders\ContentSeeder; +use Domain\Models\ValueObjects\Email; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\View; +use Shared\Helpers\UuidHelper; +use Shared\ValueObjects\CrmHashcode; -describe('PickupController', function () { - it('can access get /ajax/shops/1/pickup-timeslots', function () { +describe('PickupController', function (): void { + it('redirects unauthenticated guest requesting pickup timeslots to login', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $this->seed(ContentSeeder::class); @@ -21,7 +30,62 @@ describe('PickupController', function () { // WHEN $response = $this->get('/ajax/shops/1/pickup-timeslots'); + // THEN + $response->assertRedirectToRoute('fo.auth.connexion'); + }); + + it('returns 404 for unknown shop when authenticated active employee requests pickup timeslots', 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('employee@example.com'); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + $this->withoutMiddleware([ + EnsureCustomerEmailIsVerified::class, + CustomerIsEmployed::class, + ]); + + // WHEN + $response = $this->get('/ajax/shops/99999/pickup-timeslots'); + // THEN $response->assertStatus(404); }); + + it('returns pickup timeslots for an existing shop when authenticated active employee', 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(); + + $shop = Shop::factory()->create(); + $customer = new Customer(); + $customer->email = new Email('employee2@example.com'); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + $this->withoutMiddleware([ + EnsureCustomerEmailIsVerified::class, + CustomerIsEmployed::class, + ]); + + // WHEN + $response = $this->get(route('ajax.shops.pickup-timeslots', $shop)); + + // THEN + $response->assertStatus(200); + }); }); diff --git a/tests/Feature/App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php index 6734818f..2a1d9726 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; @@ -19,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 () { @@ -57,7 +59,7 @@ describe('ProductsController (Ajax)', function () { 'priceTtc', 'priceKgTtc', 'discountedPriceTtc', - 'is_available', + 'is_orderable', 'can_add_to_basket', 'showStrippedPrice', 'nutriscore', @@ -77,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'); @@ -141,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/ForgotPasswordControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php index 49785b95..9772a764 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/ForgotPasswordControllerTest.php @@ -2,21 +2,59 @@ declare(strict_types=1); +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; +use Domain\Models\Entities\Shopper; +use Domain\Models\ValueObjects\CrmCustomer; +use Domain\Models\ValueObjects\Email; +use Domain\Models\ValueObjects\Entities\ShopperId; +use Domain\Models\ValueObjects\Matricule; +use Domain\Models\ValueObjects\ShopperEstablishmentCode; +use Domain\Models\ValueObjects\ShopperServiceCode; +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; + +function sharePagesForForgotPasswordTest(): void +{ + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); +} 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 $this->seed(ContentSeeder::class); - View::share('PageList', Page::getCached() - ->mapWithKeys(fn ($page) => [ - $page->slug->value() => $page, - ])); - Cache::flush(); + sharePagesForForgotPasswordTest(); // WHEN $response = $this->get('/auth/mot-de-passe-oublie'); @@ -29,11 +67,7 @@ describe('ForgotPasswordController', function () { /** @var \Tests\TestCase $this */ // GIVEN $this->seed(ContentSeeder::class); - View::share('PageList', Page::getCached() - ->mapWithKeys(fn ($page) => [ - $page->slug->value() => $page, - ])); - Cache::flush(); + sharePagesForForgotPasswordTest(); // WHEN $response = $this->post('/auth/mot-de-passe-oublie', []); @@ -41,4 +75,203 @@ describe('ForgotPasswordController', function () { // THEN $response->assertStatus(302); }); + + it('returns the generic status response for an unknown email without sending any notification', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + Notification::fake(); + $this->seed(ContentSeeder::class); + sharePagesForForgotPasswordTest(); + + $crmService = $this->mock(CrmService::class); + $crmService->shouldNotReceive('getCustomerFromEmail'); + + // WHEN + $response = $this->from('/auth/mot-de-passe-oublie') + ->post('/auth/mot-de-passe-oublie', ['email' => 'unknown@example.com']); + + // THEN + $response->assertRedirect('/auth/mot-de-passe-oublie') + ->assertSessionHas('status', trans('Please check your email, if we know you you should receive a reset link')); + Notification::assertNothingSent(); + expect(Customer::query()->count())->toBe(0); + }); + + it('does not create an orphan local customer when email exists in CRM without local account', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + Notification::fake(); + $this->seed(ContentSeeder::class); + sharePagesForForgotPasswordTest(); + + $crmService = $this->mock(CrmService::class); + $crmService->shouldNotReceive('getCustomerFromEmail'); + + // WHEN + $response = $this->from('/auth/mot-de-passe-oublie') + ->post('/auth/mot-de-passe-oublie', ['email' => 'crm-only@example.com']); + + // THEN + $response->assertRedirect('/auth/mot-de-passe-oublie') + ->assertSessionHas('status', trans('Please check your email, if we know you you should receive a reset link')); + Notification::assertNothingSent(); + expect(Customer::query()->count())->toBe(0); + }); + + it('returns the identical generic status response without leaking account state for an inactive employee', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + Notification::fake(); + $this->seed(ContentSeeder::class); + sharePagesForForgotPasswordTest(); + + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'email' => new Email('inactive-employee@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + $inactiveShopper = new Shopper( + id: $customer->getId(), + email: new Email('inactive-employee@example.com'), + matricule: new Matricule('1234567'), + nom: 'Doe', + prenom: 'Jane', + startDate: CarbonImmutable::now()->subMonth(), + endDate: CarbonImmutable::now()->subDay(), + etablissement: new ShopperEstablishmentCode('01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('01'), + ); + + $shopperService = \Mockery::mock(ShopperService::class); + $shopperService->shouldReceive('getShopperFor') + ->once() + ->with(\Mockery::on(fn (ShopperId $id): bool => $id->equals($customer->getId()))) + ->andReturn($inactiveShopper); + $this->app->instance(ShopperService::class, $shopperService); + + // WHEN + $response = $this->from('/auth/mot-de-passe-oublie') + ->post('/auth/mot-de-passe-oublie', ['email' => 'inactive-employee@example.com']); + + // THEN + $response->assertRedirect('/auth/mot-de-passe-oublie') + ->assertSessionHas('status', trans('Please check your email, if we know you you should receive a reset link')) + ->assertSessionHasNoErrors(); + Notification::assertNothingSent(); + }); + + it('returns the identical JSON 202 response for an inactive employee without sending any notification', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + Notification::fake(); + $this->seed(ContentSeeder::class); + sharePagesForForgotPasswordTest(); + + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'email' => new Email('inactive-json@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + $shopperService = \Mockery::mock(ShopperService::class); + $shopperService->shouldReceive('getShopperFor') + ->once() + ->with(\Mockery::on(fn (ShopperId $id): bool => $id->equals($customer->getId()))) + ->andReturn(null); + $this->app->instance(ShopperService::class, $shopperService); + + // WHEN + $response = $this->postJson('/auth/mot-de-passe-oublie', ['email' => 'inactive-json@example.com']); + + // THEN + $response->assertStatus(202) + ->assertJson(['message' => trans('Please check your email, if we know you you should receive a reset link')]); + Notification::assertNothingSent(); + }); + + it('sends the reset password notification and returns the generic response for an active employee', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + Notification::fake(); + $this->seed(ContentSeeder::class); + sharePagesForForgotPasswordTest(); + + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'email' => new Email('active-employee@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + $crmCustomer = new CrmCustomer( + hashcode: $customer->hashcode->value, + email: 'active-employee@example.com', + password: 'old-password', + firstname: 'John', + lastname: 'Doe', + 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('getCustomerFromEmail') + ->once() + ->with('active-employee@example.com') + ->andReturn($crmCustomer); + + $activeShopper = new Shopper( + id: $customer->getId(), + email: new Email('active-employee@example.com'), + matricule: new Matricule('1234568'), + nom: 'Doe', + prenom: 'John', + startDate: CarbonImmutable::now()->subMonth(), + endDate: CarbonImmutable::now()->addMonth(), + etablissement: new ShopperEstablishmentCode('01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('01'), + ); + + $shopperService = \Mockery::mock(ShopperService::class); + $shopperService->shouldReceive('getShopperFor') + ->once() + ->with(\Mockery::on(fn (ShopperId $id): bool => $id->equals($customer->getId()))) + ->andReturn($activeShopper); + $this->app->instance(ShopperService::class, $shopperService); + + // WHEN + $response = $this->from('/auth/mot-de-passe-oublie') + ->post('/auth/mot-de-passe-oublie', ['email' => 'active-employee@example.com']); + + // THEN + $response->assertRedirect('/auth/mot-de-passe-oublie') + ->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(); + }); }); diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php index b41e4a56..2c910148 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php @@ -2,10 +2,14 @@ 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; use App\Models\Page; use App\Services\CrmService; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Database\Seeders\ContentSeeder; use Domain\Enums\Country; @@ -18,11 +22,29 @@ use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; 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\Helpers\UuidHelper; +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 @@ -97,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(UuidHelper::v4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); @@ -118,7 +140,7 @@ describe('LoginController', function () { ])); Cache::flush(); - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'email' => new Email('test@example.com'), 'hashcode' => (string) Str::uuid(), ]); @@ -170,7 +192,7 @@ describe('LoginController', function () { ])); Cache::flush(); - $customer = Customer::forceCreate([ + $customer = Customer::query()->forceCreate([ 'email' => new Email('test2@example.com'), 'hashcode' => (string) Str::uuid(), ]); @@ -195,6 +217,9 @@ describe('LoginController', function () { $crmService = $this->mock(CrmService::class); $crmService->shouldReceive('getCustomerFromEmail')->with('test2@example.com')->andReturn($crmCustomer); $crmService->shouldReceive('login')->with('test2@example.com', 'password')->andReturnTrue(); + $crmService->shouldReceive('getCustomerFromHashCode') + ->withArgs(fn (CrmHashcode $hashcode): bool => $hashcode->value === $customer->hashcode->value) + ->andReturn($crmCustomer); $shopper = new Shopper( id: clone $customer->getId(), @@ -227,4 +252,79 @@ describe('LoginController', function () { $response->assertRedirect(route('fo.pages.home')); $response->assertSessionHas('success', \trans('You are logged in!')); }); + + it('does not flash success message when email is not verified during login', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + Notification::fake(); + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + $customer = Customer::query()->forceCreate([ + 'email' => new Email('unverified@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + $crmCustomer = new CrmCustomer( + hashcode: $customer->hashcode->value, + email: 'unverified@example.com', + password: 'password', + firstname: 'Jane', + lastname: 'Doe', + birthDate: null, + phone: null, + address: null, + address2: null, + city: null, + postcode: null, + country: Country::france, + optIn: false, + status: false, + lastConnection: null, + ); + $crmService = $this->mock(CrmService::class); + $crmService->shouldReceive('getCustomerFromEmail')->with('unverified@example.com')->andReturn($crmCustomer); + $crmService->shouldReceive('login') + ->with('unverified@example.com', 'password') + ->andThrow(new CrmCustomerNotActivatedException()); + $crmService->shouldReceive('getCustomerFromHashCode') + ->withArgs(fn (CrmHashcode $hashcode): bool => $hashcode->value === $customer->hashcode->value) + ->andReturn($crmCustomer); + + $shopper = new Shopper( + id: clone $customer->getId(), + email: new Email('unverified@example.com'), + matricule: new Matricule('1234568'), + nom: 'Doe', + prenom: 'Jane', + startDate: CarbonImmutable::now()->subDays(1), + endDate: null, + etablissement: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), + ); + + $shopperService = \Mockery::mock(ShopperService::class); + $shopperService->shouldReceive('getShopperFor') + ->withArgs(function ($arg) use ($customer) { + return $arg instanceof ShopperId && (string) $arg->value === $customer->id; + }) + ->andReturn($shopper); + $this->app->instance(ShopperService::class, $shopperService); + + // WHEN + $response = $this->post('/auth/connexion', [ + 'email' => 'unverified@example.com', + 'password' => 'password', + ]); + + // THEN + $response->assertRedirect(route('fo.pages.home')); + $response->assertSessionMissing('success'); + Notification::assertSentTo($customer, VerifyEmail::class); + }); }); diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php index 18f565b1..a74e74b6 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/RegisterControllerTest.php @@ -2,10 +2,31 @@ 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; +use App\Cqs\Actions\Customers\RegisterCustomerOutput; +use App\Http\Controllers\Fo\Auth\RegisterController; +use App\Http\Requests\Fo\Auth\RegisterRequest; +use App\Models\Customer; +use App\Models\Employee; use App\Models\Page; use Database\Seeders\ContentSeeder; +use Domain\Models\ValueObjects\Code; +use Domain\Models\ValueObjects\Email; +use Domain\Models\ValueObjects\Matricule; +use Domain\Models\ValueObjects\ShopperEstablishmentCode; +use Domain\Models\ValueObjects\ShopperServiceCode; +use Domain\Models\ValueObjects\ShopperSiteCode; +use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\View; +use Illuminate\Support\ViewErrorBag; +use Shared\Helpers\UuidHelper; +use Shared\ValueObjects\CrmHashcode; +use Webmozart\Assert\Assert; describe('RegisterController', function () { it('can access get /auth/inscription', function () { @@ -41,4 +62,216 @@ describe('RegisterController', function () { // THEN $response->assertStatus(302); }); + + it('returns 422 validation error on postJson /auth/inscription when employee already has a customer_id', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $customer = new Customer(['email' => new Email('existing@example.com')]); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); + $customer->saveOrFail(); + + $employee = new Employee(); + $employee->matricule = new Matricule('1234567'); + $employee->code = new Code('ABCDEF'); + $employee->nom = 'Doe'; + $employee->prenom = 'John'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('1'); + $employee->customer()->associate($customer); + $employee->saveOrFail(); + + // WHEN + $response = $this->postJson('/auth/inscription', [ + 'matricule' => '1234567', + 'code' => 'ABCDEF', + 'lastname' => 'Doe', + 'firstname' => 'John', + 'postal_code' => '75001', + 'city' => 'Paris', + 'email' => 'john.doe@example.com', + 'password' => 'Str0ng!Pass#2026', + 'password_confirmation' => 'Str0ng!Pass#2026', + 'ok_cgv' => '1', + 'birth_date' => '1990-01-01', + ]); + + // THEN + $response->assertStatus(422) + ->assertJsonValidationErrors(['matricule', 'code']); + }); + + it('renders verify view when RegisterCustomer returns SUCCESS', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $customer = new Customer(['email' => new Email('john.doe@example.com')]); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); + $customer->saveOrFail(); + + $input = new RegisterCustomerInput( + matricule: new Matricule('1234567'), + code: new Code('ABCDEF'), + firstname: 'John', + lastname: 'Doe', + email: new Email('john.doe@example.com'), + password: 'Str0ng!Pass#2026', + birthDate: new \DateTimeImmutable('1990-01-01'), + phone: null, + address: null, + postcode: '75001', + city: 'Paris', + ); + + $request = \Mockery::mock(RegisterRequest::class); + $request->shouldReceive('toRegisterCustomerInput')->once()->andReturn($input); + + $action = $this->app->make(RegisterCustomer::class); + + $executor = \Mockery::mock(Executor::class); + $executor->shouldReceive('execute') + ->once() + ->with($action, $input) + ->andReturn(RegisterCustomerOutput::success($customer)); + + $controller = new RegisterController($executor); + + // WHEN + $result = $controller->submitForm($request, $action); + + // THEN + 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 { + /** @var \Tests\TestCase $this */ + // GIVEN + $input = new RegisterCustomerInput( + matricule: new Matricule('1234567'), + code: new Code('ABCDEF'), + firstname: 'John', + lastname: 'Doe', + email: new Email('john.doe@example.com'), + password: 'Str0ng!Pass#2026', + birthDate: new \DateTimeImmutable('1990-01-01'), + phone: null, + address: null, + postcode: '75001', + city: 'Paris', + ); + + $request = \Mockery::mock(RegisterRequest::class); + $request->shouldReceive('toRegisterCustomerInput')->once()->andReturn($input); + $request->shouldReceive('except') + ->once() + ->with(['password', 'password_confirmation']) + ->andReturn(['matricule' => '1234567']); + + $action = $this->app->make(RegisterCustomer::class); + + $executor = \Mockery::mock(Executor::class); + $executor->shouldReceive('execute') + ->once() + ->with($action, $input) + ->andReturn(RegisterCustomerOutput::employeeAlreadyRegistered()); + + $controller = new RegisterController($executor); + + // WHEN + $result = $controller->submitForm($request, $action); + + // THEN + Assert::isInstanceOf($result, RedirectResponse::class); + $errors = $result->getSession()?->get('errors'); + 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 { + /** @var \Tests\TestCase $this */ + // GIVEN + $input = new RegisterCustomerInput( + matricule: new Matricule('1234567'), + code: new Code('ABCDEF'), + firstname: 'John', + lastname: 'Doe', + email: new Email('john.doe@example.com'), + password: 'Str0ng!Pass#2026', + birthDate: new \DateTimeImmutable('1990-01-01'), + phone: null, + address: null, + postcode: '75001', + city: 'Paris', + ); + + $request = \Mockery::mock(RegisterRequest::class); + $request->shouldReceive('toRegisterCustomerInput')->once()->andReturn($input); + $request->shouldReceive('except') + ->once() + ->with(['password', 'password_confirmation']) + ->andReturn(['matricule' => '1234567']); + + $action = $this->app->make(RegisterCustomer::class); + + $executor = \Mockery::mock(Executor::class); + $executor->shouldReceive('execute') + ->once() + ->with($action, $input) + ->andReturn(RegisterCustomerOutput::lockTimeout()); + + $controller = new RegisterController($executor); + + // WHEN + $result = $controller->submitForm($request, $action); + + // THEN + Assert::isInstanceOf($result, RedirectResponse::class); + $errors = $result->getSession()?->get('errors'); + 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 { + /** @var \Tests\TestCase $this */ + // GIVEN + $input = new RegisterCustomerInput( + matricule: new Matricule('1234567'), + code: new Code('ABCDEF'), + firstname: 'John', + lastname: 'Doe', + email: new Email('john.doe@example.com'), + password: 'Str0ng!Pass#2026', + birthDate: new \DateTimeImmutable('1990-01-01'), + phone: null, + address: null, + postcode: '75001', + city: 'Paris', + ); + + $request = \Mockery::mock(RegisterRequest::class); + $request->shouldReceive('toRegisterCustomerInput')->once()->andReturn($input); + $request->shouldReceive('except') + ->once() + ->with(['password', 'password_confirmation']) + ->andReturn(['matricule' => '1234567']); + + $action = $this->app->make(RegisterCustomer::class); + + $executor = \Mockery::mock(Executor::class); + $executor->shouldReceive('execute') + ->once() + ->with($action, $input) + ->andReturn(RegisterCustomerOutput::employeeInactive()); + + $controller = new RegisterController($executor); + + // WHEN + $result = $controller->submitForm($request, $action); + + // THEN + Assert::isInstanceOf($result, RedirectResponse::class); + $errors = $result->getSession()?->get('errors'); + 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/Auth/ResetPasswordControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php index 52db2afe..e79ec14c 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/ResetPasswordControllerTest.php @@ -2,12 +2,46 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Auth; + +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; +use Domain\Models\Entities\Shopper; +use Domain\Models\ValueObjects\CrmCustomer; +use Domain\Models\ValueObjects\Email; +use Domain\Models\ValueObjects\Entities\ShopperId; +use Domain\Models\ValueObjects\Matricule; +use Domain\Models\ValueObjects\ShopperEstablishmentCode; +use Domain\Models\ValueObjects\ShopperServiceCode; +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 @@ -41,4 +75,294 @@ describe('ResetPasswordController', function () { // THEN $response->assertStatus(302); }); + + it('throws CustomerNotEmployedException when shopper is null during password reset', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'email' => new Email('reset-null@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + $crmCustomer = new CrmCustomer( + hashcode: $customer->hashcode->value, + email: 'reset-null@example.com', + password: 'old-password', + firstname: 'John', + lastname: 'Doe', + 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('getCustomerFromEmail')->with('reset-null@example.com')->andReturn($crmCustomer); + $crmService->shouldNotReceive('resetPasswordFor'); + + $token = Password::createToken($customer); + + $shopperService = \Mockery::mock(ShopperService::class); + $shopperService->shouldReceive('getShopperFor') + ->withArgs(fn ($arg): bool => $arg instanceof ShopperId && (string) $arg->value === $customer->id) + ->andReturn(null); + $this->app->instance(ShopperService::class, $shopperService); + + $this->withoutExceptionHandling(); + + // WHEN / THEN + expect(fn () => $this->post("/auth/reinitialiser-mdp/{$token}", [ + 'token' => $token, + 'email' => 'reset-null@example.com', + 'password' => 'Password123!@#', + 'password_confirmation' => 'Password123!@#', + ]))->toThrow(CustomerNotEmployedException::class); + + expect(Auth::guard('frontend')->check())->toBeFalse(); + }); + + it('throws CustomerNotEmployedException when shopper is inactive during password reset', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'email' => new Email('reset-inactive@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + $crmCustomer = new CrmCustomer( + hashcode: $customer->hashcode->value, + email: 'reset-inactive@example.com', + password: 'old-password', + firstname: 'John', + lastname: 'Doe', + 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('getCustomerFromEmail')->with('reset-inactive@example.com')->andReturn($crmCustomer); + $crmService->shouldNotReceive('resetPasswordFor'); + + $token = Password::createToken($customer); + + $shopper = new Shopper( + id: clone $customer->getId(), + email: new Email('reset-inactive@example.com'), + matricule: new Matricule('1234567'), + nom: 'Doe', + prenom: 'John', + startDate: CarbonImmutable::now()->subDays(10), + endDate: CarbonImmutable::now()->subDays(1), + etablissement: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), + ); + + $shopperService = \Mockery::mock(ShopperService::class); + $shopperService->shouldReceive('getShopperFor') + ->withArgs(fn ($arg): bool => $arg instanceof ShopperId && (string) $arg->value === $customer->id) + ->andReturn($shopper); + $this->app->instance(ShopperService::class, $shopperService); + + $this->withoutExceptionHandling(); + + // WHEN / THEN + expect(fn () => $this->post("/auth/reinitialiser-mdp/{$token}", [ + 'token' => $token, + 'email' => 'reset-inactive@example.com', + 'password' => 'Password123!@#', + 'password_confirmation' => 'Password123!@#', + ]))->toThrow(CustomerNotEmployedException::class); + + expect(Auth::guard('frontend')->check())->toBeFalse(); + }); + + it('resets password and logs in when shopper is active and email is verified', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'email' => new Email('reset-verified@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + $crmCustomer = new CrmCustomer( + hashcode: $customer->hashcode->value, + email: 'reset-verified@example.com', + password: 'old-password', + firstname: 'John', + lastname: 'Doe', + 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('getCustomerFromEmail')->with('reset-verified@example.com')->andReturn($crmCustomer); + $crmService->shouldReceive('resetPasswordFor') + ->once() + ->withArgs(fn (Email $email, string $password): bool => $email->value === 'reset-verified@example.com' + && $password === 'Password123!@#') + ->andReturnTrue(); + $crmService->shouldReceive('getCustomerFromHashCode') + ->once() + ->andReturn($crmCustomer); + + $token = Password::createToken($customer); + + $shopper = new Shopper( + id: clone $customer->getId(), + email: new Email('reset-verified@example.com'), + matricule: new Matricule('1234567'), + nom: 'Doe', + prenom: 'John', + startDate: CarbonImmutable::now()->subDays(1), + endDate: null, + etablissement: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), + ); + + $shopperService = \Mockery::mock(ShopperService::class); + $shopperService->shouldReceive('getShopperFor') + ->withArgs(fn ($arg): bool => $arg instanceof ShopperId && (string) $arg->value === $customer->id) + ->andReturn($shopper); + $this->app->instance(ShopperService::class, $shopperService); + + // WHEN + $response = $this->post("/auth/reinitialiser-mdp/{$token}", [ + 'token' => $token, + 'email' => 'reset-verified@example.com', + 'password' => 'Password123!@#', + 'password_confirmation' => 'Password123!@#', + ]); + + // THEN + $response->assertRedirect(route('fo.pages.home')); + expect(Auth::guard('frontend')->check())->toBeTrue() + ->and(Auth::guard('frontend')->id())->toBe($customer->id); + }); + + it('resets password without logging in when shopper is active and email is not verified', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'email' => new Email('reset-unverified@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + $crmCustomer = new CrmCustomer( + hashcode: $customer->hashcode->value, + email: 'reset-unverified@example.com', + password: 'old-password', + firstname: 'John', + lastname: 'Doe', + birthDate: null, + phone: null, + address: null, + address2: null, + city: null, + postcode: null, + country: Country::france, + optIn: false, + status: false, + lastConnection: null, + ); + + $crmService = $this->mock(CrmService::class); + $crmService->shouldReceive('getCustomerFromEmail')->with('reset-unverified@example.com')->andReturn($crmCustomer); + $crmService->shouldReceive('resetPasswordFor') + ->once() + ->withArgs(fn (Email $email, string $password): bool => $email->value === 'reset-unverified@example.com' + && $password === 'Password123!@#') + ->andReturnTrue(); + $crmService->shouldReceive('getCustomerFromHashCode') + ->once() + ->andReturn($crmCustomer); + + $token = Password::createToken($customer); + + $shopper = new Shopper( + id: clone $customer->getId(), + email: new Email('reset-unverified@example.com'), + matricule: new Matricule('1234567'), + nom: 'Doe', + prenom: 'John', + startDate: CarbonImmutable::now()->subDays(1), + endDate: null, + etablissement: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), + ); + + $shopperService = \Mockery::mock(ShopperService::class); + $shopperService->shouldReceive('getShopperFor') + ->withArgs(fn ($arg): bool => $arg instanceof ShopperId && (string) $arg->value === $customer->id) + ->andReturn($shopper); + $this->app->instance(ShopperService::class, $shopperService); + + // WHEN + $response = $this->post("/auth/reinitialiser-mdp/{$token}", [ + 'token' => $token, + 'email' => 'reset-unverified@example.com', + 'password' => 'Password123!@#', + 'password_confirmation' => 'Password123!@#', + ]); + + // THEN + $response->assertRedirect(route('fo.pages.home')); + expect(Auth::guard('frontend')->check())->toBeFalse(); + }); }); 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/Fo/AuthTest.php b/tests/Feature/App/Http/Controllers/Fo/AuthTest.php similarity index 86% rename from tests/Feature/Fo/AuthTest.php rename to tests/Feature/App/Http/Controllers/Fo/AuthTest.php index b584cf3a..860fa17f 100644 --- a/tests/Feature/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..d76df87d 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php @@ -2,10 +2,13 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo\Customers; + 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; @@ -15,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\Helpers\UuidHelper; 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 */ @@ -31,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(); @@ -56,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(); @@ -81,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(); @@ -105,14 +122,14 @@ describe('CustomerController', function () { ])); Cache::flush(); - $hashcode = new CrmHashcode(Uuid::uuid4()); - $customer = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + $hashcode = new CrmHashcode(UuidHelper::v4()); + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->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'), @@ -171,14 +188,14 @@ describe('CustomerController', function () { ])); Cache::flush(); - $hashcode = new CrmHashcode(Uuid::uuid4()); - $customer = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + $hashcode = new CrmHashcode(UuidHelper::v4()); + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->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 96e3d88e..aba25ed8 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; @@ -9,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; @@ -30,10 +33,23 @@ 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 () { + 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 @@ -45,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(); @@ -70,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(); @@ -94,14 +110,14 @@ describe('OrderController', function () { ])); Cache::flush(); - $hashcode = new CrmHashcode(Uuid::uuid4()); - $customer = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + $hashcode = new CrmHashcode(UuidHelper::v4()); + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->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'), @@ -116,16 +132,23 @@ describe('OrderController', function () { ]); $shop = Shop::factory()->create(); - $refUuid = Uuid::uuid7(); + $refUuid = UuidHelper::v7(); $reference = new OrderReference($refUuid); $ref = (string) $reference; - Order::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, '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(), ]); @@ -161,9 +184,16 @@ 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; }); }); @@ -177,14 +207,14 @@ describe('OrderController', function () { ])); Cache::flush(); - $hashcode = new CrmHashcode(Uuid::uuid4()); - $customer = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + $hashcode = new CrmHashcode(UuidHelper::v4()); + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->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'), @@ -199,16 +229,23 @@ describe('OrderController', function () { ]); $shop = Shop::factory()->create(); - $refUuid = Uuid::uuid7(); + $refUuid = UuidHelper::v7(); $reference = new OrderReference($refUuid); $ref = (string) $reference; - $order = Order::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + $order = Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), 'shop_id' => $shop->id, '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(), ]); @@ -246,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(UuidHelper::v4()); + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->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(UuidHelper::v7()); + Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->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/Customers/PasswordControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/PasswordControllerTest.php index 4a6250e1..0754aa5a 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; @@ -9,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 () { @@ -24,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(); @@ -49,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 6ed3777e..ddd8d185 100644 --- a/tests/Feature/App/Http/Controllers/Fo/NewsletterControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/NewsletterControllerTest.php @@ -2,12 +2,14 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Fo; + use App\Models\Page; 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 () { @@ -21,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 dce49c08..66d40e5d 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/ContactControllerTest.php @@ -5,14 +5,22 @@ declare(strict_types=1); namespace Tests\Feature\App\Http\Controllers\Fo\Pages; use App\Dto\ShopDto; -use App\Mail\SendContactMail; +use App\Jobs\SendContactMailJob; +use App\Lib\PrivateS3Disk; use App\Models\Page; use App\Models\Shop; use Database\Seeders\ContentSeeder; +use Domain\Models\ValueObjects\OrderReference; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Config; -use Illuminate\Support\Facades\Mail; +use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\View; +use Mockery\MockInterface; +use Shared\Helpers\UuidHelper; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\DiskName; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; describe('ContactController', function (): void { beforeEach(function (): void { @@ -63,17 +71,17 @@ describe('ContactController', function (): void { $response->assertViewHas('magasin', fn ($magasin) => $magasin instanceof ShopDto && $magasin->name === 'Boutique Cocotte'); }); - it('submits contact form and sends email', function (): void { + it('submits contact form and dispatches contact mail job', function (): void { /** @var \Tests\TestCase $this */ // GIVEN - Mail::fake(); + Queue::fake(); $data = [ 'first_name' => 'Jean', 'last_name' => 'Dupont', 'email' => 'jean.dupont@gmail.com', 'subject' => 'Question', - 'order_ref' => '123456', + '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', ]; @@ -84,7 +92,75 @@ describe('ContactController', function (): void { // THEN $response->assertRedirect('/contactez-nous'); $response->assertSessionHas('status', true); - Mail::assertQueued(SendContactMail::class); + Queue::assertPushed( + SendContactMailJob::class, + fn (SendContactMailJob $job): bool => $job->recipientEmail === 'test@example.com' + && $job->data->email === 'jean.dupont@gmail.com' + ); + }); + + it('submits contact form with an attachment uploaded via StorageService', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + Queue::fake(); + $file = UploadedFile::fake()->create('piece.pdf', 100, 'application/pdf'); + $this->mock(StorageService::class, function (MockInterface $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); + Queue::assertPushed( + SendContactMailJob::class, + fn (SendContactMailJob $job): bool => $job->data->file?->path === 'contact-attachments/piece.pdf' + ); + }); + + it('throttles contact form submissions after 5 attempts within 2 minutes', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + Queue::fake(); + + $data = [ + 'first_name' => 'Jean', + 'last_name' => 'Dupont', + 'email' => 'jean.dupont@gmail.com', + 'subject' => 'Question', + 'message' => 'Bonjour, ceci est un message de test qui contient au moins vingt caractères.', + 'ok_cgv' => '1', + ]; + + // WHEN + for ($i = 0; $i < 5; $i++) { + $this->from('/contactez-nous') + ->post('/contactez-nous', $data) + ->assertStatus(302); + } + + $throttledResponse = $this->from('/contactez-nous')->post('/contactez-nous', $data); + + // THEN + $throttledResponse->assertStatus(429); }); it('redirects with validation errors when form data is invalid', function (): void { diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php index be346894..f3bd4030 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php @@ -2,11 +2,14 @@ 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\Range; use App\Models\Slide; +use Carbon\CarbonImmutable; use Database\Seeders\ContentSeeder; use Domain\Enums\DiscountType; use Domain\Enums\ProductBrand; @@ -15,11 +18,26 @@ 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; +use Shared\Helpers\UuidHelper; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; 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 @@ -48,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; @@ -66,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'; @@ -137,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; @@ -153,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'; @@ -175,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'; @@ -210,4 +228,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 = new StorageFilePath('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) UuidHelper::v7(); + $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/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 19e282c9..41b1488a 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/ProductsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/ProductsControllerTest.php @@ -2,11 +2,64 @@ 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; describe('ProductsController', function () { + $createProduct = static function (string $name, bool $status, int $order): Product { + $range = new Range(); + $range->name = "Gamme {$name}"; + $range->status = true; + $range->order = $order; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + $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' => $status, + 'star' => false, + ]); + $product->order = $order; + $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(); + + return $product; + }; + it('can access get /produits', function () { /** @var \Tests\TestCase $this */ // GIVEN @@ -23,4 +76,148 @@ describe('ProductsController', function () { // THEN $response->assertStatus(200); }); + + 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); + $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}"); + + // THEN + $response->assertStatus(200); + /** @var array $associated */ + $associated = $response->viewData('associatedProducts'); + $associatedNames = array_column($associated, '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 { + // 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/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php b/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php new file mode 100644 index 00000000..d90bc829 --- /dev/null +++ b/tests/Feature/App/Http/Controllers/Fo/ProductCharacterizationTest.php @@ -0,0 +1,396 @@ +seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [$page->slug->value() => $page])); + Cache::flush(); +} + +function characterizationCustomer(string $email): Customer +{ + $customer = new Customer(); + $customer->email = new Email($email); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); + $customer->save(); + + return $customer; +} + +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; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + $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' => $status, + 'star' => $star, + ]); + $product->order = 1; + $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->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; +} + +function characterizationDiscount(): Discount +{ + $discount = new Discount(); + $discount->type = DiscountType::AMOUNT; + $discount->value = DiscountValue::fromAmount(Money::EUR(100)); + $discount->is_old_price_displayed = true; + $discount->save(); + + return $discount; +} + +describe('FO product pricing & orderability (characterization)', function (): void { + it('hides every price from guests', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + characterizationBootFo($this); + characterizationProduct('Produit Invité'); + + // WHEN + $response = $this->getJson(route('ajax.products.filter', ['search' => 'Produit Invité'])); + + // THEN + $response->assertOk(); + $row = $response->json('data.0'); + Assert::isArray($row); + expect($row['priceTtc'])->toBeNull() + ->and($row['priceKgTtc'])->toBeNull() + ->and($row['discountedPriceTtc'])->toBeNull(); + }); + + it('exposes prices to an authenticated customer', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + characterizationBootFo($this); + $this->actingAs(characterizationCustomer('price-visible@example.com'), 'frontend'); + characterizationProduct('Produit Client'); + + // WHEN + $response = $this->getJson(route('ajax.products.filter', ['search' => 'Produit Client'])); + + // THEN + $response->assertOk(); + $row = $response->json('data.0'); + 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(); + }); + + it('applies the discount: discounted price is lower than base price', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + characterizationBootFo($this); + $this->actingAs(characterizationCustomer('discount@example.com'), 'frontend'); + characterizationProduct('Produit Remisé', discount: characterizationDiscount()); + + // WHEN + $response = $this->getJson(route('ajax.products.filter', ['search' => 'Produit Remisé'])); + + // THEN + $row = $response->json('data.0'); + 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(); + }); + + it('keeps discounted price equal to base price without discount', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + characterizationBootFo($this); + $this->actingAs(characterizationCustomer('nodiscount@example.com'), 'frontend'); + characterizationProduct('Produit Sans Remise'); + + // WHEN + $response = $this->getJson(route('ajax.products.filter', ['search' => 'Produit Sans Remise'])); + + // THEN + $row = $response->json('data.0'); + 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(); + }); + + it('flags a product without INCO as not orderable and not addable to basket', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + characterizationBootFo($this); + $this->actingAs(characterizationCustomer('noinco@example.com'), 'frontend'); + characterizationProduct('Produit Sans Inco'); + + // WHEN + $response = $this->getJson(route('ajax.products.filter', ['search' => 'Produit Sans Inco'])); + + // THEN + $row = $response->json('data.0'); + Assert::isArray($row); + expect($row['is_orderable'])->toBeFalse() + ->and($row['can_add_to_basket'])->toBeFalse(); + }); + + it('does not list unpublished products', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + characterizationBootFo($this); + characterizationProduct('Produit Brouillon', status: false); + + // WHEN + $response = $this->getJson(route('ajax.products.filter', ['search' => 'Produit Brouillon'])); + + // THEN + $response->assertOk(); + expect($response->json('data'))->toBe([]); + }); +}); + +describe('FO product page (characterization)', function (): void { + it('shows a published product', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + characterizationBootFo($this); + $this->actingAs(characterizationCustomer('show@example.com'), 'frontend'); + $product = characterizationProduct('Produit Fiche'); + + // WHEN + $response = $this->get(route('fo.products.show', ['productWithPricingPublished' => $product->slug])); + + // THEN + $response->assertOk(); + $response->assertSee('Produit Fiche'); + }); + + it('returns 404 for an unpublished product', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + characterizationBootFo($this); + $product = characterizationProduct('Produit Caché', status: false); + + // WHEN + $response = $this->get(route('fo.products.show', ['productWithPricingPublished' => $product->slug])); + + // THEN + $response->assertNotFound(); + }); + + it('returns 404 for an unknown slug', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + characterizationBootFo($this); + + // WHEN + $response = $this->get('/produit/slug-inexistant'); + + // THEN + $response->assertNotFound(); + }); + + it('resolves published product route binding through Executor', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + characterizationBootFo($this); + actingAs(characterizationCustomer('executor@example.com'), 'frontend'); + $product = characterizationProduct('Produit Executor'); + + $realExecutor = app(Executor::class); + $executed = []; + $spyExecutor = new class ($realExecutor, $executed) implements Executor + { + /** @var array */ + public array $executedClasses = []; + + /** + * @param array $executedClasses + */ + public function __construct( + private readonly Executor $inner, + array &$executedClasses, + ) { + $this->executedClasses = &$executedClasses; + } + + #[\Override] + public function execute(Action | Query $executable, ActionInput | QueryInput $input): mixed + { + $this->executedClasses[] = $executable::class; + + return $this->inner->execute($executable, $input); + } + }; + app()->instance(Executor::class, $spyExecutor); + + // WHEN + $response = get(route('fo.products.show', ['productWithPricingPublished' => $product->slug])); + + // THEN + $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('-.--') + ->assertDontSee('opacity-75') + ->assertDontSee(__('Coming soon')) + ->assertSee('class="basket-buttons"', false); + }); + + it('hides prices for guests and marks non-orderable products as coming soon on the product page', 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('-.--') + ->assertSee('opacity-75') + ->assertSee(__('Coming soon')) + ->assertDontSee('class="basket-buttons"', false); + }); + + it('renders prices and add-to-basket button without coming soon 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('-.--') + ->assertDontSee('opacity-75') + ->assertDontSee(__('Coming soon')) + ->assertSee('basket-buttons', false); + }); + + it('displays coming soon badge in home slider when a starred product is not orderable', function (): void { + // GIVEN + seed(ContentSeeder::class); + View::share('PageList', Page::getCached()->mapWithKeys(fn ($page) => [$page->slug->value() => $page])); + Cache::flush(); + characterizationProduct('Produit Vedette Indispo', withInco: false, star: true); + + // WHEN + $response = get(route('fo.pages.home')); + + // THEN + $response->assertOk() + ->assertSee('Produit Vedette Indispo') + ->assertSee(__('Coming soon')) + ->assertDontSee('class="basket-buttons"', false); + }); +}); diff --git a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php index f5d9319f..11202ec6 100644 --- a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php @@ -2,27 +2,64 @@ 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\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; use App\Cqs\Queries\Orders\GetBasketSummaryQueryOutput; use App\Cqs\Queries\Orders\GetOrderConfirmationQueryOutput; 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\OrderTunnelAttempt; 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\Exceptions\OrderTunnel\WeeklyLimitExceededException; +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; +use Domain\Models\ValueObjects\Entities\OrderId; use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\OrderEmployee; use Domain\Models\ValueObjects\OrderReference; @@ -31,12 +68,23 @@ 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\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; 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; -use Ramsey\Uuid\Uuid; +use Sentry\State\HubInterface; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; describe('TunnelController', function (): void { @@ -171,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'); @@ -181,8 +229,8 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); - $basket = new Basket(new BasketId(Uuid::uuid7())); - $this->mock(Executor::class, function ($mock) use ($basket): void { + $basket = new Basket(new BasketId(UuidHelper::v7())); + $this->mock(Executor::class, function (MockInterface $mock) use ($basket): void { $mock->shouldReceive('execute') ->once() ->andReturn(new GetBasketSummaryQueryOutput( @@ -213,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'); @@ -223,7 +271,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(); }); @@ -247,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'); @@ -269,7 +317,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( @@ -303,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'); @@ -325,18 +373,22 @@ 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); }); - $this->mock(OrderTunnelService::class, function ($mock): void { + $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 { + $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($slot); + ->andReturn(ApplyPickTimeSlotOutput::matched($slot)); }); // WHEN @@ -360,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'); @@ -382,17 +434,21 @@ 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); }); - $this->mock(OrderTunnelService::class, function ($mock): void { + $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 { + $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(null); + ->andReturn(ApplyPickTimeSlotOutput::unavailable()); }); // WHEN @@ -417,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'); @@ -427,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); @@ -444,7 +500,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( @@ -478,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'); @@ -488,11 +544,21 @@ describe('TunnelController', function (): void { ]); Gate::before(fn () => true); - $orderReference = new OrderReference(Uuid::uuid7()); - $this->mock(Executor::class, function ($mock) use ($orderReference): void { + $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() - ->andReturn($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 @@ -504,6 +570,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(UuidHelper::v4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + + $this->withoutMiddleware([ + CustomerIsEmployed::class, + EnsureCustomerEmailIsVerified::class, + ]); + Gate::before(fn () => true); + + $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() + ->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(FailPendingOrder::class), \Mockery::type(FailPendingOrderInput::class)) + ->andReturn(FailPendingOrderOutput::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 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(UuidHelper::v4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + + $this->withoutMiddleware([ + CustomerIsEmployed::class, + EnsureCustomerEmailIsVerified::class, + ]); + Gate::before(fn () => true); + + $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() + ->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 @@ -516,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'); @@ -526,10 +690,12 @@ 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() - ->andThrow(new WeeklyLimitExceededException()); + ->andReturn(PlacePendingOrderOutput::weeklyLimitExceeded( + 'The total amount for this delivery date has been exceeded. Please modify it to validate.' + )); }); // WHEN @@ -542,6 +708,207 @@ describe('TunnelController', function (): void { ->assertSessionHas('message'); }); + it('redirects to pick time slot with errors when ExpiredPickupTimeSlotException 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(UuidHelper::v4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + + $this->withoutMiddleware([ + CustomerIsEmployed::class, + EnsureCustomerEmailIsVerified::class, + ]); + Gate::before(fn () => true); + + $this->mock(Executor::class, function (MockInterface $mock): void { + $mock->shouldReceive('execute') + ->once() + ->andReturn(PlacePendingOrderOutput::expiredTimeSlot('Invalid or unavailable time slot')); + }); + + // WHEN + $response = $this->from('/commande/confirmation')->post('/commande/confirmation', [ + 'ok_cgv' => '1', + ]); + + // THEN + $response->assertRedirectToRoute('fo.sales.pick-time-slot') + ->assertSessionHasErrors([ + 'timeslot' => trans('Invalid or unavailable time slot'), + ]); + }); + + it('redirects to basket summary with errors when UnorderableProductException 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(UuidHelper::v4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + + $this->withoutMiddleware([ + CustomerIsEmployed::class, + EnsureCustomerEmailIsVerified::class, + ]); + Gate::before(fn () => true); + + $this->mock(Executor::class, function (MockInterface $mock): void { + $mock->shouldReceive('execute') + ->once() + ->andReturn(PlacePendingOrderOutput::unorderableProduct( + 'One or more products in your basket are no longer available for order.' + )); + }); + + // WHEN + $response = $this->from('/commande/confirmation')->post('/commande/confirmation', [ + 'ok_cgv' => '1', + ]); + + // THEN + $response->assertRedirectToRoute('fo.sales.summary') + ->assertSessionHasErrors([ + 'basket' => trans('One or more products in your basket are no longer available for order.'), + ]); + }); + + 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(UuidHelper::v4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + + $this->withoutMiddleware([ + CustomerIsEmployed::class, + EnsureCustomerEmailIsVerified::class, + ]); + Gate::before(fn () => true); + + $this->mock(Executor::class, function (MockInterface $mock): void { + $mock->shouldReceive('execute') + ->once() + ->andReturn(PlacePendingOrderOutput::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 + $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(UuidHelper::v4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + + $this->withoutMiddleware([ + CustomerIsEmployed::class, + EnsureCustomerEmailIsVerified::class, + ]); + Gate::before(fn () => true); + + $this->mock(Executor::class, function (MockInterface $mock): void { + $mock->shouldReceive('execute') + ->once() + ->andReturn(PlacePendingOrderOutput::lockTimeout()); + }); + + // 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.')); + }); + + it('logs out and redirects home with blocked message when inactiveShopper output 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-inactive@example.com'); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + + $this->withoutMiddleware([ + CustomerIsEmployed::class, + EnsureCustomerEmailIsVerified::class, + ]); + Gate::before(fn () => true); + + $this->mock(Executor::class, function (MockInterface $mock): void { + $mock->shouldReceive('execute') + ->once() + ->andReturn(PlacePendingOrderOutput::inactiveShopper('Employee account is no longer active.')); + }); + + // WHEN + $response = $this->from('/commande/confirmation')->post('/commande/confirmation', [ + 'ok_cgv' => '1', + ]); + + // THEN + $response->assertRedirectToRoute('fo.pages.home') + ->assertSessionHasErrors(); + expect(auth('frontend')->check())->toBeFalse(); + }); + it('displays confirmed order view when customer is authorized', function (): void { /** @var \Tests\TestCase $this */ // GIVEN @@ -554,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'); @@ -572,11 +939,11 @@ 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); - $order->status = OrderStatus::WAITING; + $order->status = OrderStatus::VALIDATED; $order->pickup_day = now()->addDays(2); $order->shop_id = $shop->id; $order->employee = new OrderEmployee( @@ -606,4 +973,764 @@ describe('TunnelController', function (): void { ->assertViewHas('shop') ->assertViewHas('mapUrl'); }); + + it('reports RegateExportFailedException to Sentry and redirects cleanly to confirmation instead of 500', 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-fail@example.com'); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + + $this->withoutMiddleware([ + CustomerIsEmployed::class, + EnsureCustomerEmailIsVerified::class, + ]); + Gate::before(fn () => true); + + $sentryHub = \Mockery::mock(HubInterface::class); + $sentryHub->shouldReceive('captureException') + ->once() + ->with(\Mockery::type(RegateExportFailedException::class)); + $this->app->instance(HubInterface::class, $sentryHub); + + $this->mock(Executor::class, function (MockInterface $mock): void { + $mock->shouldReceive('execute') + ->once() + ->andThrow(new RegateExportFailedException('SMTP transport down')); + }); + + // 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('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(UuidHelper::v4()); + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->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('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); + 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(UuidHelper::v4()); + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->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::FAILED) + ->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(); + } + }); + + 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(UuidHelper::v4()); + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->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(); + } + }); + + 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(UuidHelper::v4()); + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->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(UuidHelper::v4()); + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->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/Unit/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php b/tests/Feature/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php similarity index 92% rename from tests/Unit/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php rename to tests/Feature/App/Http/Middleware/EnsureCustomerEmailIsVerifiedTest.php index e36c3031..7d76b095 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,7 @@ 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); +use Webmozart\Assert\Assert; describe('EnsureCustomerEmailIsVerified', function () { it('redirects to fo.auth.verification.notice if customer is not verified', function () { @@ -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) { @@ -36,7 +38,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/HtmlSanitizerTest.php b/tests/Feature/App/Http/Middleware/HtmlSanitizerTest.php new file mode 100644 index 00000000..ed5c2ad3 --- /dev/null +++ b/tests/Feature/App/Http/Middleware/HtmlSanitizerTest.php @@ -0,0 +1,87 @@ +shouldNotReceive('clean'); + $middleware = new HtmlSanitizer($purifier); + + $request = Request::create('/test', 'POST', [ + 'name' => 'Jean', + 'password' => 'MonPass<123', + 'password_confirmation' => 'MonPass<123', + 'current_password' => 'Ancien 'Vieuxhandle($request, fn (Request $req): Response => new Response((string) json_encode($req->all()))); + + // THEN + expect($request->input('name'))->toBe('alert(1)Jean') + ->and($request->input('password'))->toBe('MonPass<123') + ->and($request->input('password_confirmation'))->toBe('MonPass<123') + ->and($request->input('current_password'))->toBe('Ancienand($request->input('password_old'))->toBe('VieuxshouldReceive('clean') + ->once() + ->with('

Hello

') + ->andReturn('

Hello

'); + + $middleware = new HtmlSanitizer($purifier); + + $request = Request::create('/test', 'POST', [ + 'content' => '

Hello

', + 'user' => [ + 'password' => 'Pass<123', + 'bio' => 'Bio', + ], + ]); + + // WHEN + $middleware->handle( + $request, + fn (Request $req): Response => new Response('ok'), + 'content', + ); + + // THEN + expect($request->input('content'))->toBe('

Hello

') + ->and($request->input('user.password'))->toBe('Pass<123') + ->and($request->input('user.bio'))->toBe('Bio'); + }); + + it('strips http scheme from oembed urls after purifying rich inputs', function (): void { + // GIVEN + $purifier = \Mockery::mock(Purifier::class); + $purifier->shouldReceive('clean') + ->once() + ->andReturn(''); + + $middleware = new HtmlSanitizer($purifier); + $request = Request::create('/test', 'POST', [ + 'content' => '', + ]); + + // WHEN + $middleware->handle($request, fn (Request $req): Response => new Response('ok'), 'content'); + + // THEN + expect($request->input('content'))->toBe(''); + }); +}); diff --git a/tests/Feature/App/Http/Middleware/TrustProxiesTest.php b/tests/Feature/App/Http/Middleware/TrustProxiesTest.php new file mode 100644 index 00000000..6a54572d --- /dev/null +++ b/tests/Feature/App/Http/Middleware/TrustProxiesTest.php @@ -0,0 +1,62 @@ + '203.0.113.42', + 'HTTP_X_FORWARDED_FOR' => '198.51.100.10', + ]); + $this->app->instance('request', $request); + $this->app->forgetInstance('clientIp'); + + // WHEN + $clientIp = $this->app->make('clientIp'); + + // THEN + Assert::string($clientIp); + expect($clientIp)->toBe('203.0.113.42'); + }); + + it('falls back to request ip when X-Real-Ip is invalid or absent', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + $request = Request::create('/', 'GET', [], [], [], [ + 'HTTP_X_REAL_IP' => 'not-an-ip', + 'REMOTE_ADDR' => '198.51.100.25', + ]); + $this->app->instance('request', $request); + $this->app->forgetInstance('clientIp'); + + // WHEN + $clientIp = $this->app->make('clientIp'); + + // THEN + Assert::string($clientIp); + expect($clientIp)->toBe('198.51.100.25'); + }); + + it('trusts X-Forwarded-For and ignores RFC 7239 Forwarded header', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + $response = $this->withHeaders([ + 'X-Forwarded-For' => '203.0.113.99', + 'Forwarded' => 'for=198.51.100.77', + ])->get('/'); + + // WHEN + $resolvedIp = request()->ip(); + + // THEN + $response->assertStatus(200); + expect($resolvedIp)->toBe('203.0.113.99'); + }); +}); diff --git a/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php b/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php index b7f974c5..2b6698ae 100644 --- a/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php +++ b/tests/Feature/App/Http/Requests/Basket/AddBasketRequestTest.php @@ -2,31 +2,60 @@ 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; +use App\Services\ActionExecutorService; +use App\Services\ProductDtoAssemblerService; 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\Support\Facades\Gate; use Illuminate\Support\Facades\Validator; +use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; +use Infrastructure\Adapters\Repositories\EloquentProductRepository; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Psr\Log\NullLogger; +use Shared\Concurrency\Lock; +use Shared\Helpers\UuidHelper; + +function makeAddBasketRequest(): AddBasketRequest +{ + $executor = new ActionExecutorService( + lock: \Mockery::mock(Lock::class), + logger: new NullLogger(), + eventDispatcher: new LaravelDomainEventDispatcher(), + ); + $query = new GetProductWithPricingQuery( + new ProductDtoAssemblerService(new EloquentProductRepository()), + ); + + return new AddBasketRequest($executor, $query); +} describe('AddBasketRequest', function () { it('authorizes when product exists and gate allows', function () { // GIVEN - $range = Range::first() ?? Range::forceCreate(['name' => 'Test', 'slug' => 'test', 'order' => 1, 'picture_alt' => '', 'picture_title' => '']); - $product = Product::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + $range = Range::query()->first() ?? Range::query()->forceCreate([ + 'name' => 'Test', + 'slug' => 'test', + 'order' => 1, + 'picture_alt' => '', + 'picture_title' => '', + ]); + $product = Product::query()->forceCreate([ + '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, resolve(Currency::class)), + 'price' => new Money(100, new Currency('EUR')), 'invoicing_unit' => InvoicingUnit::cases()[0]->value, 'tax_rate' => TaxRate::cases()[0]->value, 'stock' => 10, @@ -42,10 +71,10 @@ describe('AddBasketRequest', function () { ]); Gate::shouldReceive('allows') - ->with('addToBasket', \Mockery::on(fn ($p) => $p->id === $product->id)) + ->with('addToBasket', \Mockery::on(fn (mixed $p): bool => $p instanceof ProductWithPricingDto && $p->product->id === $product->id)) ->andReturn(true); - $request = new AddBasketRequest(); + $request = makeAddBasketRequest(); $request->initialize(); // WHEN @@ -57,11 +86,11 @@ describe('AddBasketRequest', function () { it('does not authorize when product does not exist', function () { // GIVEN - $request = new AddBasketRequest(); + $request = makeAddBasketRequest(); $request->initialize(); // WHEN - $request->merge(['rowId' => Uuid::uuid7()->toString()]); + $request->merge(['rowId' => UuidHelper::v7()->toString()]); // THEN expect($request->authorize())->toBeFalse(); @@ -69,14 +98,20 @@ describe('AddBasketRequest', function () { it('does not authorize when gate denies', function () { // GIVEN - $range = Range::first() ?? Range::forceCreate(['name' => 'Test', 'slug' => 'test', 'order' => 1, 'picture_alt' => '', 'picture_title' => '']); - $product = Product::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + $range = Range::query()->first() ?? Range::query()->forceCreate([ + 'name' => 'Test', + 'slug' => 'test', + 'order' => 1, + 'picture_alt' => '', + 'picture_title' => '', + ]); + $product = Product::query()->forceCreate([ + '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, resolve(Currency::class)), + 'price' => new Money(100, new Currency('EUR')), 'invoicing_unit' => InvoicingUnit::cases()[0]->value, 'tax_rate' => TaxRate::cases()[0]->value, 'stock' => 10, @@ -95,7 +130,7 @@ describe('AddBasketRequest', function () { ->with('addToBasket', \Mockery::any()) ->andReturn(false); - $request = new AddBasketRequest(); + $request = makeAddBasketRequest(); $request->initialize(); // WHEN @@ -107,14 +142,20 @@ describe('AddBasketRequest', function () { it('validates correct rules', function () { // GIVEN - $range = Range::first() ?? Range::forceCreate(['name' => 'Test', 'slug' => 'test', 'order' => 1, 'picture_alt' => '', 'picture_title' => '']); - $product = Product::forceCreate([ - 'id' => Uuid::uuid7()->toString(), + $range = Range::query()->first() ?? Range::query()->forceCreate([ + 'name' => 'Test', + 'slug' => 'test', + 'order' => 1, + 'picture_alt' => '', + 'picture_title' => '', + ]); + $product = Product::query()->forceCreate([ + '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, resolve(Currency::class)), + 'price' => new Money(100, new Currency('EUR')), 'invoicing_unit' => InvoicingUnit::cases()[0]->value, 'tax_rate' => TaxRate::cases()[0]->value, 'stock' => 10, @@ -129,7 +170,7 @@ describe('AddBasketRequest', function () { 'range_id' => $range->id, ]); - $request = new AddBasketRequest(); + $request = makeAddBasketRequest(); $request->initialize(); $request->merge([ 'rowId' => $product->id, @@ -145,7 +186,7 @@ describe('AddBasketRequest', function () { it('fails validation on incorrect rules', function () { // GIVEN - $request = new AddBasketRequest(); + $request = makeAddBasketRequest(); $request->initialize(); $request->merge([ 'rowId' => 'not-a-uuid', @@ -162,8 +203,8 @@ describe('AddBasketRequest', function () { it('can get product id as value object', function () { // GIVEN - $uuid = Uuid::uuid7()->toString(); - $request = new AddBasketRequest(); + $uuid = UuidHelper::v7()->toString(); + $request = makeAddBasketRequest(); $request->initialize(); $request->merge(['rowId' => $uuid]); @@ -171,7 +212,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 21a9afd2..816a818b 100644 --- a/tests/Feature/App/Http/Requests/Basket/RemoveBasketRequestTest.php +++ b/tests/Feature/App/Http/Requests/Basket/RemoveBasketRequestTest.php @@ -2,10 +2,11 @@ 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; +use Shared\Helpers\UuidHelper; describe('RemoveBasketRequest', function () { it('authorizes always', function () { @@ -24,7 +25,7 @@ describe('RemoveBasketRequest', function () { $request = new RemoveBasketRequest(); $request->initialize(); $request->merge([ - 'rowId' => Uuid::uuid7()->toString(), + 'rowId' => UuidHelper::v7()->toString(), 'qty' => 1, ]); @@ -54,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]); @@ -63,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 34dcc54c..e2fb37d3 100644 --- a/tests/Feature/App/Http/Requests/Bo/Dashboard/DashboardRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Dashboard/DashboardRequestTest.php @@ -2,73 +2,66 @@ declare(strict_types=1); -use App\Cqs\Queries\Dashboard\GetBoDashboardQueryInput; +namespace Tests\Feature\App\Http\Requests\Bo\Dashboard; + 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', @@ -79,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 d2380260..eaf8218f 100644 --- a/tests/Feature/App/Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php @@ -2,185 +2,157 @@ 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); + $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); - $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); - $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); - $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); - $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); - $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); - $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); - $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); - $request = new StoreDiscountRequest($authService); - $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', - ]); + $authService = \Mockery::mock(AppAdminAuthService::class); + $request = new StoreDiscountRequest($authService, new Currency('EUR')); + $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 f4ca5fc1..8d427d44 100644 --- a/tests/Feature/App/Http/Requests/Bo/Faqs/StoreFaqRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Faqs/StoreFaqRequestTest.php @@ -2,123 +2,67 @@ 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; -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 e64bd930..506383e5 100644 --- a/tests/Feature/App/Http/Requests/Bo/MassActionRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/MassActionRequestTest.php @@ -2,94 +2,65 @@ declare(strict_types=1); -use App\Cqs\Actions\Common\ExecuteMassActionInput; +namespace Tests\Feature\App\Http\Requests\Bo; + 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 3caa969c..f3137956 100644 --- a/tests/Feature/App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Orders/IndexOrdersRequestTest.php @@ -2,182 +2,145 @@ declare(strict_types=1); -use App\Cqs\Queries\Orders\GetBoPaginatedOrdersQueryInput; +namespace Tests\Feature\App\Http\Requests\Bo\Orders; + 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); + $legacyNumeric = Validator::make([ + 'status' => '1', + ], $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($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); $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', - 'status' => (string) OrderStatus::VALIDATED->value, + 'status' => OrderStatus::VALIDATED->value, ]); // WHEN $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 a24a8f98..a82ca8f4 100644 --- a/tests/Feature/App/Http/Requests/Bo/Pages/UpdatePageRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Pages/UpdatePageRequestTest.php @@ -2,49 +2,77 @@ 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 b031d2d0..f5670370 100644 --- a/tests/Feature/App/Http/Requests/Bo/PickupExceptions/StorePickupExceptionRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/PickupExceptions/StorePickupExceptionRequestTest.php @@ -2,110 +2,102 @@ 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/Products/IndexProductRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php index 30325936..4f027f96 100644 --- a/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php @@ -2,84 +2,86 @@ 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 bf6179c4..ddb0fa43 100644 --- a/tests/Feature/App/Http/Requests/Bo/Products/StoreProductRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Products/StoreProductRequestTest.php @@ -2,76 +2,166 @@ declare(strict_types=1); +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); - $request = new StoreProductRequest($authService); - - // WHEN + $authService = \Mockery::mock(AppAdminAuthService::class); + $authService->shouldReceive('check')->twice()->andReturn(true, false); + $request = new StoreProductRequest($authService, new Currency('EUR')); $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('builds Money price using the injected currency', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreProductRequest($authService); + $authService = \Mockery::mock(AppAdminAuthService::class); + $request = new StoreProductRequest($authService, new Currency('USD')); + $request->initialize(); + $request->merge(['price' => 1250]); // WHEN - $request->initialize(); + $price = $request->getPrice(); // THEN - expect($request->rules())->toBeArray(); + expect($price->getAmount())->toBe('1250') + ->and($price->getCurrency()->getCode())->toBe('USD'); }); - it('returns attributes', 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); + $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(), + originalName: 'product.jpeg', + mimeType: 'image/png', + error: UPLOAD_ERR_OK, + test: true, + ); + $disallowedLarge = UploadedFile::fake()->image( + 'large.webp', + StoreProductRequest::PICTURE_LARGE_WIDTH, + StoreProductRequest::PICTURE_LARGE_HEIGHT, + ); // WHEN - $request->initialize(); + $smallValidator = Validator::make(['picture' => $mismatchedSmall], ['picture' => $rules['picture']]); + $largeValidator = Validator::make(['picture_large' => $disallowedLarge], ['picture_large' => $rules['picture_large']]); // THEN - expect($request->attributes())->toBeArray(); + expect($smallValidator->errors()->has('picture'))->toBeTrue() + ->and($largeValidator->errors()->has('picture_large'))->toBeTrue(); }); - it('prepares for validation', 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); - $request->initialize(); - $method = new \ReflectionMethod($request, 'prepareForValidation'); - $method->setAccessible(true); + $authService = \Mockery::mock(AppAdminAuthService::class); + $rules = new StoreProductRequest($authService, new Currency('EUR'))->rules(); // WHEN - $method->invoke($request); + $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), + '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(true)->toBeTrue(); // just making sure it runs without exception + 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('passes validation', function () { + it('maps request data into CreateProductInput and filters non-scalar associated products', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new StoreProductRequest($authService); - $request->initialize(); - $method = new \ReflectionMethod($request, 'passedValidation'); - $method->setAccessible(true); + $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 - $method->invoke($request); + $input = $request->toCreateProductInput(); // THEN - expect(true)->toBeTrue(); + 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 3792430e..c6c04790 100644 --- a/tests/Feature/App/Http/Requests/Bo/Ranges/StoreRangeRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Ranges/StoreRangeRequestTest.php @@ -2,61 +2,103 @@ declare(strict_types=1); +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); + $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(), + originalName: 'range.jpeg', + mimeType: 'image/png', + error: UPLOAD_ERR_OK, + test: true, + ); + $disallowedWebp = UploadedFile::fake()->image('range.webp', StoreRangeRequest::PICTURE_WIDTH, StoreRangeRequest::PICTURE_HEIGHT); // WHEN - $request->initialize(); + $mismatchValidator = Validator::make(['picture' => $mismatched], ['picture' => $rules['picture']]); + $webpValidator = Validator::make(['picture' => $disallowedWebp], ['picture' => $rules['picture']]); // THEN - expect($request->attributes())->toBeArray(); + expect($mismatchValidator->errors()->has('picture'))->toBeTrue() + ->and($webpValidator->errors()->has('picture'))->toBeTrue(); }); - it('prepares for validation', function () { + it('maps request data into CreateRangeInput with PictureMetadata', function (): void { // GIVEN - $authService = mock(AppAdminAuthService::class); + $authService = \Mockery::mock(AppAdminAuthService::class); $request = new StoreRangeRequest($authService); - $request->initialize(); - $method = new \ReflectionMethod($request, 'prepareForValidation'); - $method->setAccessible(true); + $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 - $method->invoke($request); + $input = $request->toCreateRangeInput(); // THEN - expect(true)->toBeTrue(); // just making sure it runs without exception + 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/Shops/IndexShopRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php index ba7eeeaa..317f48d0 100644 --- a/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Shops/IndexShopRequestTest.php @@ -2,153 +2,104 @@ 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 Shared\Helpers\UuidHelper; -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' => UuidHelper::v7()->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 = UuidHelper::v7()->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 = UuidHelper::v7()->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, UuidHelper::v4()->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 84ec3a4f..7bfe86dd 100644 --- a/tests/Feature/App/Http/Requests/Bo/Shops/StoreShopRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Shops/StoreShopRequestTest.php @@ -2,90 +2,116 @@ 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 e932daa8..d59ddaf3 100644 --- a/tests/Feature/App/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequestTest.php @@ -2,64 +2,37 @@ 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; 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 = [ @@ -82,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 = [ @@ -101,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 = [ @@ -120,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 = [ @@ -147,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 = [ @@ -174,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 = [ @@ -201,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(); diff --git a/tests/Feature/App/Http/Requests/Bo/Slides/StoreSlideRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Slides/StoreSlideRequestTest.php index 1426013b..c821435e 100644 --- a/tests/Feature/App/Http/Requests/Bo/Slides/StoreSlideRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Slides/StoreSlideRequestTest.php @@ -2,102 +2,86 @@ 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', @@ -108,10 +92,145 @@ 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 (): void { + // GIVEN + $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::make( + [ + 'title' => 'Slide Title', + 'picture' => $picture, + 'picture_alt' => 'Alt text', + 'picture_title' => 'Title text', + 'text' => null, + 'link_new_tab' => false, + 'connected' => false, + 'client_timezone' => 'Europe/Paris', + ], + $rules, + ); + + // THEN + expect($validator->fails())->toBeFalse(); + }); + + it('rejects a slide image when extension and mime type do not match or are disallowed', function (): void { + // GIVEN + $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(), + originalName: 'slide.jpeg', + mimeType: 'image/png', + error: UPLOAD_ERR_OK, + test: true, + ); + $disallowedWebp = UploadedFile::fake()->image('slide.webp', StoreSlideRequest::PICTURE_WIDTH, StoreSlideRequest::PICTURE_HEIGHT); + + // WHEN + $mismatchValidator = Validator::make( + [ + 'title' => 'Slide Title', + 'picture' => $mismatched, + 'picture_alt' => 'Alt text', + 'picture_title' => 'Title text', + 'text' => null, + 'link_new_tab' => false, + 'connected' => false, + 'client_timezone' => 'Europe/Paris', + ], + $rules, + ); + $webpValidator = Validator::make( + [ + 'title' => 'Slide Title', + 'picture' => $disallowedWebp, + 'picture_alt' => 'Alt text', + 'picture_title' => 'Title text', + 'text' => null, + 'link_new_tab' => false, + 'connected' => false, + 'client_timezone' => 'Europe/Paris', + ], + $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 33dd80b1..8bdb9a37 100644 --- a/tests/Feature/App/Http/Requests/Bo/Tags/StoreTagRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Tags/StoreTagRequestTest.php @@ -2,61 +2,64 @@ 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(); }); }); diff --git a/tests/Feature/App/Http/Requests/Fo/Ajax/FilterProductsRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Ajax/FilterProductsRequestTest.php index f6664acb..9a4ab204 100644 --- a/tests/Feature/App/Http/Requests/Fo/Ajax/FilterProductsRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Ajax/FilterProductsRequestTest.php @@ -2,115 +2,78 @@ declare(strict_types=1); +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 c7433c30..193b1083 100644 --- a/tests/Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Auth/RegisterRequestTest.php @@ -2,136 +2,233 @@ declare(strict_types=1); -use App\Cqs\Actions\Customers\RegisterCustomerInput; +namespace Tests\Feature\App\Http\Requests\Fo\Auth; + use App\Http\Requests\Fo\Auth\RegisterRequest; +use App\Models\Customer; +use App\Models\Employee; +use Domain\Models\ValueObjects\Code; +use Domain\Models\ValueObjects\Email; +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 Shared\Helpers\UuidHelper; +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); + it('rejects matricule and code when employee already has a customer_id', function (): void { // GIVEN - $request = new RegisterRequest($authService); + $customer = new Customer(['email' => new Email('existing@example.com')]); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); + $customer->saveOrFail(); + + $employee = new Employee(); + $employee->matricule = new Matricule('1234567'); + $employee->code = new Code('ABCDEF'); + $employee->nom = 'Doe'; + $employee->prenom = 'John'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('1'); + $employee->customer()->associate($customer); + $employee->saveOrFail(); + + $authService = \Mockery::mock(AppCustomerAuthService::class); + $request = new RegisterRequest($authService); + $request->initialize( + request: [ + 'matricule' => '1234567', + 'code' => 'ABCDEF', + ], + server: ['REQUEST_METHOD' => 'POST'], + ); // WHEN - $request->initialize(); + $validator = Validator::make( + ['matricule' => '1234567', 'code' => 'ABCDEF'], + [ + 'matricule' => $request->rules()['matricule'], + 'code' => $request->rules()['code'], + ], + ); // THEN - expect($request->attributes())->toBeArray() - ->and($request->attributes())->toHaveKeys([ - 'firstname', - 'lastname', - 'birth_date', - 'address', - 'phone', - 'city', - 'postcode', - 'password', - 'matricule', - 'code', - 'ok_cgv', - 'optin', - ]); + expect($validator->fails())->toBeTrue() + ->and($validator->errors()->has('matricule'))->toBeTrue() + ->and($validator->errors()->has('code'))->toBeTrue(); + }); + + it('accepts matricule and code when employee has no customer_id', function (): void { + // GIVEN + $employee = new Employee(); + $employee->matricule = new Matricule('7654321'); + $employee->code = new Code('FGHJKM'); + $employee->nom = 'Doe'; + $employee->prenom = 'Jane'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('1'); + $employee->saveOrFail(); + + $authService = \Mockery::mock(AppCustomerAuthService::class); + $request = new RegisterRequest($authService); + $request->initialize( + request: [ + 'matricule' => '7654321', + 'code' => 'FGHJKM', + ], + server: ['REQUEST_METHOD' => 'POST'], + ); + + // WHEN + $validator = Validator::make( + ['matricule' => '7654321', 'code' => 'FGHJKM'], + [ + 'matricule' => $request->rules()['matricule'], + 'code' => $request->rules()['code'], + ], + ); + + // THEN + expect($validator->passes())->toBeTrue(); + }); + + it('rejects invalid matricule and code format in validation rules', function (): void { + // GIVEN + $authService = \Mockery::mock(AppCustomerAuthService::class); + $request = new RegisterRequest($authService); + $request->initialize(); + + // WHEN + $validator = Validator::make( + ['matricule' => 'not-digits', 'code' => '0OIl!'], + [ + 'matricule' => $request->rules()['matricule'], + 'code' => $request->rules()['code'], + ], + ); + + // THEN + expect($validator->fails())->toBeTrue() + ->and($validator->errors()->has('matricule'))->toBeTrue() + ->and($validator->errors()->has('code'))->toBeTrue(); + }); + + it('rejects matricule and code when employee is inactive due to end_date or future start_date', function (): void { + // GIVEN + Date::setTestNow(Date::parse('2026-06-15 10:00:00', 'Europe/Paris')); + + try { + $endedEmployee = new Employee(); + $endedEmployee->matricule = new Matricule('7654322'); + $endedEmployee->code = new Code('FGHJK2'); + $endedEmployee->nom = 'Doe'; + $endedEmployee->prenom = 'Ended'; + $endedEmployee->end_date = Carbon::parse('2026-06-15'); + $endedEmployee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $endedEmployee->site = new ShopperSiteCode('SITE'); + $endedEmployee->service = new ShopperServiceCode('1'); + $endedEmployee->saveOrFail(); + + $futureEmployee = new Employee(); + $futureEmployee->matricule = new Matricule('7654323'); + $futureEmployee->code = new Code('FGHJK3'); + $futureEmployee->nom = 'Doe'; + $futureEmployee->prenom = 'Future'; + $futureEmployee->start_date = Carbon::parse('2026-06-16'); + $futureEmployee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $futureEmployee->site = new ShopperSiteCode('SITE'); + $futureEmployee->service = new ShopperServiceCode('1'); + $futureEmployee->saveOrFail(); + + $authService = \Mockery::mock(AppCustomerAuthService::class); + $request = new RegisterRequest($authService); + $request->initialize(); + + // WHEN + $endedValidator = Validator::make( + ['matricule' => '7654322', 'code' => 'FGHJK2'], + ['matricule' => $request->rules()['matricule'], 'code' => $request->rules()['code']], + ); + $futureValidator = Validator::make( + ['matricule' => '7654323', 'code' => 'FGHJK3'], + ['matricule' => $request->rules()['matricule'], 'code' => $request->rules()['code']], + ); + + // THEN + expect($endedValidator->fails())->toBeTrue() + ->and($endedValidator->errors()->has('matricule'))->toBeTrue() + ->and($endedValidator->errors()->has('code'))->toBeTrue() + ->and($futureValidator->fails())->toBeTrue() + ->and($futureValidator->errors()->has('matricule'))->toBeTrue() + ->and($futureValidator->errors()->has('code'))->toBeTrue(); + } finally { + Date::setTestNow(); + } }); }); diff --git a/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php b/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php index 5f4dec67..012cb60b 100644 --- a/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/ContactFormRequestTest.php @@ -2,10 +2,14 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Requests\Fo; + use App\Http\Requests\Fo\ContactFormRequest; -use Domain\Models\ValueObjects\ContactFormData; +use Domain\Models\ValueObjects\OrderReference; use Illuminate\Http\UploadedFile; +use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; +use Shared\Helpers\UuidHelper; describe('ContactFormRequest', function () { it('validates correct rules', function () { @@ -17,15 +21,16 @@ describe('ContactFormRequest', function () { $request->merge([ 'last_name' => 'Doe', 'first_name' => 'John', - 'email' => 'john.doe@example.com', + 'email' => 'john.doe@gmail.com', 'subject' => 'Help with my order', - 'order_ref' => '123456', + 'order_ref' => (string) new OrderReference(UuidHelper::v7()), 'message' => 'This is a message that is longer than 20 characters.', 'ok_cgv' => true, ]); // THEN - expect(true)->toBeTrue(); + $validator = Validator::make($request->all(), $request->rules(), $request->messages()); + expect($validator->passes())->toBeTrue(); }); it('fails validation on incorrect rules', function () { @@ -67,7 +72,7 @@ describe('ContactFormRequest', function () { $request->merge([ 'last_name' => 'Doe', 'first_name' => 'John', - 'email' => 'john.doe@example.com', + 'email' => 'john.doe@gmail.com', 'subject' => 'Help with my order', 'message' => 'This is a message that is longer than 20 characters.', 'ok_cgv' => true, @@ -77,37 +82,69 @@ describe('ContactFormRequest', function () { $request->files->set('file', $file); // THEN - expect(true)->toBeTrue(); + $validator = Validator::make($request->all(), $request->rules(), $request->messages()); + expect($validator->passes())->toBeTrue(); }); - it('converts to value object without file', function () { + it('rejects contact attachment when extension and mime type do not match', function () { // GIVEN + $pngSource = UploadedFile::fake()->image('cropped.png', 100, 100); + $mismatched = new UploadedFile( + path: $pngSource->getRealPath(), + originalName: 'attachment.pdf', + mimeType: 'image/png', + error: UPLOAD_ERR_OK, + test: true, + ); $request = new ContactFormRequest(); $request->initialize(); + + // WHEN + $validator = Validator::make(['file' => $mismatched], ['file' => $request->rules()['file']], $request->messages()); + + // THEN + expect($validator->errors()->has('file'))->toBeTrue(); + }); + + it('converts to action input without file', function () { + // GIVEN + $orderRef = new OrderReference(UuidHelper::v7()); + $request = new ContactFormRequest(); + $request->initialize(); $request->merge([ 'last_name' => 'Doe', 'first_name' => 'John', - 'email' => 'john.doe@example.com', + 'email' => 'john.doe@gmail.com', 'subject' => 'Help', - 'order_ref' => '123', + 'order_ref' => (string) $orderRef, 'message' => 'This is a message that is longer than 20 characters.', ]); // WHEN - $vo = $request->toValueObject(); + $input = $request->toSubmitContactFormInput(); // THEN - expect($vo)->toBeInstanceOf(ContactFormData::class) - ->and($vo->lastName)->toBe('Doe') - ->and($vo->firstName)->toBe('John') - ->and($vo->email)->toBe('john.doe@example.com') - ->and($vo->subject)->toBe('Help') - ->and($vo->orderRef)->toBe('123') - ->and($vo->message)->toBe('This is a message that is longer than 20 characters.') - ->and($vo->file)->toBeNull(); + expect($input->lastName)->toBe('Doe') + ->and($input->firstName)->toBe('John') + ->and($input->email)->toBe('john.doe@gmail.com') + ->and($input->subject)->toBe('Help') + ->and($input->orderRef?->value->toString())->toBe($orderRef->value->toString()) + ->and($input->message)->toBe('This is a message that is longer than 20 characters.') + ->and($input->file)->toBeNull(); }); - it('converts to value object with file', function () { + it('keeps a configured s3 private disk for emailed attachments', function () { + // GIVEN + expect(config('filesystems.disks.s3-private'))->not->toBeNull(); + + // WHEN + $disk = Storage::disk('s3-private'); + + // THEN + expect($disk->getConfig())->toHaveKey('driver', 's3'); + }); + + it('converts to action input with file', function () { // GIVEN $file = UploadedFile::fake()->create('document.pdf', 100, 'application/pdf'); @@ -116,35 +153,16 @@ describe('ContactFormRequest', function () { $request->merge([ 'last_name' => 'Doe', 'first_name' => 'John', - 'email' => 'john.doe@example.com', + 'email' => 'john.doe@gmail.com', 'subject' => 'Help', 'message' => 'This is a message that is longer than 20 characters.', ]); $request->files->set('file', $file); // WHEN - $vo = $request->toValueObject(); + $input = $request->toSubmitContactFormInput(); // THEN - expect($vo)->toBeInstanceOf(ContactFormData::class) - ->and($vo->file)->not->toBeNull() - ->and($vo->file->originalName)->toBe('document.pdf') - ->and($vo->file->mimeType)->toBe('application/pdf'); - }); - - 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 4c8ccaea..64e1bb19 100644 --- a/tests/Feature/App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php @@ -2,79 +2,101 @@ declare(strict_types=1); -use App\Cqs\Actions\Crm\UpdateCustomerInput; +namespace Tests\Feature\App\Http\Requests\Fo\Customer; + 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') @@ -82,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 98999b2f..52e9c21b 100644 --- a/tests/Feature/App/Http/Requests/Fo/Customer/UpdatePasswordRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Customer/UpdatePasswordRequestTest.php @@ -2,48 +2,73 @@ 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 462d09fb..8851cc76 100644 --- a/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Orders/ConfirmOrderRequestTest.php @@ -2,60 +2,54 @@ declare(strict_types=1); -use App\Cqs\Actions\Orders\FinalizeOrderInput; +namespace Tests\Feature\App\Http\Requests\Fo\Orders; + 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; +use Shared\Helpers\UuidHelper; -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 FinalizeOrderInput', function () { - // GIVEN - $shopperId = new ShopperId(Uuid::uuid7()); - $customer = \Mockery::mock(Customer::class); - $customer->shouldReceive('getId')->once()->andReturn($shopperId); + $shopperId = new ShopperId(UuidHelper::v7()); + $customer = new Customer(); + $customer->id = $shopperId->value->toString(); $authService = \Mockery::mock(AppCustomerAuthService::class); $authService->shouldReceive('getCustomerAsMandatory')->once()->andReturn($customer); @@ -64,10 +58,9 @@ describe('ConfirmOrderRequest', function () { $request->initialize(); // WHEN - $input = $request->toFinalizeOrderInput(); + $input = $request->toPlacePendingOrderInput(); // THEN - expect($input)->toBeInstanceOf(FinalizeOrderInput::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 883a70b9..9fa17dfa 100644 --- a/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php @@ -2,10 +2,13 @@ declare(strict_types=1); -use App\Cqs\Actions\Orders\ApplyPickTimeSlotInput; +namespace Tests\Feature\App\Http\Requests\Fo\Orders; + 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; use Domain\Models\Entities\Basket; use Domain\Models\Entities\Shopper; @@ -17,137 +20,86 @@ use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Ports\Repositories\ShopperRepository; -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; 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(BasketService::class), \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(BasketService::class), - \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( $authService, - \Mockery::mock(BasketService::class), \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(BasketService::class), \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(BasketService::class), - \Mockery::mock(ShopperRepository::class), - \Mockery::mock(OrderTunnelService::class), - ); + $shopperId = new ShopperId(UuidHelper::v7()); + $customer = new Customer(); + $customer->id = $shopperId->value->toString(); - // 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(BasketService::class), - \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); - - $basket = new Basket(new BasketId(Uuid::uuid7()), []); + $basket = new Basket(new BasketId(UuidHelper::v7()), []); $shopper = new Shopper( $shopperId, new Email('shopper@example.com'), new Matricule('1234567'), 'Nom', 'Prenom', - now(), + CarbonImmutable::parse('2023-10-01 10:00:00'), null, new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), @@ -157,71 +109,79 @@ describe('PickTimeSlotRequest', function () { $authService = \Mockery::mock(AppCustomerAuthService::class); $authService->shouldReceive('getCustomerAsMandatory')->once()->andReturn($customer); - $basketService = \Mockery::mock(BasketService::class); - $basketService->shouldReceive('getBasket')->once()->andReturn($basket); + $builder = \Mockery::mock(OrderBuilderWithBasket::class); + $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()); $request = new PickTimeSlotRequest( $authService, - $basketService, $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(UuidHelper::v7()); + $customer = new Customer(); + $customer->id = $shopperId->value->toString(); $authService = \Mockery::mock(AppCustomerAuthService::class); $authService->shouldReceive('getCustomerAsMandatory')->once()->andReturn($customer); $request = new PickTimeSlotRequest( $authService, - \Mockery::mock(BasketService::class), \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 9fa35826..1d6e842d 100644 --- a/tests/Feature/App/Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Orders/ValidateSummaryRequestTest.php @@ -2,7 +2,8 @@ declare(strict_types=1); -use App\Cqs\Actions\Orders\InitializeOrderTunnelInput; +namespace Tests\Feature\App\Http\Requests\Fo\Orders; + use App\Http\Requests\Fo\Orders\ValidateSummaryRequest; use App\Models\Customer; use Domain\Exceptions\OrderTunnel\OrderLimitExceededException; @@ -11,49 +12,35 @@ 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; +use Shared\Helpers\UuidHelper; -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()), []); + $basket = new Basket(new BasketId(UuidHelper::v7()), []); $authService = \Mockery::mock(AppCustomerAuthService::class); $basketService = \Mockery::mock(BasketService::class); @@ -72,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(UuidHelper::v7()); + $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(UuidHelper::v7()), []); + $authService = \Mockery::mock(AppCustomerAuthService::class); $authService->shouldReceive('getCustomerAsMandatory')->once()->andReturn($customer); $basketService = \Mockery::mock(BasketService::class); @@ -110,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 38a9c610..1504aaef 100644 --- a/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php @@ -2,10 +2,11 @@ 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; -use Shared\ValueObjects\CrmHashcode; +use Shared\Helpers\UuidHelper; describe('UnsubscribeNewsletterRequest', function () { it('validates correct rules', function () { @@ -13,7 +14,7 @@ describe('UnsubscribeNewsletterRequest', function () { $request = new UnsubscribeNewsletterRequest(); $request->initialize(); $request->merge([ - 'hashcode' => Uuid::uuid4()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), ]); // WHEN @@ -57,7 +58,7 @@ describe('UnsubscribeNewsletterRequest', function () { // GIVEN $request = new UnsubscribeNewsletterRequest(); $request->initialize(); - $uuid = Uuid::uuid4(); + $uuid = UuidHelper::v4(); $request->merge([ 'hashcode' => $uuid->toString(), ]); @@ -66,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/Feature/App/Jobs/DeleteOldResetTokensTest.php b/tests/Feature/App/Jobs/DeleteOldResetTokensTest.php new file mode 100644 index 00000000..aaffb1d3 --- /dev/null +++ b/tests/Feature/App/Jobs/DeleteOldResetTokensTest.php @@ -0,0 +1,35 @@ +insert([ + [ + 'email' => 'expired@example.com', + 'token' => 'expired-token', + 'created_at' => Date::now()->subDays(8), + ], + [ + 'email' => 'fresh@example.com', + 'token' => 'fresh-token', + 'created_at' => Date::now()->subDay(), + ], + ]); + + // WHEN + DeleteOldResetTokens::dispatchSync(); + + // THEN + expect(PasswordReset::query()->where('email', 'expired@example.com')->exists())->toBeFalse() + ->and(PasswordReset::query()->where('email', 'fresh@example.com')->exists())->toBeTrue(); + + Date::setTestNow(); +}); diff --git a/tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php b/tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php new file mode 100644 index 00000000..22ed28d3 --- /dev/null +++ b/tests/Feature/App/Jobs/EnsurePublicHolidaysSyncedJobTest.php @@ -0,0 +1,77 @@ +create(); + + Http::fake([ + 'https://calendrier.api.gouv.fr/jours-feries/metropole/2026.json' => Http::response([ + '2026-01-01' => '1er janvier', + '2026-12-25' => 'Jour de Noël', + ], 200), + ]); + + // WHEN + EnsurePublicHolidaysSyncedJob::dispatchSync(); + + // THEN + Http::assertSentCount(1); + expect(PickupException::query()->whereYear('date', 2026)->count())->toBe(2) + ->and(PickupException::query()->whereYear('date', 2027)->count())->toBe(0) + ->and($shop->pickupExceptions()->count())->toBe(2); + + // WHEN (second run) + Http::fake(); + EnsurePublicHolidaysSyncedJob::dispatchSync(); + + // THEN + Http::assertNothingSent(); +}); + +it('catches up missing current and next year holidays on or after november and skips subsequent runs', function (): void { + // GIVEN + Date::setTestNow('2026-11-05 07:30:00'); + $shop = Shop::factory()->create(); + + Http::fake([ + 'https://calendrier.api.gouv.fr/jours-feries/metropole/2026.json' => Http::response([ + '2026-11-11' => 'Armistice', + '2026-12-25' => 'Jour de Noël', + ], 200), + 'https://calendrier.api.gouv.fr/jours-feries/metropole/2027.json' => Http::response([ + '2027-11-11' => 'Armistice', + '2027-12-25' => 'Jour de Noël', + ], 200), + ]); + + // WHEN + EnsurePublicHolidaysSyncedJob::dispatchSync(); + + // THEN + Http::assertSentCount(2); + expect(PickupException::query()->whereYear('date', 2026)->count())->toBe(2) + ->and(PickupException::query()->whereYear('date', 2027)->count())->toBe(2) + ->and($shop->pickupExceptions()->count())->toBe(4); + + // WHEN (subsequent run) + Http::fake(); + EnsurePublicHolidaysSyncedJob::dispatchSync(); + + // THEN + Http::assertNothingSent(); +}); 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/Jobs/SendContactMailJobTest.php b/tests/Feature/App/Jobs/SendContactMailJobTest.php new file mode 100644 index 00000000..df7af92f --- /dev/null +++ b/tests/Feature/App/Jobs/SendContactMailJobTest.php @@ -0,0 +1,208 @@ +allows('fileExistsOnDisk')->andReturn(true); + + // WHEN + $job->handle($mailer, $storageService, $privateS3Disk); + + // THEN + 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 { + // GIVEN + Mail::fake(); + /** @var Mailer $mailer */ + $mailer = Mail::getFacadeRoot(); + + $data = new ContactFormData( + lastName: 'Dupont', + firstName: 'Jean', + 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: new AttachedFile( + path: 'contact-attachments/missing.pdf', + originalName: 'missing.pdf', + mimeType: 'application/pdf', + ), + ); + + $job = new SendContactMailJob($data, 'contact@example.com'); + $privateS3Disk = new PrivateS3Disk(); + + /** @var StorageService&\Mockery\MockInterface $storageService */ + $storageService = \Mockery::spy(StorageService::class); + $storageService->allows('fileExistsOnDisk')->andReturn(false); + + // WHEN + $job->handle($mailer, $storageService, $privateS3Disk); + + // THEN + 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 { + // GIVEN + Mail::fake(); + /** @var Mailer $mailer */ + $mailer = Mail::getFacadeRoot(); + + $data = new ContactFormData( + lastName: 'Dupont', + firstName: 'Jean', + email: 'jean.dupont@gmail.com', + subject: 'Question sans PJ', + message: 'Bonjour, ceci est un message de test qui contient au moins vingt caractères.', + ); + + $job = new SendContactMailJob($data, 'contact@example.com'); + $privateS3Disk = new PrivateS3Disk(); + + /** @var StorageService&\Mockery\MockInterface $storageService */ + $storageService = \Mockery::spy(StorageService::class); + + // WHEN + $job->handle($mailer, $storageService, $privateS3Disk); + + // THEN + 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 { + // GIVEN + $data = new ContactFormData( + lastName: 'Dupont', + firstName: 'Jean', + 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: new AttachedFile( + path: 'contact-attachments/failed.pdf', + originalName: 'failed.pdf', + mimeType: 'application/pdf', + ), + ); + + $job = new SendContactMailJob($data, 'contact@example.com'); + + /** @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 + $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 { + // GIVEN + $data = new ContactFormData( + lastName: 'Dupont', + firstName: 'Jean', + 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: new AttachedFile( + path: 'contact-attachments/already-deleted.pdf', + originalName: 'already-deleted.pdf', + mimeType: 'application/pdf', + ), + ); + + $job = new SendContactMailJob($data, 'contact@example.com'); + + /** @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 + $storageService->shouldHaveReceived('fileExistsOnDisk')->once(); + $storageService->shouldNotHaveReceived('removeFromDisk'); + }); +}); diff --git a/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php b/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php new file mode 100644 index 00000000..3808c6b2 --- /dev/null +++ b/tests/Feature/App/Jobs/SendMissingOrderReminderJobTest.php @@ -0,0 +1,276 @@ + Friday 2026-11-20 + + Shop::factory()->create(['default' => true]); + + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'email' => new Email('reminder@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + /** @var Employee $employee */ + $employee = Employee::query()->forceCreate([ + 'customer_id' => $customer->id, + 'matricule' => new Matricule('1234567'), + 'nom' => 'Dupont', + 'prenom' => 'Jean', + 'code' => new Code('ABC1234'), + 'etablissement' => new ShopperEstablishmentCode('01'), + 'site' => new ShopperSiteCode('SITE'), + 'service' => new ShopperServiceCode('01'), + 'start_date' => CarbonImmutable::now()->subMonth(), + 'end_date' => CarbonImmutable::now()->addMonth(), + ]); + + $pickupExceptionRepo = \Mockery::mock(PickupExceptionRepository::class); + $pickupExceptionRepo->shouldReceive('getExceptionsForShop')->once()->andReturn([]); + + $schedulingService = new PickupSchedulingService($pickupExceptionRepo); + $shopperService = $this->app->make(ShopperService::class); + $icsGenerator = new IcsGeneratorService('Cocotte Test'); + $cache = new CacheRepository(new ArrayStore()); + + // WHEN + $job = new SendMissingOrderReminderJob(); + $job->handle($schedulingService, $shopperService, $icsGenerator, $cache); + // Second invocation within the same week must be idempotent. + $job->handle($schedulingService, $shopperService, $icsGenerator, $cache); + + // THEN + Notification::assertSentToTimes($employee, MissingOrderReminderNotification::class, 1); + Notification::assertSentTo( + $employee, + MissingOrderReminderNotification::class, + function (MissingOrderReminderNotification $notification) use ($employee): bool { + $mail = $notification->toMail($employee); + + return count($mail->rawAttachments) === 1 + && $mail->rawAttachments[0]['name'] === 'rappel-commande.ics' + && str_contains((string) $mail->rawAttachments[0]['data'], 'BEGIN:VCALENDAR'); + } + ); + + expect($cache->has('missing-order-reminder:2026-W47:' . $employee->id))->toBeTrue(); + + Date::setTestNow(); + }); + + it('skips employees when their shop is closed on pickup day without replacement', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + Notification::fake(); + Config::set('app.url', 'https://cocotte.example.com'); + Config::set('app.name', 'Cocotte Test'); + Date::setTestNow('2026-11-16 08:00:00'); // Monday 8am -> Friday 2026-11-20 + + Shop::factory()->create(['default' => true]); + + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'email' => new Email('closed-shop@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + /** @var Employee $employee */ + $employee = Employee::query()->forceCreate([ + 'customer_id' => $customer->id, + 'matricule' => new Matricule('2234567'), + 'nom' => 'Martin', + 'prenom' => 'Paul', + 'code' => new Code('DEF1234'), + 'etablissement' => new ShopperEstablishmentCode('01'), + 'site' => new ShopperSiteCode('SITE'), + 'service' => new ShopperServiceCode('01'), + 'start_date' => CarbonImmutable::now()->subMonth(), + 'end_date' => CarbonImmutable::now()->addMonth(), + ]); + + $exception = new PickupExceptionOnDate( + id: new PickupExceptionId(UuidHelper::v7()), + date: CarbonImmutable::parse('2026-11-20', 'Europe/Paris'), + label: 'Fermeture exceptionnelle', + repeatable: false, + repeatFrequency: RepeatFrequency::YEARLY, + autoUpdated: false, + ); + $override = new ShopPickupOverride($exception, replacementDate: null, orderDeadlineAt: null); + + $pickupExceptionRepo = \Mockery::mock(PickupExceptionRepository::class); + $pickupExceptionRepo->shouldReceive('getExceptionsForShop')->once()->andReturn([$override]); + + $schedulingService = new PickupSchedulingService($pickupExceptionRepo); + $shopperService = $this->app->make(ShopperService::class); + $icsGenerator = new IcsGeneratorService('Cocotte Test'); + $cache = new CacheRepository(new ArrayStore()); + + // WHEN + new SendMissingOrderReminderJob()->handle( + $schedulingService, + $shopperService, + $icsGenerator, + $cache, + ); + + // THEN + Notification::assertNothingSent(); + expect($cache->has('missing-order-reminder:2026-W47:' . $employee->id))->toBeFalse(); + + Date::setTestNow(); + }); + + it('uses replacement pickup day and excludes employees who already ordered for replacement date', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + Notification::fake(); + Config::set('app.url', 'https://cocotte.example.com'); + Config::set('app.name', 'Cocotte Test'); + Date::setTestNow('2026-11-16 08:00:00'); // Monday 8am -> Friday 2026-11-20 replaced by Thursday 2026-11-19 + + $shop = Shop::factory()->create(['default' => true]); + + $orderedCustomer = Customer::query()->forceCreate([ + 'email' => new Email('ordered-repl@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + $orderedEmployee = Employee::query()->forceCreate([ + 'customer_id' => $orderedCustomer->id, + 'matricule' => new Matricule('3234567'), + 'nom' => 'Ordered', + 'prenom' => 'Claire', + 'code' => new Code('GHJ2345'), + 'etablissement' => new ShopperEstablishmentCode('01'), + 'site' => new ShopperSiteCode('SITE'), + 'service' => new ShopperServiceCode('01'), + 'start_date' => CarbonImmutable::now()->subMonth(), + 'end_date' => CarbonImmutable::now()->addMonth(), + ]); + + Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(UuidHelper::v7()), + 'status' => OrderStatus::VALIDATED->value, + 'total' => new Money(2500, new Currency('EUR')), + 'employee' => new OrderEmployee( + new Matricule('3234567'), + 'Claire', + 'Ordered', + new ShopperEstablishmentCode('01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('01'), + ), + 'delivery_address' => new DeliveryAddress('Shop', '1 rue Test', '75000', 'Paris'), + 'pickup_day' => '2026-11-19', + ]); + + $missingCustomer = Customer::query()->forceCreate([ + 'email' => new Email('missing-repl@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + $missingEmployee = Employee::query()->forceCreate([ + 'customer_id' => $missingCustomer->id, + 'matricule' => new Matricule('4234567'), + 'nom' => 'Missing', + 'prenom' => 'Luc', + 'code' => new Code('KMN2345'), + 'etablissement' => new ShopperEstablishmentCode('01'), + 'site' => new ShopperSiteCode('SITE'), + 'service' => new ShopperServiceCode('01'), + 'start_date' => CarbonImmutable::now()->subMonth(), + 'end_date' => CarbonImmutable::now()->addMonth(), + ]); + + $exception = new PickupExceptionOnDate( + id: new PickupExceptionId(UuidHelper::v7()), + date: CarbonImmutable::parse('2026-11-20', 'Europe/Paris'), + label: 'Décalage jeudi', + repeatable: false, + repeatFrequency: RepeatFrequency::YEARLY, + autoUpdated: false, + ); + $override = new ShopPickupOverride( + $exception, + replacementDate: CarbonImmutable::parse('2026-11-19', 'Europe/Paris'), + orderDeadlineAt: CarbonImmutable::parse('2026-11-16 16:00:00', 'Europe/Paris'), + ); + + $pickupExceptionRepo = \Mockery::mock(PickupExceptionRepository::class); + $pickupExceptionRepo->shouldReceive('getExceptionsForShop')->once()->andReturn([$override]); + + $schedulingService = new PickupSchedulingService($pickupExceptionRepo); + $shopperService = $this->app->make(ShopperService::class); + $icsGenerator = new IcsGeneratorService('Cocotte Test'); + $cache = new CacheRepository(new ArrayStore()); + + // WHEN + new SendMissingOrderReminderJob()->handle( + $schedulingService, + $shopperService, + $icsGenerator, + $cache, + ); + + // THEN + Notification::assertNotSentTo($orderedEmployee, MissingOrderReminderNotification::class); + Notification::assertSentTo( + $missingEmployee, + MissingOrderReminderNotification::class, + function (MissingOrderReminderNotification $notification) use ($missingEmployee): bool { + $rendered = $notification->toMail($missingEmployee)->render(); + + return str_contains((string) $rendered, '19/11/2026') + && str_contains((string) $rendered, '16h'); + } + ); + + Date::setTestNow(); + }); +}); diff --git a/tests/Feature/App/Jobs/SendReminderMailTest.php b/tests/Feature/App/Jobs/SendReminderMailTest.php new file mode 100644 index 00000000..25cc87ce --- /dev/null +++ b/tests/Feature/App/Jobs/SendReminderMailTest.php @@ -0,0 +1,182 @@ +create(); + $customer = Customer::query()->forceCreate([ + 'email' => new Email('today-reminder@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + $employee = Employee::query()->forceCreate([ + 'customer_id' => $customer->id, + 'matricule' => new Matricule('5234567'), + 'nom' => 'Bernard', + 'prenom' => 'Alice', + 'code' => new Code('MNQ2345'), + 'etablissement' => new ShopperEstablishmentCode('01'), + 'site' => new ShopperSiteCode('SITE'), + 'service' => new ShopperServiceCode('01'), + ]); + + $order = Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(UuidHelper::v7()), + 'status' => OrderStatus::VALIDATED->value, + 'total' => new Money(3000, new Currency('EUR')), + 'employee' => new OrderEmployee( + new Matricule('5234567'), + 'Alice', + 'Bernard', + 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')->once()->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); + + // WHEN + $job->handle($executor, $claimAction, $releaseAction); + // Re-running on same day (e.g. retry or duplicate run) must not notify twice. + $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(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' => UuidHelper::v7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(UuidHelper::v7()), + '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/Feature/App/Jobs/UpdateSlidesStatusTest.php b/tests/Feature/App/Jobs/UpdateSlidesStatusTest.php new file mode 100644 index 00000000..88e6fad3 --- /dev/null +++ b/tests/Feature/App/Jobs/UpdateSlidesStatusTest.php @@ -0,0 +1,34 @@ +addHour(); + $dateEnd = Date::now()->addDay(); + $slide = Slide::factory()->create([ + 'date_start' => $dateStart, + 'date_end' => $dateEnd, + ]); + expect($slide->status)->toBeFalse(); + + Date::setTestNow('2026-11-14 12:00:00'); + + // WHEN + UpdateSlidesStatus::dispatchSync(); + + // THEN + $slide->refresh(); + expect($slide->status)->toBeTrue() + ->and($slide->date_start?->format('Y-m-d H:i:s'))->toBe($dateStart->format('Y-m-d H:i:s')) + ->and($slide->date_end?->format('Y-m-d H:i:s'))->toBe($dateEnd->format('Y-m-d H:i:s')); + + Date::setTestNow(); +}); diff --git a/tests/Feature/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php b/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php similarity index 81% rename from tests/Feature/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php rename to tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php index b934283e..742ba164 100644 --- a/tests/Feature/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php +++ b/tests/Feature/App/Jobs/UpsertShopsPickupExceptionsUsingApiForYearTest.php @@ -2,14 +2,14 @@ declare(strict_types=1); +namespace Tests\Feature\App\Jobs; + 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); +use Webmozart\Assert\Assert; it('throws an exception if the year is before 2026', function (): void { // GIVEN @@ -33,20 +33,24 @@ it('upserts holidays from the api and syncs them to all shops', function (): voi ]); // WHEN - $job = new UpsertShopsPickupExceptionsUsingApiForYear($year); - $job->handle(); + UpsertShopsPickupExceptionsUsingApiForYear::dispatchSync($year); // THEN 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 { @@ -68,8 +72,7 @@ it('updates existing pickup exceptions without creating duplicates', function () ]); // WHEN - $job = new UpsertShopsPickupExceptionsUsingApiForYear($year); - $job->handle(); + UpsertShopsPickupExceptionsUsingApiForYear::dispatchSync($year); // THEN expect(PickupException::query()->count())->toBe(1); diff --git a/tests/Feature/App/Listeners/CustomerPasswordUpdatedListenerTest.php b/tests/Feature/App/Listeners/CustomerPasswordUpdatedListenerTest.php new file mode 100644 index 00000000..4748f61a --- /dev/null +++ b/tests/Feature/App/Listeners/CustomerPasswordUpdatedListenerTest.php @@ -0,0 +1,29 @@ +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..fde7b6ad --- /dev/null +++ b/tests/Feature/App/Listeners/Orders/SendAdminOrderConfirmationTest.php @@ -0,0 +1,89 @@ + 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..40250500 --- /dev/null +++ b/tests/Feature/App/Listeners/Orders/SendCustomerOrderConfirmationTest.php @@ -0,0 +1,100 @@ +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/Feature/App/Listeners/UpdateCustomerLastLoginTest.php b/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php new file mode 100644 index 00000000..54802504 --- /dev/null +++ b/tests/Feature/App/Listeners/UpdateCustomerLastLoginTest.php @@ -0,0 +1,46 @@ +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()); + + // 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'); + + Date::setTestNow(); + }); +}); diff --git a/tests/Feature/App/Providers/AuthServiceProviderTest.php b/tests/Feature/App/Providers/AuthServiceProviderTest.php new file mode 100644 index 00000000..51d39ad9 --- /dev/null +++ b/tests/Feature/App/Providers/AuthServiceProviderTest.php @@ -0,0 +1,66 @@ +forceCreate([ + 'email' => new Email('verify-callback@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + $notification = new VerifyEmail(); + + // 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); + $request = Request::create($relativeUrl, 'GET'); + + // THEN + $expectedHash = hash_hmac('sha256', 'verify-callback@example.com', Config::string('app.key')); + expect($actionUrl)->toContain('/auth/email/verify/' . $customer->id . '/' . $expectedHash) + ->and(URL::hasValidSignature($request, absolute: false))->toBeTrue(); + }); + + it('registers ResetPassword URL callback during boot without instantiating AuthController', function (): void { + // GIVEN + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'email' => new Email('reset-callback@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + $notification = new ResetPassword('secret-reset-token'); + + // 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); + $request = Request::create($relativeUrl, 'GET'); + + // THEN + expect($actionUrl)->toContain('/auth/reinitialiser-mdp/secret-reset-token') + ->and($actionUrl)->toContain('email=reset-callback%40example.com') + ->and(URL::hasValidSignature($request, absolute: false))->toBeTrue(); + }); +}); diff --git a/tests/Feature/App/Providers/DateMacrosTest.php b/tests/Feature/App/Providers/DateMacrosTest.php new file mode 100644 index 00000000..212b35b6 --- /dev/null +++ b/tests/Feature/App/Providers/DateMacrosTest.php @@ -0,0 +1,67 @@ +app->instance('request', Request::create('/', 'GET', ['client_timezone' => 'America/New_York'])); + $utcDate = new \DateTimeImmutable('2026-06-15 14:00:00', new \DateTimeZone('UTC')); + + // WHEN + /** @phpstan-ignore staticMethod.notFound */ + $localInput = Date::toLocalInput($utcDate); + /** @phpstan-ignore staticMethod.notFound */ + $forHumans = Date::forHumans($utcDate); + Assert::string($localInput); + Assert::string($forHumans); + + // THEN + expect($localInput)->toBe('2026-06-15T10:00') + ->and($forHumans)->toContain('10:00'); + }); + + it('falls back to Europe/Paris when client_timezone is invalid or empty', function (string $invalidTimezone): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $this->app->instance('request', Request::create('/', 'GET', ['client_timezone' => $invalidTimezone])); + $utcDate = new \DateTimeImmutable('2026-06-15 14:00:00', new \DateTimeZone('UTC')); + + // WHEN + /** @phpstan-ignore staticMethod.notFound */ + $localInput = Date::toLocalInput($utcDate); + /** @phpstan-ignore staticMethod.notFound */ + $forHumans = Date::forHumans($utcDate); + Assert::string($localInput); + Assert::string($forHumans); + + // THEN + expect($localInput)->toBe('2026-06-15T16:00') + ->and($forHumans)->toContain('16:00'); + })->with([ + 'invalid string' => ['invalid'], + 'empty string' => [''], + ]); + + it('formats calendar dates without shifting day or adding hours in Date::forHumansDate', function (): void { + // GIVEN + app()->instance('request', Request::create('/', 'GET', ['client_timezone' => 'America/New_York'])); + $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)->toContain('08/05/2026') + ->and($formatted)->not->toContain('à'); + }); +}); diff --git a/tests/Feature/Bo/Modules/ChangeOrderBladeTest.php b/tests/Feature/App/Views/ChangeOrderBladeTest.php similarity index 98% rename from tests/Feature/Bo/Modules/ChangeOrderBladeTest.php rename to tests/Feature/App/Views/ChangeOrderBladeTest.php index 0c0a11d1..518b596c 100644 --- a/tests/Feature/Bo/Modules/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; diff --git a/tests/Feature/Bo/Settings/SettingsControllerTest.php b/tests/Feature/Bo/Settings/SettingsControllerTest.php deleted file mode 100644 index 3c9b2fba..00000000 --- a/tests/Feature/Bo/Settings/SettingsControllerTest.php +++ /dev/null @@ -1,82 +0,0 @@ -createOne(); - $route = route('bo.settings.edit'); - - // WHEN - $response = $this->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 */ - // GIVEN - $user = User::factory()->createOne(); - $route = route('bo.settings.update'); - $formData = [ - 'employee_sites' => ['PA', 'LY', 'NA'], - ]; - - // WHEN - $response = $this->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('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'); - $formData = [ - 'employee_sites' => 'PA, LY, NA', - ]; - - // WHEN - $response = $this->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('rejects invalid site code formats', function (): void { - /** @var \Tests\TestCase $this */ - // GIVEN - $user = User::factory()->createOne(); - $route = route('bo.settings.update'); - $formData = [ - 'employee_sites' => ['PA', '123', 'INVALID!'], - ]; - - // WHEN - $response = $this->actingAs($user, 'backend')->put($route, $formData); - - // THEN - $response->assertSessionHasErrors(['employee_sites.1', 'employee_sites.2']); - }); -}); 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/Unit/App/Actions/Ranges/CreateRangeInputTest.php b/tests/Integration/Standalones/App/Cqs/Actions/Ranges/CreateRangeInputTest.php similarity index 98% rename from tests/Unit/App/Actions/Ranges/CreateRangeInputTest.php rename to tests/Integration/Standalones/App/Cqs/Actions/Ranges/CreateRangeInputTest.php index 1bb18171..05a5a31e 100644 --- a/tests/Unit/App/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/Unit/App/Actions/Ranges/UpdateRangeInputTest.php b/tests/Integration/Standalones/App/Cqs/Actions/Ranges/UpdateRangeInputTest.php similarity index 96% rename from tests/Unit/App/Actions/Ranges/UpdateRangeInputTest.php rename to tests/Integration/Standalones/App/Cqs/Actions/Ranges/UpdateRangeInputTest.php index 2ebb21d5..b959034b 100644 --- a/tests/Unit/App/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/Unit/App/Actions/Slides/CreateSlideInputTest.php b/tests/Integration/Standalones/App/Cqs/Actions/Slides/CreateSlideInputTest.php similarity index 89% rename from tests/Unit/App/Actions/Slides/CreateSlideInputTest.php rename to tests/Integration/Standalones/App/Cqs/Actions/Slides/CreateSlideInputTest.php index b52ad42d..bf512c1e 100644 --- a/tests/Unit/App/Actions/Slides/CreateSlideInputTest.php +++ b/tests/Integration/Standalones/App/Cqs/Actions/Slides/CreateSlideInputTest.php @@ -2,8 +2,11 @@ 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; describe('CreateSlideInput', function (): void { it('creates a valid CreateSlideInput instance with text', function (): void { @@ -29,7 +32,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 +84,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/Services/DataTableServiceTest.php b/tests/Integration/Standalones/App/Services/DataTableServiceTest.php similarity index 60% rename from tests/Unit/Services/DataTableServiceTest.php rename to tests/Integration/Standalones/App/Services/DataTableServiceTest.php index 26f6b3b3..101b8442 100644 --- a/tests/Unit/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; @@ -10,8 +10,6 @@ use App\Services\DataTableService; use Illuminate\Contracts\Database\Query\Builder; use Illuminate\Contracts\Session\Session; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Schema; -use SortDirection; describe('DataTableService', function () { beforeEach(function () { @@ -24,40 +22,40 @@ 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); + $service = new DataTableService($request, $session, static fn (string $table): array => []); // WHEN $sort = $service->getSortRequest(); // THEN expect($sort['sort_col'])->toBe('name'); - expect($sort['sort_way'])->toBe(SortDirection::Descending); + expect($sort['sort_way'])->toBe(\SortDirection::Descending); }); 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'); - $service = new DataTableService($request, $session); + $service = new DataTableService($request, $session, static fn (string $table): array => []); // WHEN $sort = $service->getSortRequest(); // THEN expect($sort['sort_col'])->toBe('name'); - expect($sort['sort_way'])->toBe(SortDirection::Ascending); + expect($sort['sort_way'])->toBe(\SortDirection::Ascending); }); 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', @@ -65,7 +63,7 @@ describe('DataTableService', function () { ])->once(); $session->shouldReceive('get')->andReturn(null); - $service = new DataTableService($request, $session); + $service = new DataTableService($request, $session, static fn (string $table): array => []); // WHEN $service->resetSortSession('noroute'); @@ -80,84 +78,90 @@ 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); - Schema::shouldReceive('getColumnListing') - ->once() - ->with('products') - ->andReturn(['id', 'name', 'order', 'created_at']); + $schemaCalls = []; + $columnResolver = function (string $table) use (&$schemaCalls): array { + $schemaCalls[] = $table; - $query = mock(Builder::class); + return ['id', 'name', 'order', 'created_at']; + }; + + $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); + $service = new DataTableService($request, $session, $columnResolver); // WHEN - // First call triggers getColumnListing + // First call triggers column listing resolver $service->sortQuery(Product::class, $query); - // Second call uses columnsCache without re-calling getColumnListing + // Second call uses columnsCache without re-calling column listing resolver $service->sortQuery(Product::class, $query2); // THEN - // Mockery verifies on teardown: getColumnListing() once, orderBy() once per query. + expect($schemaCalls)->toBe(['products']); }); 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); - Schema::shouldReceive('getColumnListing') - ->once() - ->with('products') - ->andReturn(['id', 'name', 'order', 'created_at']); + $schemaCalls = []; + $columnResolver = function (string $table) use (&$schemaCalls): array { + $schemaCalls[] = $table; - $query = mock(Builder::class); + return ['id', 'name', 'order', 'created_at']; + }; + + $query = \Mockery::mock(Builder::class); $query->shouldReceive('orderBy')->once()->with('order', 'asc'); - $service = new DataTableService($request, $session); + $service = new DataTableService($request, $session, $columnResolver); // WHEN $service->sortQuery(Product::class, $query); // THEN - // Mockery verifies on teardown that orderBy('order', 'asc') was called once. + expect($schemaCalls)->toBe(['products']); }); 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); - Schema::shouldReceive('getColumnListing') - ->once() - ->with('orders') - ->andReturn(['id', 'reference', 'status', 'total']); + $schemaCalls = []; + $columnResolver = function (string $table) use (&$schemaCalls): array { + $schemaCalls[] = $table; - $query = mock(Builder::class); + return ['id', 'reference', 'status', 'total']; + }; + + $query = \Mockery::mock(Builder::class); $query->shouldReceive('orderBy')->once()->with('orders.id', 'desc'); - $service = new DataTableService($request, $session); + $service = new DataTableService($request, $session, $columnResolver); // WHEN $service->sortQuery( Order::class, $query, defaultSortCol: 'date', - defaultSortWay: SortDirection::Descending, + defaultSortWay: \SortDirection::Descending, columnMap: ['date' => 'id'], ); // THEN - // Mockery verifies on teardown that orderBy('orders.id', 'desc') was called once. + expect($schemaCalls)->toBe(['orders']); }); it('uses columnMap when sorting by an explicit virtual column', function () { @@ -166,19 +170,21 @@ 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(); - Schema::shouldReceive('getColumnListing') - ->once() - ->with('orders') - ->andReturn(['id', 'reference', 'status', 'total']); + $schemaCalls = []; + $columnResolver = function (string $table) use (&$schemaCalls): array { + $schemaCalls[] = $table; - $query = mock(Builder::class); + return ['id', 'reference', 'status', 'total']; + }; + + $query = \Mockery::mock(Builder::class); $query->shouldReceive('orderBy')->once()->with('orders.id', 'asc'); - $service = new DataTableService($request, $session); + $service = new DataTableService($request, $session, $columnResolver); // WHEN $service->sortQuery( @@ -188,6 +194,6 @@ describe('DataTableService', function () { ); // THEN - // Mockery verifies on teardown that orderBy('orders.id', 'asc') was called once. + expect($schemaCalls)->toBe(['orders']); }); }); diff --git a/tests/Integration/Standalones/App/Services/ImageOptimizerServiceTest.php b/tests/Integration/Standalones/App/Services/ImageOptimizerServiceTest.php new file mode 100644 index 00000000..876aaeec --- /dev/null +++ b/tests/Integration/Standalones/App/Services/ImageOptimizerServiceTest.php @@ -0,0 +1,55 @@ + new ImageOptimizerService( + new TemporaryFileFactory(), + new NullLogger(), + ); + + it('creates a real temp file for optimized images with the original extension', function () use ($makeService): void { + // GIVEN + $service = $makeService(); + $file = UploadedFile::fake()->image('picture.jpg', 800, 600); + + // WHEN + $optimized = $service->optimize($file, quality: 70); + $path = $optimized->getRealPath(); + $optimized->rewind(); + $content = $optimized->fread(16); + + // THEN + expect($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 ($makeService): void { + // GIVEN + $service = $makeService(); + $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($path)->not->toBeFalse() + ->and(file_exists($path))->toBeTrue() + ->and(pathinfo($path, PATHINFO_EXTENSION))->toBe('pdf') + ->and($content)->toBeString(); + }); +}); diff --git a/tests/Integration/Standalones/Infra/Adapters/Locks/LaravelCacheLockTest.php b/tests/Integration/Standalones/Infra/Adapters/Locks/LaravelCacheLockTest.php new file mode 100644 index 00000000..4730703e --- /dev/null +++ b/tests/Integration/Standalones/Infra/Adapters/Locks/LaravelCacheLockTest.php @@ -0,0 +1,107 @@ +synchronize('test:lock:success', fn (): string => 'ok'); + + // THEN + expect($result)->toBe('ok'); + + // Verify lock was released and can be acquired again immediately + $reacquired = $store->lock('test:lock:success', 10)->get(); + expect($reacquired)->toBeTrue(); + }); + + it('releases lock even when callback throws an exception', function (): void { + // GIVEN + $store = new ArrayStore(); + $cache = new Repository($store); + $cacheLock = new LaravelCacheLock($cache); + $customException = new \RuntimeException('Callback failure'); + + // WHEN + $action = fn () => $cacheLock->synchronize('test:lock:exception', function () use ($customException): never { + throw $customException; + }); + + // THEN + expect($action)->toThrow($customException); + + $reacquired = $store->lock('test:lock:exception', 10)->get(); + expect($reacquired)->toBeTrue(); + }); + + it('throws LockTimeoutException when lock is already held', function (): void { + // GIVEN + $store = new ArrayStore(); + $cache = new Repository($store); + $cacheLock = new LaravelCacheLock($cache); + + $heldLock = $store->lock('test:lock:held', 30); + expect($heldLock->get())->toBeTrue(); + + // WHEN + $action = fn () => $cacheLock->synchronize( + key: 'test:lock:held', + callback: fn (): string => 'never', + ttlSeconds: 30, + waitSeconds: 0, + ); + + // THEN + expect($action)->toThrow(LockTimeoutException::class); + + $heldLock->release(); + }); + + it('wraps Laravel LockTimeoutException with previous exception preserved', function (): void { + // GIVEN + $laravelLock = \Mockery::mock(Lock::class); + $laravelLock->shouldReceive('block') + ->once() + ->with(5, \Mockery::type(\Closure::class)) + ->andThrow(new LaravelLockTimeoutException('Timed out')); + + $store = \Mockery::mock(Store::class, LockProvider::class); + $store->shouldReceive('lock') + ->once() + ->with('test:lock:wrapped', 30) + ->andReturn($laravelLock); + + $cache = new Repository($store); + $cacheLock = new LaravelCacheLock($cache); + + // WHEN + $caught = null; + + try { + $cacheLock->synchronize('test:lock:wrapped', fn (): string => 'never', 30, 5); + } catch (LockTimeoutException $e) { + $caught = $e; + } + + // THEN + expect($caught)->toBeInstanceOf(LockTimeoutException::class) + ->and($caught?->getMessage())->toBe('Timed out') + ->and($caught?->getPrevious())->toBeInstanceOf(LaravelLockTimeoutException::class); + }); +}); diff --git a/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php b/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php new file mode 100644 index 00000000..80607fc9 --- /dev/null +++ b/tests/Integration/Standalones/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php @@ -0,0 +1,91 @@ +find($basketId); + + // THEN + expect($basket)->toBeNull(); + }); + + it('persists and retrieves a basket using real Store and BasketSerializer', function (): void { + // GIVEN + $basketId = new BasketId(UuidHelper::v7()); + $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 + expect($session->has('basket_key' . $basketId->value->toString()))->toBeTrue() + ->and($retrieved)->toBeInstanceOf(Basket::class) + ->and($retrieved?->id->equals($basketId))->toBeTrue(); + }); + + it('returns null if session data is invalid json', function (): void { + // GIVEN + $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()); + + // WHEN + $basket = $repo->find($basketId); + + // THEN + expect($basket)->toBeNull(); + }); + + it('returns null if deserialization throws exception', function (): void { + // GIVEN + $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()); + + // WHEN + $basket = $repo->find($basketId); + + // THEN + expect($basket)->toBeNull(); + }); + + it('deletes basket from session', function (): void { + // GIVEN + $basketId = new BasketId(UuidHelper::v7()); + $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 + 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 new file mode 100644 index 00000000..b1ffc87f --- /dev/null +++ b/tests/Integration/Standalones/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php @@ -0,0 +1,104 @@ + new SessionOrderBuilderManager($session, ' '); + + // 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(UuidHelper::v7()), []), + new ShopperId(UuidHelper::v7()), + ); + $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(UuidHelper::v7()), []), + new ShopperId(UuidHelper::v7()), + ); + $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(UuidHelper::v7()), []), + new ShopperId(UuidHelper::v7()), + ); + $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/Actions/Customers/RegisterCustomerTest.php b/tests/Integration/WithApp/App/Actions/Customers/RegisterCustomerTest.php deleted file mode 100644 index c421f910..00000000 --- a/tests/Integration/WithApp/App/Actions/Customers/RegisterCustomerTest.php +++ /dev/null @@ -1,349 +0,0 @@ -matricule = $matricule; - $employee->code = $code; - $employee->nom = 'Doe'; - $employee->prenom = 'John'; - $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); - $employee->site = new ShopperSiteCode('SITE'); - $employee->service = new ShopperServiceCode('1'); - $employee->saveOrFail(); - - $crmReturnedHashcode = Uuid::uuid4()->toString(); - - $crmService = \Mockery::mock(CrmService::class); - $crmService->shouldReceive('persist') - ->once() - ->withArgs(function (CrmCustomer $crmCust) use ($email): bool { - return $crmCust->email === $email->value - && $crmCust->firstname === 'John' - && $crmCust->lastname === 'Doe' - && $crmCust->city === 'Paris' - && $crmCust->country === Country::france; - }) - ->andReturn(new CrmCustomer( - hashcode: $crmReturnedHashcode, - email: $email->value, - password: null, - firstname: 'John', - lastname: 'Doe', - birthDate: '1990-01-01', - phone: '+33612345678', - address: '10 rue de Paris', - address2: null, - city: 'Paris', - postcode: '75001', - country: Country::france, - optIn: true, - status: false, - lastConnection: null, - )); - App::instance(CrmService::class, $crmService); - - $authService = \Mockery::mock(AppCustomerAuthService::class); - $authService->shouldReceive('logIn') - ->once() - ->withArgs(fn (Customer $c) => $c->email->value === $email->value); - App::instance(AppCustomerAuthService::class, $authService); - - $employeeRepo = resolve(EmployeeRepository::class); - - $action = new RegisterCustomer( - authService: $authService, - crmService: $crmService, - employeeRepository: $employeeRepo, - ); - - $input = new RegisterCustomerInput( - matricule: $matricule, - code: $code, - firstname: 'John', - lastname: 'Doe', - email: $email, - password: 'secretPassword123!', - birthDate: $birthDate, - phone: $phone, - address: '10 rue de Paris', - postcode: '75001', - city: 'Paris', - optIn: true, - ); - - // WHEN - $customer = $action($input); - - // THEN - expect($customer)->toBeInstanceOf(Customer::class) - ->and($customer->email->value)->toBe('john.doe@example.com') - ->and($customer->hashcode->value)->toBe($crmReturnedHashcode); - - $freshEmployee = Employee::query()->find($employee->id); - expect($freshEmployee?->customer_id)->toBe($customer->id); - }); - - it('throws ModelNotFoundException when employee does not exist', function (): void { - // GIVEN - $crmService = \Mockery::mock(CrmService::class); - $authService = \Mockery::mock(AppCustomerAuthService::class); - App::instance(CrmService::class, $crmService); - App::instance(AppCustomerAuthService::class, $authService); - - $employeeRepo = resolve(EmployeeRepository::class); - - $action = new RegisterCustomer( - authService: $authService, - crmService: $crmService, - employeeRepository: $employeeRepo, - ); - - $input = new RegisterCustomerInput( - matricule: new Matricule('9999999'), - code: new Code('ABCDYZ'), // no I, L, O, V in Code VO - firstname: 'John', - lastname: 'Doe', - email: new Email('ghost@example.com'), - password: 'secretPassword123!', - birthDate: new \DateTimeImmutable('1990-01-01'), - phone: null, - address: null, - postcode: '75001', - city: 'Paris', - ); - - // WHEN & THEN - expect(fn () => $action($input))->toThrow(ModelNotFoundException::class); - }); - - it('throws ValidationException when CRM indicates customer already exists', function (): void { - // GIVEN - $matricule = new Matricule('2345678'); - $code = new Code('BCDEFG'); - $email = new Email('existing@example.com'); - - $employee = new Employee(); - $employee->matricule = $matricule; - $employee->code = $code; - $employee->nom = 'Existing'; - $employee->prenom = 'User'; - $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); - $employee->site = new ShopperSiteCode('SITE'); - $employee->service = new ShopperServiceCode('1'); - $employee->saveOrFail(); - - $crmService = \Mockery::mock(CrmService::class); - $crmService->shouldReceive('persist') - ->once() - ->andThrow(new CrmCustomerExistsException()); - App::instance(CrmService::class, $crmService); - - $authService = \Mockery::mock(AppCustomerAuthService::class); - App::instance(AppCustomerAuthService::class, $authService); - - $employeeRepo = resolve(EmployeeRepository::class); - - $action = new RegisterCustomer( - authService: $authService, - crmService: $crmService, - employeeRepository: $employeeRepo, - ); - - $input = new RegisterCustomerInput( - matricule: $matricule, - code: $code, - firstname: 'User', - lastname: 'Existing', - email: $email, - password: 'secretPassword123!', - birthDate: new \DateTimeImmutable('1990-01-01'), - phone: null, - address: null, - postcode: '75001', - city: 'Paris', - ); - - // WHEN & THEN - expect(fn () => $action($input))->toThrow(ValidationException::class); - }); - - it('throws ValidationException when CRM fails with CrmServiceException', function (): void { - // GIVEN - $matricule = new Matricule('3456789'); - $code = new Code('CDEFGH'); - $email = new Email('crmerror@example.com'); - - $employee = new Employee(); - $employee->matricule = $matricule; - $employee->code = $code; - $employee->nom = 'Error'; - $employee->prenom = 'Crm'; - $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); - $employee->site = new ShopperSiteCode('SITE'); - $employee->service = new ShopperServiceCode('1'); - $employee->saveOrFail(); - - $crmService = \Mockery::mock(CrmService::class); - $crmService->shouldReceive('persist') - ->once() - ->andThrow(CrmServiceException::of('CRM service offline')); - App::instance(CrmService::class, $crmService); - - $authService = \Mockery::mock(AppCustomerAuthService::class); - App::instance(AppCustomerAuthService::class, $authService); - - $employeeRepo = resolve(EmployeeRepository::class); - - $action = new RegisterCustomer( - authService: $authService, - crmService: $crmService, - employeeRepository: $employeeRepo, - ); - - $input = new RegisterCustomerInput( - matricule: $matricule, - code: $code, - firstname: 'Crm', - lastname: 'Error', - email: $email, - password: 'secretPassword123!', - birthDate: new \DateTimeImmutable('1990-01-01'), - phone: null, - address: null, - postcode: '75001', - city: 'Paris', - ); - - // WHEN & THEN - expect(fn () => $action($input))->toThrow(ValidationException::class); - }); - - it('throws UnexpectedValueException when CRM returns no hashcode', function (): void { - // GIVEN - $matricule = new Matricule('4567890'); - $code = new Code('DEFGHJ'); - $email = new Email('nohash@example.com'); - - $employee = new Employee(); - $employee->matricule = $matricule; - $employee->code = $code; - $employee->nom = 'No'; - $employee->prenom = 'Hash'; - $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); - $employee->site = new ShopperSiteCode('SITE'); - $employee->service = new ShopperServiceCode('1'); - $employee->saveOrFail(); - - $crmService = \Mockery::mock(CrmService::class); - $crmService->shouldReceive('persist') - ->once() - ->andReturn(new CrmCustomer( - hashcode: null, - email: $email->value, - password: null, - firstname: 'Hash', - lastname: 'No', - birthDate: '1990-01-01', - phone: null, - address: null, - address2: null, - city: 'Paris', - postcode: '75001', - country: Country::france, - optIn: false, - status: false, - lastConnection: null, - )); - App::instance(CrmService::class, $crmService); - - $authService = \Mockery::mock(AppCustomerAuthService::class); - App::instance(AppCustomerAuthService::class, $authService); - - $employeeRepo = resolve(EmployeeRepository::class); - - $action = new RegisterCustomer( - authService: $authService, - crmService: $crmService, - employeeRepository: $employeeRepo, - ); - - $input = new RegisterCustomerInput( - matricule: $matricule, - code: $code, - firstname: 'Hash', - lastname: 'No', - email: $email, - password: 'secretPassword123!', - birthDate: new \DateTimeImmutable('1990-01-01'), - phone: null, - address: null, - postcode: '75001', - city: 'Paris', - ); - - // WHEN & THEN - expect(fn () => $action($input))->toThrow(\UnexpectedValueException::class); - }); - - it('throws when invalid ActionInput is passed', function (): void { - // GIVEN - $crmService = \Mockery::mock(CrmService::class); - $authService = \Mockery::mock(AppCustomerAuthService::class); - App::instance(CrmService::class, $crmService); - App::instance(AppCustomerAuthService::class, $authService); - - $employeeRepo = resolve(EmployeeRepository::class); - - $action = new RegisterCustomer( - authService: $authService, - crmService: $crmService, - employeeRepository: $employeeRepo, - ); - - $invalidInput = new class () implements ActionInput - { - }; - - // WHEN & THEN - expect(fn () => $action($invalidInput))->toThrow(\InvalidArgumentException::class); - }); -}); diff --git a/tests/Integration/WithApp/App/Actions/Ranges/CreateRangeTest.php b/tests/Integration/WithApp/App/Actions/Ranges/CreateRangeTest.php deleted file mode 100644 index 31aadc91..00000000 --- a/tests/Integration/WithApp/App/Actions/Ranges/CreateRangeTest.php +++ /dev/null @@ -1,61 +0,0 @@ -Une superbe gamme

', - picture: UploadedFile::fake()->image('range.jpg', 500, 500), - pictureMetadata: new PictureMetadata(alt: 'Image alt range', title: 'Image title range'), - status: true, - ); - - // WHEN - $range = $action($input); - - // THEN - expect($range)->toBeInstanceOf(Range::class) - ->and($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') - ->and($range->picture_title)->toBe('Image title range') - ->and($range->status)->toBeTrue() - ->and($range->exists)->toBeTrue(); - - $this->assertDatabaseHas('ranges', [ - 'id' => $range->id, - 'name' => 'Gamme Décoration', - 'slug' => 'gamme-decoration', - ]); - }); - - test('it throws when an invalid input is passed', function () { - // GIVEN - $action = new CreateRange(); - $invalidInput = new class () implements ActionInput - { - }; - - // WHEN & THEN - expect(fn () => $action($invalidInput)) - ->toThrow(\InvalidArgumentException::class); - }); -}); diff --git a/tests/Integration/WithApp/App/Actions/Ranges/DeleteRangeTest.php b/tests/Integration/WithApp/App/Actions/Ranges/DeleteRangeTest.php deleted file mode 100644 index 19ae58dd..00000000 --- a/tests/Integration/WithApp/App/Actions/Ranges/DeleteRangeTest.php +++ /dev/null @@ -1,48 +0,0 @@ -name = 'Gamme Temporaire'; - $range->picture_alt = 'Alt'; - $range->picture_title = 'Title'; - $range->status = true; - $range->save(); - - $action = new DeleteRange(); - $input = new DeleteRangeInput(range: $range); - - // WHEN - $result = $action($input); - - // THEN - expect($result)->toBeTrue(); - $this->assertDatabaseMissing('ranges', [ - 'id' => $range->id, - ]); - }); - - test('it throws when an invalid input is passed', function () { - // GIVEN - $action = new DeleteRange(); - $invalidInput = new class () implements ActionInput - { - }; - - // WHEN & THEN - expect(fn () => $action($invalidInput)) - ->toThrow(\InvalidArgumentException::class); - }); -}); diff --git a/tests/Integration/WithApp/App/Actions/Ranges/UpdateRangeTest.php b/tests/Integration/WithApp/App/Actions/Ranges/UpdateRangeTest.php deleted file mode 100644 index 326ef02c..00000000 --- a/tests/Integration/WithApp/App/Actions/Ranges/UpdateRangeTest.php +++ /dev/null @@ -1,69 +0,0 @@ -name = 'Gamme Initiale'; - $range->description = 'Ancien contenu'; - $range->picture_alt = 'Ancien alt'; - $range->picture_title = 'Ancien title'; - $range->status = true; - $range->save(); - - $action = new UpdateRange(); - $input = new UpdateRangeInput( - range: $range, - name: 'Gamme Renommée', - description: 'Nouveau contenu', - picture: UploadedFile::fake()->image('new-range.jpg', 500, 500), - pictureMetadata: new PictureMetadata(alt: 'Nouveau alt', title: 'Nouveau title'), - status: false, - ); - - // WHEN - $updatedRange = $action($input); - - // THEN - expect($updatedRange->id)->toBe($range->id) - ->and($updatedRange->name)->toBe('Gamme Renommée') - ->and($updatedRange->slug)->toBe('gamme-renommee') - ->and($updatedRange->description)->toBe('Nouveau contenu') - ->and($updatedRange->picture_alt)->toBe('Nouveau alt') - ->and($updatedRange->picture_title)->toBe('Nouveau title') - ->and($updatedRange->status)->toBeFalse(); - - $this->assertDatabaseHas('ranges', [ - 'id' => $range->id, - 'name' => 'Gamme Renommée', - 'status' => 0, - ]); - }); - - test('it throws when an invalid input is passed', function () { - // GIVEN - $action = new UpdateRange(); - $invalidInput = new class () implements ActionInput - { - }; - - // WHEN & THEN - expect(fn () => $action($invalidInput)) - ->toThrow(\InvalidArgumentException::class); - }); -}); diff --git a/tests/Integration/WithApp/App/Actions/Shops/CreateShopTest.php b/tests/Integration/WithApp/App/Actions/Shops/CreateShopTest.php deleted file mode 100644 index faf7452a..00000000 --- a/tests/Integration/WithApp/App/Actions/Shops/CreateShopTest.php +++ /dev/null @@ -1,62 +0,0 @@ -toBeInstanceOf(Shop::class) - ->and($shop->name)->toBe('Boutique Bastille') - ->and($shop->address)->toBe('5 Place de la Bastille') - ->and($shop->postcode)->toBe('75011') - ->and($shop->city)->toBe('Paris') - ->and($shop->phone)->toBe('+33140506070') - ->and((float) $shop->latitude)->toBe(48.8530) - ->and((float) $shop->longitude)->toBe(2.3690) - ->and($shop->default)->toBeTrue() - ->and($shop->exists)->toBeTrue(); - - $this->assertDatabaseHas('shops', [ - 'id' => $shop->id, - 'name' => 'Boutique Bastille', - ]); - }); - - test('it throws when an invalid input is passed', function () { - // GIVEN - $action = new CreateShop(); - $invalidInput = new class () implements ActionInput - { - }; - - // WHEN & THEN - expect(fn () => $action($invalidInput)) - ->toThrow(\InvalidArgumentException::class); - }); -}); diff --git a/tests/Integration/WithApp/App/Actions/Slides/DeleteSlideTest.php b/tests/Integration/WithApp/App/Actions/Slides/DeleteSlideTest.php deleted file mode 100644 index a9e22ebc..00000000 --- a/tests/Integration/WithApp/App/Actions/Slides/DeleteSlideTest.php +++ /dev/null @@ -1,44 +0,0 @@ -title = 'Slide à supprimer'; - $slide->text = '

Contenu

'; - $slide->saveOrFail(); - - $action = new DeleteSlide(); - $input = new DeleteSlideInput(slide: $slide); - - // WHEN - $result = $action($input); - - // THEN - expect($result)->toBeTrue(); - expect(Slide::query()->find($slide->id))->toBeNull(); - }); - - it('throws when an invalid input is passed', function (): void { - // GIVEN - $action = new DeleteSlide(); - $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/Slides/UpdateSlideTest.php b/tests/Integration/WithApp/App/Actions/Slides/UpdateSlideTest.php deleted file mode 100644 index cd8e3676..00000000 --- a/tests/Integration/WithApp/App/Actions/Slides/UpdateSlideTest.php +++ /dev/null @@ -1,68 +0,0 @@ -title = 'Ancien Titre'; - $slide->text = '

Ancien texte

'; - $slide->saveOrFail(); - - $action = new UpdateSlide(); - $start = new \DateTimeImmutable('2026-07-01 10:00:00'); - $end = new \DateTimeImmutable('2026-07-31 20:00:00'); - $period = new DatePeriod($start, $end); - - $input = new UpdateSlideInput( - slide: $slide, - title: 'Titre Mis à Jour', - text: '

Texte mis à jour

', - link: 'https://example.com/updated', - linkLabel: 'Lien mis à jour', - linkNewTab: true, - connected: true, - period: $period, - ); - - // WHEN - $updatedSlide = $action($input); - - // THEN - expect($updatedSlide->id)->toBe($slide->id) - ->and($updatedSlide->title)->toBe('Titre Mis à Jour') - ->and($updatedSlide->text)->toBe('

Texte mis à jour

') - ->and($updatedSlide->link)->toBe('https://example.com/updated') - ->and($updatedSlide->link_label)->toBe('Lien mis à jour') - ->and($updatedSlide->link_new_tab)->toBeTrue() - ->and($updatedSlide->connected)->toBeTrue(); - - $fresh = Slide::query()->find($slide->id); - expect($fresh)->not->toBeNull() - ->and($fresh?->title)->toBe('Titre Mis à Jour') - ->and($fresh?->text)->toBe('

Texte mis à jour

'); - }); - - it('throws when an invalid input is passed', function (): void { - // GIVEN - $action = new UpdateSlide(); - $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/Auth/CrmUserProviderTest.php b/tests/Integration/WithApp/App/Auth/CrmUserProviderTest.php new file mode 100644 index 00000000..7d1759e1 --- /dev/null +++ b/tests/Integration/WithApp/App/Auth/CrmUserProviderTest.php @@ -0,0 +1,109 @@ +shouldNotReceive('getCustomerFromEmail'); + + $provider = new CrmUserProvider($hasher, Customer::class, $crmService); + + // WHEN + $result = $provider->retrieveByCredentials(['email' => 'crm-only@example.com']); + + // THEN + expect($result)->toBeNull() + ->and(Customer::query()->count())->toBe(0); + }); + + it('returns the existing local customer when CRM also confirms it', function (): void { + // GIVEN + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'email' => new Email('existing-local@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + $crmCustomer = new CrmCustomer( + hashcode: $customer->hashcode->value, + email: 'existing-local@example.com', + password: null, + firstname: 'John', + lastname: 'Doe', + birthDate: null, + phone: null, + address: null, + address2: null, + city: null, + postcode: null, + country: Country::france, + optIn: false, + status: true, + lastConnection: null, + ); + + $hasher = new BcryptHasher(); + /** @var \Mockery\MockInterface&\App\Services\CrmService $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('getCustomerFromEmail') + ->once() + ->with('existing-local@example.com') + ->andReturn($crmCustomer); + + $provider = new CrmUserProvider($hasher, Customer::class, $crmService); + + // WHEN + $result = $provider->retrieveByCredentials(['email' => 'existing-local@example.com']); + + // THEN + expect($result)->toBeInstanceOf(Customer::class) + ->and($result?->getAuthIdentifier())->toBe($customer->id); + }); + + it('catches mail delivery failures when resending activation email for unactivated accounts', function (): void { + // GIVEN + $customer = new Customer(['email' => new Email('unverified@example.com')]); + + $dispatcher = \Mockery::mock(Dispatcher::class); + $dispatcher->shouldReceive('send') + ->once() + ->andThrow(new \RuntimeException('SMTP connection refused')); + app()->instance(Dispatcher::class, $dispatcher); + + $hasher = new BcryptHasher(); + /** @var \Mockery\MockInterface&\App\Services\CrmService $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('login') + ->once() + ->with('unverified@example.com', 'valid-password') + ->andThrow(new CrmCustomerNotActivatedException()); + + $provider = new CrmUserProvider($hasher, Customer::class, $crmService); + + // WHEN + $isValid = $provider->validateCredentials($customer, [ + 'email' => 'unverified@example.com', + 'password' => 'valid-password', + ]); + + // THEN + expect($isValid)->toBeTrue(); + }); +}); diff --git a/tests/Integration/WithApp/App/Casts/CalendarDateCastTest.php b/tests/Integration/WithApp/App/Casts/CalendarDateCastTest.php new file mode 100644 index 00000000..a7a8e2ff --- /dev/null +++ b/tests/Integration/WithApp/App/Casts/CalendarDateCastTest.php @@ -0,0 +1,53 @@ +date = $parisMidnight; + $exception->label = 'Victoire 1945'; + $exception->repeatable = true; + $exception->repeat_frequency = RepeatFrequency::YEARLY; + $exception->setAttribute('auto_updated', true); + + // WHEN + $exception->saveOrFail(); + + $rawDate = DB::table('pickup_exceptions')->where('id', $exception->id)->value('date'); + $reloaded = PickupException::query()->findOrFail($exception->id); + + // THEN + expect($rawDate)->toBe('2026-05-08') + ->and($reloaded->date->format('Y-m-d'))->toBe('2026-05-08') + ->and($reloaded->date->timezoneName)->toBe('UTC'); + }); + + it('preserves calendar date for CarbonImmutable midnight and returns startOfDay UTC', function (): void { + // GIVEN + $cast = new CalendarDateCast(); + $model = new PickupException(); + $parisImmutable = CarbonImmutable::parse('2026-05-08 00:00:00', 'Europe/Paris'); + + // WHEN + $storedDate = $cast->set($model, 'date', $parisImmutable, []); + $readDate = $cast->get($model, 'date', '2026-05-08', []); + + // THEN + expect($storedDate)->toBe('2026-05-08') + ->and($readDate?->format('Y-m-d H:i:s'))->toBe('2026-05-08 00:00:00') + ->and($readDate?->timezoneName)->toBe('UTC'); + }); +}); diff --git a/tests/Unit/App/Casts/CodeCastTest.php b/tests/Integration/WithApp/App/Casts/CodeCastTest.php similarity index 90% rename from tests/Unit/App/Casts/CodeCastTest.php rename to tests/Integration/WithApp/App/Casts/CodeCastTest.php index 988ad5d4..6f69b925 100644 --- a/tests/Unit/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; @@ -15,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 () { @@ -52,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/Unit/App/Casts/DeliveryAddressCastTest.php b/tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php similarity index 92% rename from tests/Unit/App/Casts/DeliveryAddressCastTest.php rename to tests/Integration/WithApp/App/Casts/DeliveryAddressCastTest.php index 979aa75f..ea1e9908 100644 --- a/tests/Unit/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; @@ -15,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é'); @@ -52,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') @@ -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/Unit/App/Casts/DiscountValueCastTest.php b/tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php similarity index 87% rename from tests/Unit/App/Casts/DiscountValueCastTest.php rename to tests/Integration/WithApp/App/Casts/DiscountValueCastTest.php index e8bd1b0c..8aa29bb4 100644 --- a/tests/Unit/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; @@ -23,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 () { @@ -41,9 +42,9 @@ it('gets a discount value from amount', function () { ); // THEN - expect($value)->toBeInstanceOf(DiscountValue::class) - ->and($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,9 +61,9 @@ it('gets a discount value from amount string', function () { ); // THEN - expect($value)->toBeInstanceOf(DiscountValue::class) - ->and($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 () { @@ -129,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 @@ -154,7 +156,7 @@ it('sets a discount value amount', function () { // GIVEN $cast = new DiscountValueCast(); $model = \Mockery::mock(Model::class); - $currency = resolve(Currency::class); + $currency = new Currency('EUR'); $discount = DiscountValue::fromAmount(new Money(1000, $currency)); // WHEN diff --git a/tests/Unit/App/Casts/EmailCastTest.php b/tests/Integration/WithApp/App/Casts/EmailCastTest.php similarity index 92% rename from tests/Unit/App/Casts/EmailCastTest.php rename to tests/Integration/WithApp/App/Casts/EmailCastTest.php index df906c3d..f6851055 100644 --- a/tests/Unit/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; @@ -15,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 () { @@ -58,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/Unit/App/Casts/EmployeeSitesCastTest.php b/tests/Integration/WithApp/App/Casts/EmployeeSitesCastTest.php similarity index 97% rename from tests/Unit/App/Casts/EmployeeSitesCastTest.php rename to tests/Integration/WithApp/App/Casts/EmployeeSitesCastTest.php index 8928b119..6a040d35 100644 --- a/tests/Unit/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; @@ -88,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/Unit/App/Casts/MatriculeCastTest.php b/tests/Integration/WithApp/App/Casts/MatriculeCastTest.php similarity index 92% rename from tests/Unit/App/Casts/MatriculeCastTest.php rename to tests/Integration/WithApp/App/Casts/MatriculeCastTest.php index f4075e6c..8c91c873 100644 --- a/tests/Unit/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; @@ -15,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 () { @@ -47,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/Unit/App/Casts/MoneyCastTest.php b/tests/Integration/WithApp/App/Casts/MoneyCastTest.php similarity index 83% rename from tests/Unit/App/Casts/MoneyCastTest.php rename to tests/Integration/WithApp/App/Casts/MoneyCastTest.php index ddd92a16..d12e8126 100644 --- a/tests/Unit/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; @@ -16,9 +18,8 @@ it('gets a money from string', function () { $money = $cast->get($model, 'price', '1000', []); // THEN - expect($money)->toBeInstanceOf(Money::class) - ->and($money->getAmount())->toBe('1000') - ->and($money->getCurrency()->getCode())->toBe(resolve(Currency::class)->getCode()); + expect($money->getAmount())->toBe('1000') + ->and($money->getCurrency()->getCode())->toBe('EUR'); }); it('gets a money from int', function () { @@ -30,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 () { @@ -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 @@ -66,7 +67,7 @@ it('sets a money', function () { // GIVEN $cast = new MoneyCast(); $model = \Mockery::mock(Model::class); - $money = new Money(1000, resolve(Currency::class)); + $money = new Money(1000, new Currency('EUR')); // WHEN $value = $cast->set($model, 'price', $money, []); diff --git a/tests/Unit/App/Casts/NutritionalValuesCastTest.php b/tests/Integration/WithApp/App/Casts/NutritionalValuesCastTest.php similarity index 87% rename from tests/Unit/App/Casts/NutritionalValuesCastTest.php rename to tests/Integration/WithApp/App/Casts/NutritionalValuesCastTest.php index d552bde3..1a7a98a7 100644 --- a/tests/Unit/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; @@ -19,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(); }); @@ -51,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); }); @@ -65,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 () { @@ -75,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/Unit/App/Casts/OrderEmployeeCastTest.php b/tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php similarity index 88% rename from tests/Unit/App/Casts/OrderEmployeeCastTest.php rename to tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php index b0087466..98019748 100644 --- a/tests/Unit/App/Casts/OrderEmployeeCastTest.php +++ b/tests/Integration/WithApp/App/Casts/OrderEmployeeCastTest.php @@ -2,9 +2,14 @@ declare(strict_types=1); +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 () { @@ -33,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(); @@ -55,16 +56,12 @@ it('gets an order employee from json string', function () { $employee = $cast->get($model, 'employee', $json, []); // THEN - expect($employee)->toBeInstanceOf(OrderEmployee::class) - ->and($employee->matricule)->toBeInstanceOf(Matricule::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)->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'); }); @@ -86,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 @@ -111,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 new file mode 100644 index 00000000..b818b461 --- /dev/null +++ b/tests/Integration/WithApp/App/Casts/OrderLineProductCastTest.php @@ -0,0 +1,159 @@ +get($model, 'product', null, []); + + // THEN + })->throws(\InvalidArgumentException::class, 'The value cannot be null.'); + + it('throws exception when getting non-string', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); + + // WHEN + $cast->get($model, 'product', 123, []); + + // THEN + })->throws(\InvalidArgumentException::class, 'The value must be a string.'); + + it('gets an order line product', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); + $uuid = UuidHelper::v7()->toString(); + + $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', + ]); + + // WHEN + $product = $cast->get($model, 'product', $json, []); + + // THEN + 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) + ->and($product->weight->isVariable)->toBeFalse() + ->and($product->taxRate)->toBe(TaxRate::TVA_5_5) + ->and($product->picture?->value)->toBe('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 = UuidHelper::v7()->toString(); + + $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, + ]); + + // WHEN + $product = $cast->get($model, 'product', $json, []); + + // THEN + expect($product->taxRate)->toBe(TaxRate::TVA_20) + ->and($product->picture)->toBeNull(); + }); + + it('throws exception when setting invalid type', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); + + // WHEN + /** @phpstan-ignore argument.type */ + $cast->set($model, 'product', 'invalid', []); + + // THEN + })->throws( + \InvalidArgumentException::class, + 'The given value is not an instance of OrderLineProduct.' + ); + + it('sets an order line product', function () { + // GIVEN + $cast = new OrderLineProductCast(); + $model = \Mockery::mock(Model::class); + $currency = new Currency('EUR'); + + $product = new OrderLineProduct( + incoId: new IncoId(123), + originalId: new ProductId(UuidHelper::v7()), + 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 + assert(is_array($data)); + expect($value)->toBeJson() + ->and($data) + ->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/App/Casts/OrderReferenceCastTest.php b/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php new file mode 100644 index 00000000..9a47ba67 --- /dev/null +++ b/tests/Integration/WithApp/App/Casts/OrderReferenceCastTest.php @@ -0,0 +1,94 @@ +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 = 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/Unit/App/Casts/ShopperEstablishmentCodeCastTest.php b/tests/Integration/WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php similarity index 94% rename from tests/Unit/App/Casts/ShopperEstablishmentCodeCastTest.php rename to tests/Integration/WithApp/App/Casts/ShopperEstablishmentCodeCastTest.php index 5c8576be..36684fd6 100644 --- a/tests/Unit/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; @@ -15,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 () { @@ -72,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/Unit/App/Casts/ShopperServiceCodeCastTest.php b/tests/Integration/WithApp/App/Casts/ShopperServiceCodeCastTest.php similarity index 94% rename from tests/Unit/App/Casts/ShopperServiceCodeCastTest.php rename to tests/Integration/WithApp/App/Casts/ShopperServiceCodeCastTest.php index 02c3ad3c..e66a078a 100644 --- a/tests/Unit/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; @@ -15,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 () { @@ -72,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/Unit/App/Casts/ShopperSiteCodeCastTest.php b/tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php similarity index 93% rename from tests/Unit/App/Casts/ShopperSiteCodeCastTest.php rename to tests/Integration/WithApp/App/Casts/ShopperSiteCodeCastTest.php index 2209806c..51594a6e 100644 --- a/tests/Unit/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; @@ -15,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 () { @@ -72,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/Casts/UtcDatetimeCastTest.php b/tests/Integration/WithApp/App/Casts/UtcDatetimeCastTest.php new file mode 100644 index 00000000..fc644848 --- /dev/null +++ b/tests/Integration/WithApp/App/Casts/UtcDatetimeCastTest.php @@ -0,0 +1,61 @@ +type = DiscountType::AMOUNT; + $discount->value = DiscountValue::fromAmount(Money::EUR(100)); + $discount->is_old_price_displayed = true; + $discount->date_start = $parisStart; + $discount->date_end = $parisEnd; + + // WHEN + $discount->saveOrFail(); + + $rawRow = DB::table('discounts')->where('id', $discount->id)->first(); + $reloaded = Discount::query()->findOrFail($discount->id); + + // THEN + expect($rawRow?->date_start)->toBe('2026-05-04 14:00:00') + ->and($rawRow?->date_end)->toBe('2026-11-02 14:30:00') + ->and($reloaded->date_start?->timezoneName)->toBe('UTC') + ->and($reloaded->date_start?->format('Y-m-d H:i:s'))->toBe('2026-05-04 14:00:00') + ->and($reloaded->date_end?->format('Y-m-d H:i:s'))->toBe('2026-11-02 14:30:00'); + }); + + it('normalizes offset-aware ISO strings and CarbonImmutable to UTC and preserves null values', function (): void { + // GIVEN + $cast = new UtcDatetimeCast(); + $model = new Discount(); + $parisImmutable = CarbonImmutable::parse('2026-05-04 16:00:00', 'Europe/Paris'); + + // WHEN + $storedImmutable = $cast->set($model, 'date_start', $parisImmutable, []); + $storedIso = $cast->set($model, 'date_start', '2026-07-10T10:15:00+02:00', []); + $storedNull = $cast->set($model, 'date_start', null, []); + $readNull = $cast->get($model, 'date_start', null, []); + + // THEN + expect($storedImmutable)->toBe('2026-05-04 14:00:00') + ->and($storedIso)->toBe('2026-07-10 08:15:00') + ->and($storedNull)->toBeNull() + ->and($readNull)->toBeNull(); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Auth/DeleteOldResetTokensTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Auth/DeleteOldResetTokensTest.php new file mode 100644 index 00000000..ac96b0e2 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Auth/DeleteOldResetTokensTest.php @@ -0,0 +1,56 @@ +insert([ + [ + 'email' => 'old@example.com', + 'token' => 'old-token', + 'created_at' => Date::now()->subDays(8), + ], + [ + 'email' => 'recent@example.com', + 'token' => 'recent-token', + 'created_at' => Date::now()->subDays(2), + ], + ]); + $action = new DeleteOldResetTokens(); + + // WHEN + $action(new ActionInputEmpty()); + + // THEN + expect(PasswordReset::query()->where('email', 'old@example.com')->exists())->toBeFalse() + ->and(PasswordReset::query()->where('email', 'recent@example.com')->exists())->toBeTrue(); + + Date::setTestNow(); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $action = new DeleteOldResetTokens(); + $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/Cqs/Actions/Auth/ResetCustomerPasswordTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php new file mode 100644 index 00000000..c0cb1a00 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Auth/ResetCustomerPasswordTest.php @@ -0,0 +1,167 @@ +forceCreate([ + 'email' => new Email('action-reset@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + $shopper = new Shopper( + id: $customer->getId(), + email: new Email('action-reset@example.com'), + matricule: new Matricule('1234567'), + nom: 'Doe', + prenom: 'John', + startDate: CarbonImmutable::now()->subMonth(), + endDate: null, + etablissement: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), + ); + + $shopperService = \Mockery::mock(ShopperService::class); + $shopperService->shouldReceive('getShopperFor') + ->once() + ->with(\Mockery::on(fn (ShopperId $id): bool => $id->equals($customer->getId()))) + ->andReturn($shopper); + + $authService = \Mockery::mock(AppCustomerAuthService::class); + $authService->shouldReceive('resetPasswordFor') + ->once() + ->with($customer, 'NewPassword123!') + ->andReturnTrue(); + $authService->shouldReceive('hasVerifiedEmail') + ->once() + ->with($customer) + ->andReturnTrue(); + + $action = new ResetCustomerPassword($shopperService, $authService); + $input = new ResetCustomerPasswordInput($customer, 'NewPassword123!'); + + // WHEN + $output = $action($input); + + // THEN + expect($output->status)->toBe(ResetCustomerPasswordStatus::SUCCESS) + ->and($output->emailVerified)->toBeTrue() + ->and($customer->fresh()?->getRememberToken())->not->toBeNull(); + }); + + it('returns notEmployed output when shopper is missing or inactive', function (): void { + // GIVEN + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'email' => new Email('action-inactive@example.com'), + 'hashcode' => (string) Str::uuid(), + 'remember_token' => 'existing-token', + ]); + + $inactiveShopper = new Shopper( + id: $customer->getId(), + email: new Email('action-inactive@example.com'), + matricule: new Matricule('1234568'), + nom: 'Doe', + prenom: 'Jane', + startDate: CarbonImmutable::now()->subMonth(), + endDate: CarbonImmutable::now()->subDay(), + etablissement: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), + ); + + $shopperService = \Mockery::mock(ShopperService::class); + $shopperService->shouldReceive('getShopperFor')->once()->andReturn($inactiveShopper); + + $authService = \Mockery::mock(AppCustomerAuthService::class); + $authService->shouldNotReceive('resetPasswordFor'); + + $action = new ResetCustomerPassword($shopperService, $authService); + + // WHEN + $output = $action(new ResetCustomerPasswordInput($customer, 'NewPassword123!')); + + // THEN + expect($output->status)->toBe(ResetCustomerPasswordStatus::NOT_EMPLOYED) + ->and($customer->fresh()?->getRememberToken())->toBe('existing-token'); + }); + + it('returns invalidPassword output when CRM rejects the new password', function (): void { + // GIVEN + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'email' => new Email('action-invalid@example.com'), + 'hashcode' => (string) Str::uuid(), + 'remember_token' => 'existing-token', + ]); + + $shopper = new Shopper( + id: $customer->getId(), + email: new Email('action-invalid@example.com'), + matricule: new Matricule('1234569'), + nom: 'Doe', + prenom: 'Alice', + startDate: CarbonImmutable::now()->subMonth(), + endDate: null, + etablissement: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), + ); + + $shopperService = \Mockery::mock(ShopperService::class); + $shopperService->shouldReceive('getShopperFor')->once()->andReturn($shopper); + + $authService = \Mockery::mock(AppCustomerAuthService::class); + $authService->shouldReceive('resetPasswordFor') + ->once() + ->andReturn(ValidationException::withMessages(['password' => 'Too weak'])); + + $action = new ResetCustomerPassword($shopperService, $authService); + + // WHEN + $output = $action(new ResetCustomerPasswordInput($customer, 'weak')); + + // THEN + expect($output->status)->toBe(ResetCustomerPasswordStatus::INVALID_PASSWORD) + ->and($output->errorMessage)->toContain('Too weak') + ->and($customer->fresh()?->getRememberToken())->toBe('existing-token'); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php new file mode 100644 index 00000000..f407f3c9 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/AddToBasketTest.php @@ -0,0 +1,161 @@ +name = 'Gamme Panier ' . uniqid(); + $range->status = true; + /** @var int $maxOrder */ + $maxOrder = Range::query()->max('order') ?? 0; + $range->order = $maxOrder + 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $product = new Product([ + 'range_id' => $range->id, + 'name' => 'Produit Panier ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_5_5, + 'description' => 'Description panier', + 'status' => $status, + ]); + $product->price = Money::EUR(1000); + $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(); + + if ($withInco) { + $inco = new ProductInco(); + $inco->product_id = $product->id; + $inco->no_art = random_int(10000, 99999); + $inco->saveOrFail(); + } + + return $product; +} + +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(); + $basketSvc = new BasketService( + $repository, + new EloquentProductRepository(), + new AppSessionService('domain_session_uuid'), + $dispatcher, + ); + $action = new AddToBasket($basketSvc); + + // WHEN + $action(new AddToBasketInput($product->getId(), 2)); + $action(new AddToBasketInput($product->getId(), 3)); + + // THEN + $basket = $basketSvc->getBasket(); + expect($basket->countItems())->toBe(5) + ->and($basket->items())->toHaveCount(1) + ->and($basket->items()[$product->id]->qty)->toBe(5) + ->and($basket->items()[$product->id]->unitPriceHt->getAmount())->toBe('1000'); + }); + + 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'); + $builderManager->save(OrderBuilder::fromBasket( + new Basket(new BasketId(UuidHelper::v7()), []), + new ShopperId(UuidHelper::v7()), + )); + + $dispatcher = new LaravelDomainEventDispatcher(); + $basketSvc = new BasketService( + $repository, + new EloquentProductRepository(), + new AppSessionService('domain_session_uuid'), + $dispatcher, + ); + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + $dispatcher, + ); + + // WHEN + $executor->execute(new AddToBasket($basketSvc), new AddToBasketInput($product->getId(), 1)); + + // THEN + expect($builderManager->get())->toBeNull() + ->and($basketSvc->getBasket()->countItems())->toBe(1); + }); + + it('throws UnorderableProductException when product is disabled or missing inco', 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()), + new EloquentProductRepository(), + new AppSessionService('domain_session_uuid'), + new LaravelDomainEventDispatcher(), + ); + $action = new AddToBasket($basketSvc); + + // WHEN & THEN + expect(fn () => $action(new AddToBasketInput($inactiveProduct->getId(), 1))) + ->toThrow(UnorderableProductException::class); + expect(fn () => $action(new AddToBasketInput($noIncoProduct->getId(), 1))) + ->toThrow(UnorderableProductException::class); + expect($basketSvc->hasItems())->toBeFalse(); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php new file mode 100644 index 00000000..38535638 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/EmptyBasketTest.php @@ -0,0 +1,103 @@ +name = 'Gamme Vider Panier ' . uniqid(); + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $product = new Product([ + 'range_id' => $range->id, + 'name' => 'Produit À Vider ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_5_5, + 'description' => 'Desc', + 'status' => true, + ]); + $product->price = Money::EUR(900); + $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 = 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(); + $basketSvc = new BasketService( + new SessionBasketRepository($session, 'basket_', new BasketSerializer()), + new EloquentProductRepository(), + new AppSessionService('domain_session_uuid'), + $dispatcher, + ); + $basketSvc->add($product->getId(), 2); + + $builderManager->save(OrderBuilder::fromBasket( + new Basket(new BasketId(UuidHelper::v7()), []), + new ShopperId(UuidHelper::v7()), + )); + + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + $dispatcher, + ); + + // WHEN + $executor->execute(new EmptyBasket($basketSvc), ActionInputEmpty::create()); + + // THEN + expect($basketSvc->hasItems())->toBeFalse() + ->and($basketSvc->getBasket()->items())->toBeEmpty() + ->and($builderManager->get())->toBeNull(); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php new file mode 100644 index 00000000..6bded19c --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Basket/RemoveFromBasketTest.php @@ -0,0 +1,144 @@ +name = 'Gamme Retrait Panier ' . uniqid(); + $range->status = true; + /** @var int $maxOrder */ + $maxOrder = Range::query()->max('order') ?? 0; + $range->order = $maxOrder + 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $product = new Product([ + 'range_id' => $range->id, + 'name' => 'Produit Retrait ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_5_5, + 'description' => 'Description retrait', + 'status' => true, + ]); + $product->price = Money::EUR(800); + $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 = random_int(10000, 99999); + $inco->saveOrFail(); + + return $product; +} + +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()), + new EloquentProductRepository(), + new AppSessionService('domain_session_uuid'), + new LaravelDomainEventDispatcher(), + ); + $basketSvc->add($product->getId(), 5); + $action = new RemoveFromBasket($basketSvc); + + // WHEN + $action(new RemoveQuantityFromBasketInput($product->getId(), 2)); + + // THEN + expect($basketSvc->getBasket()->items()[$product->id]->qty)->toBe(3); + + // WHEN removing remaining quantity + $action(new RemoveQuantityFromBasketInput($product->getId(), 3)); + + // THEN + expect($basketSvc->hasItems())->toBeFalse(); + }); + + it('removes the whole product line with RemoveProductFromBasketInput and clears order builder', 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(); + $basketSvc = new BasketService( + new SessionBasketRepository($session, 'basket_', new BasketSerializer()), + new EloquentProductRepository(), + new AppSessionService('domain_session_uuid'), + $dispatcher, + ); + $basketSvc->add($product1->getId(), 4); + $basketSvc->add($product2->getId(), 2); + + $builderManager->save(OrderBuilder::fromBasket( + new Basket(new BasketId(UuidHelper::v7()), []), + new ShopperId(UuidHelper::v7()), + )); + + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + $dispatcher, + ); + + // WHEN + $executor->execute(new RemoveFromBasket($basketSvc), new RemoveProductFromBasketInput($product1->getId())); + + // THEN + $basket = $basketSvc->getBasket(); + expect($basket->countItems())->toBe(2) + ->and($basket->items())->toHaveCount(1) + ->and(array_key_exists($product1->id, $basket->items()))->toBeFalse() + ->and($basket->items()[$product2->id]->qty)->toBe(2) + ->and($builderManager->get())->toBeNull(); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Common/ChangeModelOrderPositionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderPositionTest.php similarity index 99% rename from tests/Integration/WithApp/App/Actions/Common/ChangeModelOrderPositionTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderPositionTest.php index e9b2d58d..b8c9b2e0 100644 --- a/tests/Integration/WithApp/App/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/Actions/Common/ChangeModelOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderTest.php similarity index 98% rename from tests/Integration/WithApp/App/Actions/Common/ChangeModelOrderTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Common/ChangeModelOrderTest.php index 10594ca7..a7ca05bc 100644 --- a/tests/Integration/WithApp/App/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/Actions/Common/ExecuteMassActionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ExecuteMassActionTest.php similarity index 95% rename from tests/Integration/WithApp/App/Actions/Common/ExecuteMassActionTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Common/ExecuteMassActionTest.php index 7866a664..0ac1e02f 100644 --- a/tests/Integration/WithApp/App/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; @@ -41,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/Actions/Common/ToggleModelStarTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStarTest.php similarity index 97% rename from tests/Integration/WithApp/App/Actions/Common/ToggleModelStarTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStarTest.php index c779520a..c558be3c 100644 --- a/tests/Integration/WithApp/App/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/Actions/Common/ToggleModelStatusTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStatusTest.php similarity index 95% rename from tests/Integration/WithApp/App/Actions/Common/ToggleModelStatusTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Common/ToggleModelStatusTest.php index 1721e71e..8cd397ef 100644 --- a/tests/Integration/WithApp/App/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 new file mode 100644 index 00000000..d03e0d04 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Contact/SubmitContactFormTest.php @@ -0,0 +1,135 @@ +shouldNotReceive('storeUploadedOntoDisk'); + $action = new SubmitContactForm($storage, new PrivateS3Disk()); + $orderRef = new OrderReference(UuidHelper::v7()); + $input = new SubmitContactFormInput( + lastName: 'Doe', + firstName: 'John', + email: 'john.doe@example.com', + subject: 'Question', + message: 'Bonjour, ceci est un message de test valide.', + orderRef: $orderRef, + ); + + // WHEN + $result = $action($input); + + // THEN + expect($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($orderRef) + ->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->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 & THEN + expect( + /** @phpstan-ignore argument.type */ + fn () => $action($invalidInput) + ) + ->toThrow(\InvalidArgumentException::class); + }); + + it('cleans up private S3 attachment when onFailure is triggered after upload', function (): void { + // GIVEN + $file = UploadedFile::fake()->create('document.pdf', 100, 'application/pdf'); + $storedPath = new StorageFilePath('contact-attachments/orphan.pdf'); + /** @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( + lastName: 'Doe', + firstName: 'John', + email: 'john.doe@example.com', + subject: 'Question', + message: 'Bonjour, ceci est un message de test valide.', + file: $file, + ); + + // WHEN + $action($input); + $action->onFailure($input, new \RuntimeException('Mail dispatch failed')); + + // THEN + $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/Crm/UnsubscribeFromNewsletterTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UnsubscribeFromNewsletterTest.php new file mode 100644 index 00000000..d3ce64b6 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UnsubscribeFromNewsletterTest.php @@ -0,0 +1,73 @@ +shouldReceive('unsubscribeCustomer') + ->once() + ->with(\Mockery::on(static fn (CrmHashcode $h): bool => $h->value === $hashcode->value)) + ->andReturnTrue(); + + $action = new UnsubscribeFromNewsletter($crmService); + + // WHEN + $output = $action(new UnsubscribeFromNewsletterInput($hashcode)); + + // THEN + expect($output)->toBe(UnsubscribeFromNewsletterOutput::SUCCESS); + }); + + it('returns FAILURE when CRM service returns false', function (): void { + // GIVEN + $hashcode = new CrmHashcode(UuidHelper::v4()); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('unsubscribeCustomer') + ->once() + ->with(\Mockery::on(static fn (CrmHashcode $h): bool => $h->value === $hashcode->value)) + ->andReturnFalse(); + + $action = new UnsubscribeFromNewsletter($crmService); + + // WHEN + $output = $action(new UnsubscribeFromNewsletterInput($hashcode)); + + // THEN + expect($output)->toBe(UnsubscribeFromNewsletterOutput::FAILURE); + }); + + it('returns FAILURE without throwing when CRM service throws an exception', function (): void { + // GIVEN + $hashcode = new CrmHashcode(UuidHelper::v4()); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('unsubscribeCustomer') + ->once() + ->andThrow(new \RuntimeException('CRM timeout')); + + $action = new UnsubscribeFromNewsletter($crmService); + + // WHEN + $output = $action(new UnsubscribeFromNewsletterInput($hashcode)); + + // THEN + expect($output)->toBe(UnsubscribeFromNewsletterOutput::FAILURE); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php new file mode 100644 index 00000000..fd1e567e --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerPasswordTest.php @@ -0,0 +1,151 @@ +toString(); + $customer = new Customer(); + $customer->email = new Email('claire.dupuis@example.com'); + $customer->hashcode = new CrmHashcode($hashcodeUuid); + $customer->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + $crmCustomer = makePasswordTestCrmCustomer($hashcode, $customer->email->value); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('getCustomerFromHashCode') + ->once() + ->with(\Mockery::on(static fn (CrmHashcode $h): bool => $h->value === $hashcode)) + ->andReturn($crmCustomer); + $crmService->shouldReceive('changePassword') + ->once() + ->with($crmCustomer, 'OldPass123!', 'NewPass456!') + ->andReturn($crmCustomer); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomerPassword($authService, $crmService); + + // WHEN + $output = $action(new UpdateCustomerPasswordInput('OldPass123!', 'NewPass456!')); + + // THEN + expect($output->result)->toBe($crmCustomer); + }); + + it('returns false output when customer cannot be resolved in CRM', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $customer = new Customer(); + $customer->email = new Email('missing.crm@example.com'); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); + $customer->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('getCustomerFromHashCode') + ->once() + ->andReturnNull(); + $crmService->shouldNotReceive('changePassword'); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomerPassword($authService, $crmService); + + // WHEN + $output = $action(new UpdateCustomerPasswordInput('OldPass123!', 'NewPass456!')); + + // THEN + expect($output->result)->toBeFalse(); + }); + + it('returns false output when changePassword throws an unexpected exception', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $hashcodeUuid = UuidHelper::v4(); + $hashcode = $hashcodeUuid->toString(); + $customer = new Customer(); + $customer->email = new Email('pwd.error@example.com'); + $customer->hashcode = new CrmHashcode($hashcodeUuid); + $customer->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + $crmCustomer = makePasswordTestCrmCustomer($hashcode, $customer->email->value); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('getCustomerFromHashCode') + ->once() + ->andReturn($crmCustomer); + $crmService->shouldReceive('changePassword') + ->once() + ->andThrow(new \RuntimeException('CRM error')); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomerPassword($authService, $crmService); + + // WHEN + $output = $action(new UpdateCustomerPasswordInput('OldPass123!', 'NewPass456!')); + + // THEN + expect($output->result)->toBeFalse(); + }); + + it('throws AuthServiceException when unauthenticated', function (): void { + // GIVEN + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldNotReceive('getCustomerFromHashCode'); + $crmService->shouldNotReceive('changePassword'); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomerPassword($authService, $crmService); + + // WHEN & THEN + expect(fn () => $action(new UpdateCustomerPasswordInput('OldPass123!', 'NewPass456!'))) + ->toThrow(AuthServiceException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php new file mode 100644 index 00000000..059f0211 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Crm/UpdateCustomerTest.php @@ -0,0 +1,203 @@ +toString(); + $customer = new Customer(); + $customer->email = new Email('jeanne.martin@example.com'); + $customer->hashcode = new CrmHashcode($hashcodeUuid); + $customer->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + $expectedCrmCustomer = makeCrmCustomerDto($hashcode, $customer->email->value); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('updateCustomerInfos') + ->once() + ->withArgs(function (Customer $passedCustomer, array $data) use ($customer): bool { + return $passedCustomer->id === $customer->id + && $data === [ + 'firstname' => 'Jeanne', + 'lastname' => 'Martin', + 'birth_date' => '1992-05-14', + 'postcode' => '53000', + 'city' => 'Laval', + 'opt_in' => true, + 'phone' => '+33611223344', + 'address' => '12 rue des Lilas', + ]; + }) + ->andReturn($expectedCrmCustomer); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomer($authService, $crmService); + + $input = new UpdateCustomerInput( + firstname: 'Jeanne', + lastname: 'Martin', + birthDate: '1992-05-14', + phone: '+33611223344', + address: '12 rue des Lilas', + postcode: '53000', + city: 'Laval', + optIn: true, + ); + + // WHEN + $output = $action($input); + + // THEN + expect($output->result)->toBe($expectedCrmCustomer); + }); + + it('omits nullable phone and address when null and propagates validation exceptions', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $hashcodeUuid = UuidHelper::v4(); + $customer = new Customer(); + $customer->email = new Email('no.phone@example.com'); + $customer->hashcode = new CrmHashcode($hashcodeUuid); + $customer->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + $validationException = ValidationException::withMessages(['postcode' => ['Code postal invalide']]); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('updateCustomerInfos') + ->once() + ->withArgs(function (Customer $_, array $data): bool { + return ! array_key_exists('phone', $data) + && ! array_key_exists('address', $data) + && $data['opt_in'] === false; + }) + ->andReturn($validationException); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomer($authService, $crmService); + + $input = new UpdateCustomerInput( + firstname: 'Paul', + lastname: 'Durand', + birthDate: '1985-03-10', + phone: null, + address: null, + postcode: '00000', + city: 'Sablé', + optIn: false, + ); + + // WHEN + $output = $action($input); + + // THEN + expect($output->result)->toBe($validationException); + }); + + it('returns false output when CRM service throws an unexpected error', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $customer = new Customer(); + $customer->email = new Email('err.crm@example.com'); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); + $customer->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('updateCustomerInfos') + ->once() + ->andThrow(new \RuntimeException('CRM unavailable')); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomer($authService, $crmService); + + $input = new UpdateCustomerInput( + firstname: 'Paul', + lastname: 'Durand', + birthDate: '1985-03-10', + phone: null, + address: null, + postcode: '72300', + city: 'Sablé', + optIn: true, + ); + + // WHEN + $output = $action($input); + + // THEN + expect($output->result)->toBeFalse(); + }); + + it('throws AuthServiceException when no customer is authenticated', function (): void { + // GIVEN + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldNotReceive('updateCustomerInfos'); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomer($authService, $crmService); + + $input = new UpdateCustomerInput( + firstname: 'Guest', + lastname: 'User', + birthDate: '1990-01-01', + phone: null, + address: null, + postcode: '72300', + city: 'Sablé', + optIn: false, + ); + + // WHEN & THEN + expect(fn () => $action($input)) + ->toThrow(AuthServiceException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php new file mode 100644 index 00000000..876281d5 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php @@ -0,0 +1,761 @@ +matricule = $matricule; + $employee->code = $code; + $employee->nom = 'Doe'; + $employee->prenom = 'John'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('1'); + $employee->saveOrFail(); + + $crmReturnedHashcode = UuidHelper::v4()->toString(); + + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('persist') + ->once() + ->withArgs(function (CrmCustomer $crmCust) use ($email): bool { + return $crmCust->email === $email->value + && $crmCust->firstname === 'John' + && $crmCust->lastname === 'Doe' + && $crmCust->city === 'Paris' + && $crmCust->country === Country::france; + }) + ->andReturn(new CrmCustomer( + hashcode: $crmReturnedHashcode, + email: $email->value, + password: null, + firstname: 'John', + lastname: 'Doe', + birthDate: '1990-01-01', + phone: '+33612345678', + address: '10 rue de Paris', + address2: null, + city: 'Paris', + postcode: '75001', + country: Country::france, + optIn: true, + status: false, + lastConnection: null, + )); + $authService = \Mockery::mock(AppCustomerAuthService::class); + $authService->shouldReceive('logIn') + ->once() + ->withArgs(fn (Customer $c) => $c->email->value === $email->value); + + $action = new RegisterCustomer( + authService: $authService, + crmService: $crmService, + ); + + $input = new RegisterCustomerInput( + matricule: $matricule, + code: $code, + firstname: 'John', + lastname: 'Doe', + email: $email, + password: 'secretPassword123!', + birthDate: $birthDate, + phone: $phone, + address: '10 rue de Paris', + postcode: '75001', + city: 'Paris', + optIn: true, + ); + + // WHEN + $result = $action($input); + + // THEN: __invoke defers email verification and login to onSuccess() + 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); + + Notification::assertNothingSent(); + + $action->onSuccess($input, $result); + + Notification::assertSentTo($result->customer, VerifyEmail::class); + + $freshEmployee = Employee::query()->find($employee->id); + expect($freshEmployee?->customer_id)->toBe($result->customer?->id); + }); + + 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(UuidHelper::v4()); + $existingCustomer->saveOrFail(); + + $matricule = new Matricule('5678901'); + $code = new Code('FGHJKM'); + + $employee = new Employee(); + $employee->matricule = $matricule; + $employee->code = $code; + $employee->nom = 'Already'; + $employee->prenom = 'Registered'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('1'); + $employee->customer()->associate($existingCustomer); + $employee->saveOrFail(); + + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldNotReceive('persist'); + + $authService = \Mockery::mock(AppCustomerAuthService::class); + $authService->shouldNotReceive('logIn'); + + $action = new RegisterCustomer( + authService: $authService, + crmService: $crmService, + ); + + $input = new RegisterCustomerInput( + matricule: $matricule, + code: $code, + firstname: 'New', + lastname: 'User', + email: new Email('new.user@example.com'), + password: 'secretPassword123!', + birthDate: new \DateTimeImmutable('1990-01-01'), + phone: null, + address: null, + postcode: '75001', + city: 'Paris', + ); + + // WHEN + $result = $action($input); + + // THEN + expect($result->status)->toBe(RegisterCustomerStatus::EMPLOYEE_ALREADY_REGISTERED) + ->and($result->customer)->toBeNull() + ->and(Customer::query()->count())->toBe(1); + + $freshEmployee = Employee::query()->find($employee->id); + expect($freshEmployee?->customer_id)->toBe($existingCustomer->id); + }); + + it('returns EMPLOYEE_INACTIVE when employee contract has ended', function (): void { + // GIVEN + Date::setTestNow(Date::parse('2026-06-15 10:00:00', 'Europe/Paris')); + + try { + $matricule = new Matricule('5678902'); + $code = new Code('FGHJK2'); + + $employee = new Employee(); + $employee->matricule = $matricule; + $employee->code = $code; + $employee->nom = 'Inactive'; + $employee->prenom = 'User'; + $employee->end_date = Carbon::parse('2026-06-15'); + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('1'); + $employee->saveOrFail(); + + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldNotReceive('persist'); + + $authService = \Mockery::mock(AppCustomerAuthService::class); + $authService->shouldNotReceive('logIn'); + + $action = new RegisterCustomer( + authService: $authService, + crmService: $crmService, + ); + + $input = new RegisterCustomerInput( + matricule: $matricule, + code: $code, + firstname: 'Inactive', + lastname: 'User', + email: new Email('inactive.user@example.com'), + password: 'secretPassword123!', + birthDate: new \DateTimeImmutable('1990-01-01'), + phone: null, + address: null, + postcode: '75001', + city: 'Paris', + ); + + // WHEN + $result = $action($input); + + // THEN + expect($result) + ->and($result->status)->toBe(RegisterCustomerStatus::EMPLOYEE_INACTIVE) + ->and($result->customer)->toBeNull() + ->and(Customer::query()->count())->toBe(0); + } finally { + Date::setTestNow(); + } + }); + + it('throws ModelNotFoundException when employee does not exist', function (): void { + // GIVEN + $crmService = \Mockery::mock(CrmService::class); + $authService = \Mockery::mock(AppCustomerAuthService::class); + + $action = new RegisterCustomer( + authService: $authService, + crmService: $crmService, + ); + + $input = new RegisterCustomerInput( + matricule: new Matricule('9999999'), + code: new Code('ABCDYZ'), // no I, L, O, V in Code VO + firstname: 'John', + lastname: 'Doe', + email: new Email('ghost@example.com'), + password: 'secretPassword123!', + birthDate: new \DateTimeImmutable('1990-01-01'), + phone: null, + address: null, + postcode: '75001', + city: 'Paris', + ); + + // WHEN & THEN + expect(fn () => $action($input))->toThrow(ModelNotFoundException::class); + }); + + it('throws ValidationException when CRM indicates customer already exists', function (): void { + // GIVEN + $matricule = new Matricule('2345678'); + $code = new Code('BCDEFG'); + $email = new Email('existing@example.com'); + + $employee = new Employee(); + $employee->matricule = $matricule; + $employee->code = $code; + $employee->nom = 'Existing'; + $employee->prenom = 'User'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('1'); + $employee->saveOrFail(); + + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('persist') + ->once() + ->andThrow(new CrmCustomerExistsException()); + + $authService = \Mockery::mock(AppCustomerAuthService::class); + + $action = new RegisterCustomer( + authService: $authService, + crmService: $crmService, + ); + + $input = new RegisterCustomerInput( + matricule: $matricule, + code: $code, + firstname: 'User', + lastname: 'Existing', + email: $email, + password: 'secretPassword123!', + birthDate: new \DateTimeImmutable('1990-01-01'), + phone: null, + address: null, + postcode: '75001', + city: 'Paris', + ); + + // WHEN & THEN + expect(fn () => $action($input))->toThrow(ValidationException::class); + }); + + it('throws ValidationException when CRM fails with CrmServiceException', function (): void { + // GIVEN + $matricule = new Matricule('3456789'); + $code = new Code('CDEFGH'); + $email = new Email('crmerror@example.com'); + + $employee = new Employee(); + $employee->matricule = $matricule; + $employee->code = $code; + $employee->nom = 'Error'; + $employee->prenom = 'Crm'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('1'); + $employee->saveOrFail(); + + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('persist') + ->once() + ->andThrow(CrmServiceException::of('CRM service offline')); + + $authService = \Mockery::mock(AppCustomerAuthService::class); + + $action = new RegisterCustomer( + authService: $authService, + crmService: $crmService, + ); + + $input = new RegisterCustomerInput( + matricule: $matricule, + code: $code, + firstname: 'Crm', + lastname: 'Error', + email: $email, + password: 'secretPassword123!', + birthDate: new \DateTimeImmutable('1990-01-01'), + phone: null, + address: null, + postcode: '75001', + city: 'Paris', + ); + + // WHEN & THEN + expect(fn () => $action($input))->toThrow(ValidationException::class); + }); + + it('throws UnexpectedValueException when CRM returns no hashcode', function (): void { + // GIVEN + $matricule = new Matricule('4567890'); + $code = new Code('DEFGHJ'); + $email = new Email('nohash@example.com'); + + $employee = new Employee(); + $employee->matricule = $matricule; + $employee->code = $code; + $employee->nom = 'No'; + $employee->prenom = 'Hash'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('1'); + $employee->saveOrFail(); + + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('persist') + ->once() + ->andReturn(new CrmCustomer( + hashcode: null, + email: $email->value, + password: null, + firstname: 'Hash', + lastname: 'No', + birthDate: '1990-01-01', + phone: null, + address: null, + address2: null, + city: 'Paris', + postcode: '75001', + country: Country::france, + optIn: false, + status: false, + lastConnection: null, + )); + $authService = \Mockery::mock(AppCustomerAuthService::class); + + $action = new RegisterCustomer( + authService: $authService, + crmService: $crmService, + ); + + $input = new RegisterCustomerInput( + matricule: $matricule, + code: $code, + firstname: 'Hash', + lastname: 'No', + email: $email, + password: 'secretPassword123!', + birthDate: new \DateTimeImmutable('1990-01-01'), + phone: null, + address: null, + postcode: '75001', + city: 'Paris', + ); + + // WHEN & THEN + expect(fn () => $action($input))->toThrow(\UnexpectedValueException::class); + }); + + it('throws when invalid ActionInput is passed', function (): void { + // GIVEN + $crmService = \Mockery::mock(CrmService::class); + $authService = \Mockery::mock(AppCustomerAuthService::class); + + $action = new RegisterCustomer( + authService: $authService, + crmService: $crmService, + ); + + $invalidInput = new class () implements ActionInput + { + }; + + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + + // WHEN & THEN + expect(fn () => $callable($invalidInput))->toThrow(\InvalidArgumentException::class); + }); + + it('acquires matricule lock via ActionExecutorService and returns LOCK_TIMEOUT when lock fails', function (): void { + // GIVEN + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldNotReceive('persist'); + $authService = \Mockery::mock(AppCustomerAuthService::class); + $action = new RegisterCustomer( + authService: $authService, + crmService: $crmService, + ); + + $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 + $output = $executor->execute($action, $input); + + // THEN + expect($output) + ->and($output->status)->toBe(RegisterCustomerStatus::LOCK_TIMEOUT); + }); + + it('builds lockKey from input matricule', function (): void { + // GIVEN + $crmService = \Mockery::mock(CrmService::class); + $authService = \Mockery::mock(AppCustomerAuthService::class); + $action = new RegisterCustomer( + authService: $authService, + crmService: $crmService, + ); + + $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', + ); + + // WHEN + $key = $action->lockKey($input); + + // THEN + expect($key)->toBe('customer:register:employee:1234567'); + }); + + it('returns lockTimeout output on lock timeout', function (): void { + // GIVEN + $crmService = \Mockery::mock(CrmService::class); + $authService = \Mockery::mock(AppCustomerAuthService::class); + $action = new RegisterCustomer( + authService: $authService, + crmService: $crmService, + ); + + $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', + ); + + // WHEN + $result = $action->onLockTimeout($input); + + // THEN + expect($result) + ->and($result->status)->toBe(RegisterCustomerStatus::LOCK_TIMEOUT) + ->and($result->customer)->toBeNull() + ->and($result->errorMessage)->toBeNull(); + }); + + it('executes post-commit verification email and login only after commit via Executor', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $matricule = new Matricule('6789012'); + $code = new Code('MNPQRS'); + $email = new Email('postcommit@example.com'); + + $employee = new Employee(); + $employee->matricule = $matricule; + $employee->code = $code; + $employee->nom = 'Commit'; + $employee->prenom = 'Post'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('1'); + $employee->saveOrFail(); + + $crmReturnedHashcode = UuidHelper::v4()->toString(); + + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('persist')->once()->andReturn(new CrmCustomer( + hashcode: $crmReturnedHashcode, + email: $email->value, + password: null, + firstname: 'Post', + lastname: 'Commit', + birthDate: '1990-01-01', + phone: null, + address: null, + address2: null, + city: 'Paris', + postcode: '75001', + country: Country::france, + optIn: false, + status: false, + lastConnection: null, + )); + $crmService->shouldNotReceive('deleteByHashcode'); + + $authService = \Mockery::mock(AppCustomerAuthService::class); + $authService->shouldReceive('logIn') + ->once() + ->withArgs(fn (Customer $c): bool => $c->email->value === $email->value); + + $action = new RegisterCustomer($authService, $crmService); + $executor = $this->app->make(Executor::class); + $input = new RegisterCustomerInput( + matricule: $matricule, + code: $code, + firstname: 'Post', + lastname: 'Commit', + email: $email, + password: 'secretPassword123!', + birthDate: new \DateTimeImmutable('1990-01-01'), + phone: null, + address: null, + postcode: '75001', + city: 'Paris', + ); + + // WHEN + $result = $executor->execute($action, $input); + + // THEN + expect($result->status)->toBe(RegisterCustomerStatus::SUCCESS) + ->and($result->customer)->toBeInstanceOf(Customer::class); + Notification::assertSentTo($result->customer, VerifyEmail::class); + }); + + it('compensates CRM customer via deleteByHashcode when local persistence fails after CRM creation', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $matricule = new Matricule('7890123'); + $code = new Code('NPQRST'); + $email = new Email('splitbrain@example.com'); + + $employee = new Employee(); + $employee->matricule = $matricule; + $employee->code = $code; + $employee->nom = 'Brain'; + $employee->prenom = 'Split'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('1'); + $employee->saveOrFail(); + + $crmUuid = UuidHelper::v4(); + $crmReturnedHashcode = $crmUuid->toString(); + + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('persist')->once()->andReturn(new CrmCustomer( + hashcode: $crmReturnedHashcode, + email: $email->value, + password: null, + firstname: 'Split', + lastname: 'Brain', + birthDate: '1990-01-01', + phone: null, + address: null, + address2: null, + city: 'Paris', + postcode: '75001', + country: Country::france, + optIn: false, + status: false, + lastConnection: null, + )); + $crmService->shouldReceive('deleteByHashcode') + ->once() + ->withArgs( + fn (CrmHashcode $hash, ?Email $deletedEmail): bool => $hash->value === $crmReturnedHashcode + && $deletedEmail?->value === $email->value + ) + ->andReturnTrue(); + + $authService = \Mockery::mock(AppCustomerAuthService::class); + $authService->shouldNotReceive('logIn'); + + $action = new RegisterCustomer($authService, $crmService); + $executor = $this->app->make(Executor::class); + $input = new RegisterCustomerInput( + matricule: $matricule, + code: $code, + firstname: 'Split', + lastname: 'Brain', + email: $email, + password: 'secretPassword123!', + birthDate: new \DateTimeImmutable('1990-01-01'), + phone: null, + address: null, + postcode: '75001', + city: 'Paris', + ); + + Event::listen('eloquent.updating: ' . Customer::class, static function (): void { + throw new \RuntimeException('Simulated DB error after CRM persist'); + }); + + // WHEN & THEN + try { + expect(fn () => $executor->execute($action, $input)) + ->toThrow(\RuntimeException::class, 'Simulated DB error after CRM persist'); + } finally { + Event::forget('eloquent.updating: ' . Customer::class); + } + + expect(Customer::query()->count())->toBe(0) + ->and($employee->fresh()?->customer_id)->toBeNull(); + Notification::assertNothingSent(); + }); + + it('does not call deleteByHashcode on failure when CRM creation did not succeed', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $matricule = new Matricule('8901234'); + $code = new Code('PQRSTU'); + $email = new Email('already-crm@example.com'); + + $employee = new Employee(); + $employee->matricule = $matricule; + $employee->code = $code; + $employee->nom = 'Exists'; + $employee->prenom = 'Crm'; + $employee->etablissement = new ShopperEstablishmentCode('ETAB01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('1'); + $employee->saveOrFail(); + + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('persist')->once()->andThrow(new CrmCustomerExistsException()); + $crmService->shouldNotReceive('deleteByHashcode'); + + $authService = \Mockery::mock(AppCustomerAuthService::class); + $authService->shouldNotReceive('logIn'); + + $action = new RegisterCustomer($authService, $crmService); + $executor = $this->app->make(Executor::class); + $input = new RegisterCustomerInput( + matricule: $matricule, + code: $code, + firstname: 'Crm', + lastname: 'Exists', + email: $email, + password: 'secretPassword123!', + birthDate: new \DateTimeImmutable('1990-01-01'), + phone: null, + address: null, + postcode: '75001', + city: 'Paris', + ); + + // WHEN & THEN + expect(fn () => $executor->execute($action, $input)) + ->toThrow(ValidationException::class); + + expect(Customer::query()->count())->toBe(0) + ->and($employee->fresh()?->customer_id)->toBeNull(); + Notification::assertNothingSent(); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Customers/UpdateCustomerLastLoginTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Customers/UpdateCustomerLastLoginTest.php new file mode 100644 index 00000000..e9003f68 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Customers/UpdateCustomerLastLoginTest.php @@ -0,0 +1,55 @@ +email = new Email('customer@example.com'); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); + $customer->last_login_at = null; + $customer->saveOrFail(); + + $action = new UpdateCustomerLastLogin(); + $input = new UpdateCustomerLastLoginInput($customer); + + // WHEN + $updated = $action($input); + + // THEN + expect($updated->last_login_at?->format('Y-m-d H:i:s'))->toBe('2026-11-14 10:30:00') + ->and(Customer::query()->find($customer->id)?->last_login_at?->format('Y-m-d H:i:s')) + ->toBe('2026-11-14 10:30:00'); + + Date::setTestNow(); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $action = new UpdateCustomerLastLogin(); + $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/Discounts/CreateDiscountTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Discounts/CreateDiscountTest.php similarity index 95% rename from tests/Integration/WithApp/App/Actions/Discounts/CreateDiscountTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Discounts/CreateDiscountTest.php index 737057fd..c176d33f 100644 --- a/tests/Integration/WithApp/App/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/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/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php new file mode 100644 index 00000000..46731116 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php @@ -0,0 +1,113 @@ +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/Faqs/CreateFaqTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Faqs/CreateFaqTest.php similarity index 89% rename from tests/Integration/WithApp/App/Actions/Faqs/CreateFaqTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Faqs/CreateFaqTest.php index bec06a46..9b585feb 100644 --- a/tests/Integration/WithApp/App/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; @@ -20,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/Actions/Faqs/DeleteFaqTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Faqs/DeleteFaqTest.php similarity index 95% rename from tests/Integration/WithApp/App/Actions/Faqs/DeleteFaqTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Faqs/DeleteFaqTest.php index 90cde2bf..0fdfd3aa 100644 --- a/tests/Integration/WithApp/App/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/Actions/Faqs/UpdateFaqTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Faqs/UpdateFaqTest.php similarity index 96% rename from tests/Integration/WithApp/App/Actions/Faqs/UpdateFaqTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Faqs/UpdateFaqTest.php index a305aef9..a4725b86 100644 --- a/tests/Integration/WithApp/App/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 new file mode 100644 index 00000000..a27f113c --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php @@ -0,0 +1,189 @@ +create(['default' => true]); + + $customer = new Customer(); + $customer->email = new Email('slot.buyer@example.com'); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); + $customer->saveOrFail(); + + $employee = new Employee(); + $employee->customer_id = $customer->id; + $employee->matricule = new Matricule('1000303'); + $employee->code = new Code('ABCDEF'); + $employee->nom = 'Durand'; + $employee->prenom = 'Sophie'; + $employee->start_date = Carbon::parse('2025-01-01'); + $employee->etablissement = new ShopperEstablishmentCode('01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('01'); + $employee->saveOrFail(); + + $productId = new ProductId(UuidHelper::v7()); + $basket = new Basket(new BasketId(UuidHelper::v7()), [ + $productId->value->toString() => new BasketProduct( + id: $productId, + name: 'Filet de Poulet', + qty: 1, + unitPriceHt: Money::EUR(1000), + unitDiscount: Money::EUR(0), + taxRate: TaxRate::TVA_5_5, + weightGrams: 500, + brand: ProductBrand::loue, + incoId: new IncoId(654321), + orderUnit: OrderUnit::PCE, + slug: 'filet-de-poulet', + picture: null, + description: null, + weightVariable: false, + discountRate: DiscountRate::zero(), + priceKgTtc: Money::EUR(1000), + options: [], + ), + ]); + + /** @var \Illuminate\Contracts\Session\Session $session */ + $session = Session::driver(); + $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); + $builderManager->save(OrderBuilder::fromBasket($basket, $customer->getId())); + + $shopRepo = new EloquentShopRepository(); + $shopperRepo = new EloquentShopperRepository(); + $orderRepo = new EloquentOrderRepository(); + + /** @var \Domain\Ports\Services\RegateService&\Mockery\MockInterface $regateService */ + $regateService = \Mockery::mock(RegateService::class); + + $tunnelService = new OrderTunnelService( + new LaravelDomainEventDispatcher(), + 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 DatabaseTunnelAttemptTrackerService($session, 'order_tunnel_attempt_id'), + ); + + return [$customer, $shop, $builderManager, $tunnelService]; + } + + it('matches an open pickup day and upgrades the session builder to OrderBuilderCompleted', function (): void { + // GIVEN + [$customer, $shop, $builderManager, $tunnelService] = makePickSlotEnvironment(); + $action = new ApplyPickTimeSlot($tunnelService); + + // Friday of current week after Monday 10:00 cutoff -> open + $targetFriday = CarbonImmutable::parse('2026-11-20', 'Europe/Paris'); + + // WHEN + $output = $action(new ApplyPickTimeSlotInput($customer->getId(), $targetFriday)); + + // THEN + expect($output->status)->toBe(ApplyPickTimeSlotStatus::MATCHED) + ->and($output->timeSlot)->not->toBeNull() + ->and($output->timeSlot?->getAt()->format('Y-m-d'))->toBe('2026-11-20'); + + $completed = $builderManager->get(); + 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 { + // GIVEN + [$customer, $shop, $_, $tunnelService] = makePickSlotEnvironment(); + + $blockedException = PickupException::factory()->create([ + 'date' => '2026-11-20', + 'label' => 'Fermeture exceptionnelle', + ]); + $shop->pickupExceptions()->attach($blockedException->id, [ + 'replacement_date' => null, + 'order_deadline_at' => null, + ]); + + $action = new ApplyPickTimeSlot($tunnelService); + $targetFriday = CarbonImmutable::parse('2026-11-20', 'Europe/Paris'); + + // WHEN + $output = $action(new ApplyPickTimeSlotInput($customer->getId(), $targetFriday)); + + // THEN + expect($output->status)->toBe(ApplyPickTimeSlotStatus::UNAVAILABLE) + ->and($output->timeSlot)->toBeNull(); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php new file mode 100644 index 00000000..ea48952e --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/CancelOrderTest.php @@ -0,0 +1,76 @@ +create(); + + return Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(UuidHelper::v7()), + 'status' => $status->value, + 'total' => new Money(2500, new Currency('EUR')), + 'employee' => new OrderEmployee( + new Matricule('1000202'), + 'Alice', + 'Martin', + new ShopperEstablishmentCode('01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('01'), + ), + 'delivery_address' => new DeliveryAddress('Shop Test', '2 rue Test', '72300', 'Sablé'), + 'pickup_day' => '2026-11-20 14:00:00', + ]); +} + +describe('CancelOrder action', function (): void { + it('cancels an existing persisted order and updates status in database', function (): void { + // GIVEN + $order = makeCancelOrderFixture(OrderStatus::VALIDATED); + $action = new CancelOrder(new OrderService(new EloquentOrderRepository())); + + // WHEN + $output = $action(new CancelOrderInput($order)); + + // THEN + expect($output)->toBe(CancelOrderOutput::CANCELLED) + ->and($order->fresh()?->status)->toBe(OrderStatus::CANCELED); + }); + + it('returns NOT_FOUND when the order does not exist in database', function (): void { + // GIVEN + $missingOrder = new Order(); + $missingOrder->id = UuidHelper::v7()->toString(); + + $action = new CancelOrder(new OrderService(new EloquentOrderRepository())); + + // WHEN + $output = $action(new CancelOrderInput($missingOrder)); + + // THEN + expect($output)->toBe(CancelOrderOutput::NOT_FOUND); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php new file mode 100644 index 00000000..e32d88d3 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ClaimTodayOrderReminderTest.php @@ -0,0 +1,59 @@ +create(); + $order = Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(UuidHelper::v7()), + 'status' => OrderStatus::VALIDATED->value, + 'total' => new Money(2000, new Currency('EUR')), + 'employee' => new OrderEmployee( + new Matricule('1000101'), + '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', + ]); + + $action = new ClaimTodayOrderReminder(); + $remindedAt = CarbonImmutable::parse('2026-11-20 10:00:00'); + $input = new ClaimTodayOrderReminderInput($order->getId(), $remindedAt); + + // WHEN + $firstClaim = $action($input); + $secondClaim = $action($input); + + // THEN + expect($firstClaim)->toBeTrue() + ->and($secondClaim)->toBeFalse() + ->and($order->fresh()?->reminded_at)->not->toBeNull(); + }); +}); 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..97b4575a --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/FailStalePendingOrdersTest.php @@ -0,0 +1,106 @@ +create(); + + $stalePendingId = UuidHelper::v7()->toString(); + $freshPendingId = UuidHelper::v7()->toString(); + $staleWaitingId = UuidHelper::v7()->toString(); + $staleValidatedId = UuidHelper::v7()->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(UuidHelper::v7()), + 'status' => OrderStatus::PENDING->value, + 'updated_at' => $now->subMinutes(15)->toDateTimeString(), + ]), + array_merge($baseRow, [ + 'id' => $freshPendingId, + '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(UuidHelper::v7()), + 'status' => OrderStatus::WAITING->value, + 'updated_at' => $now->subHours(2)->toDateTimeString(), + ]), + array_merge($baseRow, [ + 'id' => $staleValidatedId, + 'reference' => (string) new OrderReference(UuidHelper::v7()), + '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/InitializeOrderTunnelTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php new file mode 100644 index 00000000..a5b1ed40 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/InitializeOrderTunnelTest.php @@ -0,0 +1,111 @@ +value->toString() => new BasketProduct( + id: $productId, + name: 'Poulet Rôti', + qty: 2, + unitPriceHt: Money::EUR(1200), + unitDiscount: Money::EUR(0), + taxRate: TaxRate::TVA_5_5, + weightGrams: 1200, + 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), + options: [], + ), + ]); + /** @var Customer $customer */ + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'email' => new Email('init-tunnel@example.com'), + 'hashcode' => UuidHelper::v4()->toString(), + ]); + $shopperId = $customer->getId(); + + $action = new InitializeOrderTunnel($tunnelService); + + // WHEN + $action(new InitializeOrderTunnelInput($basket, $shopperId)); + + // THEN + $storedBuilder = $builderManager->get(); + expect($storedBuilder)->toBeInstanceOf(OrderBuilderWithBasket::class) + ->and($storedBuilder?->getShopperId()->equals($shopperId))->toBeTrue() + ->and($storedBuilder?->getBasket()->countItems())->toBe(2); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php new file mode 100644 index 00000000..48ef9267 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -0,0 +1,520 @@ +forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'email' => new Email('buyer-' . uniqid() . '@example.com'), + 'hashcode' => new CrmHashcode(UuidHelper::v4()), + ]); + + /** @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 \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(); + + $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); + + $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); + $builderManager->save($builder); + + $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), + new DatabaseTunnelAttemptTrackerService($session, 'order_tunnel_attempt_id'), + ); + + $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 PENDING order + $placeOutput = $ctx['executor']->execute($placeAction, new PlacePendingOrderInput($ctx['customer']->getId())); + + // 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::PENDING); + 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('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); + $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']); + $failAction = new FailPendingOrder($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)); + $failOutput = $ctx['executor']->execute($failAction, new FailPendingOrderInput($orderId)); + + // THEN + expect($exportOutput)->toBe(ExportOrderToRegateOutput::FAILED) + ->and($failOutput)->toBe(FailPendingOrderOutput::FAILED); + + $persistedOrder = Order::query()->find($orderId->value->toString()); + expect($persistedOrder?->status)->toBe(OrderStatus::FAILED) + ->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 PENDING orders toward weekly limit to prevent concurrent overspending', function (): void { + // GIVEN + $ctx = buildOrderPlacementScenario(priceCents: 6000, qty: 1); + + Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'shop_id' => $ctx['shop']->id, + 'reference' => new OrderReference(UuidHelper::v7()), + 'status' => OrderStatus::PENDING->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); + }); + + it('executes ExportOrderToRegate without opening a DB transaction and returns LOCK_TIMEOUT when lock fails', function (): void { + // GIVEN + $orderId = new OrderId(UuidHelper::v7()); + $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/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php new file mode 100644 index 00000000..3aa9d435 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Orders/ReleaseTodayOrderReminderTest.php @@ -0,0 +1,60 @@ +create(); + $order = Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(UuidHelper::v7()), + '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/Pages/UpdatePageTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Pages/UpdatePageTest.php similarity index 97% rename from tests/Integration/WithApp/App/Actions/Pages/UpdatePageTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Pages/UpdatePageTest.php index fb1890a4..7039b5ae 100644 --- a/tests/Integration/WithApp/App/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/Actions/PickupExceptions/CreatePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php similarity index 78% rename from tests/Integration/WithApp/App/Actions/PickupExceptions/CreatePickupExceptionTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php index af1f77c0..a0ecc755 100644 --- a/tests/Integration/WithApp/App/Actions/PickupExceptions/CreatePickupExceptionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionTest.php @@ -2,14 +2,13 @@ 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; 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 () { @@ -26,8 +25,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) @@ -43,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/Actions/PickupExceptions/DeletePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php similarity index 78% rename from tests/Integration/WithApp/App/Actions/PickupExceptions/DeletePickupExceptionTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php index e04f2607..53e6b377 100644 --- a/tests/Integration/WithApp/App/Actions/PickupExceptions/DeletePickupExceptionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/DeletePickupExceptionTest.php @@ -2,13 +2,12 @@ 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; 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 () { @@ -35,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/Actions/PickupExceptions/UpdatePickupExceptionTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php similarity index 86% rename from tests/Integration/WithApp/App/Actions/PickupExceptions/UpdatePickupExceptionTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php index 709f022d..f963716c 100644 --- a/tests/Integration/WithApp/App/Actions/PickupExceptions/UpdatePickupExceptionTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionTest.php @@ -2,14 +2,13 @@ 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; 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 () { @@ -55,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/PickupExceptions/UpsertShopsPickupExceptionsForYearTest.php b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpsertShopsPickupExceptionsForYearTest.php new file mode 100644 index 00000000..0fc51eac --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/PickupExceptions/UpsertShopsPickupExceptionsForYearTest.php @@ -0,0 +1,104 @@ +count(2)->create(); + $holidays = [ + new PublicHolidayDto(CarbonImmutable::parse('2026-01-01', 'Europe/Paris'), '1er janvier'), + new PublicHolidayDto(CarbonImmutable::parse('2026-12-25', 'Europe/Paris'), 'Jour de Noël'), + ]; + + $action = new UpsertShopsPickupExceptionsForYear(); + $input = new UpsertShopsPickupExceptionsForYearInput(2026, $holidays); + + // WHEN + $action($input); + + // THEN + expect(PickupException::query()->count())->toBe(2); + $newYear = PickupException::query()->where('label', '1er janvier')->first(); + 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) + ->and($newYear?->auto_updated)->toBeTrue() + ->and($shops->first()?->pickupExceptions()->count())->toBe(2) + ->and($shops->last()?->pickupExceptions()->count())->toBe(2); + }); + + it('does not overwrite previous year holidays when importing a new year and preserves shop associations', function (): void { + // GIVEN + $shop = Shop::factory()->create(); + + $armistice2026 = PickupException::factory()->create([ + 'date' => '2026-11-11', + 'label' => 'Armistice', + 'repeatable' => true, + 'repeat_frequency' => RepeatFrequency::YEARLY, + 'auto_updated' => true, + ]); + $christmas2026 = PickupException::factory()->create([ + 'date' => '2026-12-25', + 'label' => 'Jour de Noël', + 'repeatable' => true, + 'repeat_frequency' => RepeatFrequency::YEARLY, + 'auto_updated' => true, + ]); + $shop->pickupExceptions()->attach([$armistice2026->id, $christmas2026->id]); + + $holidays = [ + new PublicHolidayDto(CarbonImmutable::parse('2027-11-11', 'Europe/Paris'), 'Armistice'), + new PublicHolidayDto(CarbonImmutable::parse('2027-12-25', 'Europe/Paris'), 'Jour de Noël'), + ]; + + $action = new UpsertShopsPickupExceptionsForYear(); + $input = new UpsertShopsPickupExceptionsForYearInput(2027, $holidays); + + // WHEN + $action($input); + + // THEN + expect(PickupException::query()->count())->toBe(4) + ->and(PickupException::query()->whereYear('date', 2026)->count())->toBe(2) + ->and(PickupException::query()->whereYear('date', 2027)->count())->toBe(2) + ->and($armistice2026->fresh()?->date?->format('Y-m-d'))->toBe('2026-11-11') + ->and($christmas2026->fresh()?->date?->format('Y-m-d'))->toBe('2026-12-25') + ->and($shop->pickupExceptions()->count())->toBe(4); + }); + + it('rejects years before 2026 in input', function (): void { + // GIVEN / WHEN / THEN + expect(fn () => new UpsertShopsPickupExceptionsForYearInput(2025, [])) + ->toThrow(\InvalidArgumentException::class); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $action = new UpsertShopsPickupExceptionsForYear(); + $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/ProductIncos/AssociateProductIncoTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php similarity index 65% rename from tests/Integration/WithApp/App/Actions/ProductIncos/AssociateProductIncoTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php index d080856a..733f3b37 100644 --- a/tests/Integration/WithApp/App/Actions/ProductIncos/AssociateProductIncoTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/AssociateProductIncoTest.php @@ -2,10 +2,13 @@ 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; use App\Dto\ArcadiaIncoDataDto; +use App\Enums\ProductIncoSyncStatus; use App\Models\Product; use App\Models\ProductInco; use App\Models\Range; @@ -17,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(); @@ -81,22 +81,23 @@ describe('AssociateProductInco action', function (): void { ->andReturn($incoData); $action = new AssociateProductInco($arcadiaService); - $input = new AssociateProductIncoInput(product: $product, no_art: 27996); + $input = new AssociateProductIncoInput(productId: $product->getId(), no_art: 27996); // WHEN - $result = $action($input); + $output = $action($input); // THEN - expect($result)->toBeInstanceOf(ProductInco::class) - ->and($result->product_id)->toBe($product->id) - ->and($result->no_art)->toBe(27996) - ->and($result->ingredients)->toBe('

Poulet (100%)

') - ->and($result->preparation)->toBe('

Au four

') - ->and($result->servings)->toBe('4/5') - ->and($result->allergens)->toBe('Aucun') - ->and($result->selling_argument)->toBe('

Excellence

') - ->and($result->nutriscore)->toBe(Nutriscore::A) - ->and($result->nutrition->kj)->toBe(600.0); + 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) + ->and($output->inco?->ingredients)->toBe('

Poulet (100%)

') + ->and($output->inco?->preparation)->toBe('

Au four

') + ->and($output->inco?->servings)->toBe('4/5') + ->and($output->inco?->allergens)->toBe('Aucun') + ->and($output->inco?->selling_argument)->toBe('

Excellence

') + ->and($output->inco?->nutriscore)->toBe(Nutriscore::A) + ->and($output->inco?->nutrition->kj)->toBe(600.0); expect(ProductInco::query()->where('product_id', $product->id)->count())->toBe(1); }); @@ -134,19 +135,20 @@ describe('AssociateProductInco action', function (): void { ->andReturn($newIncoData); $action = new AssociateProductInco($arcadiaService); - $input = new AssociateProductIncoInput(product: $product, no_art: 22222); + $input = new AssociateProductIncoInput(productId: $product->getId(), no_art: 22222); // WHEN - $newInco = $action($input); + $output = $action($input); // THEN - expect($newInco->no_art)->toBe(22222); + expect($output->status)->toBe(ProductIncoSyncStatus::SUCCESS) + ->and($output->inco?->no_art)->toBe(22222); expect(ProductInco::query()->where('id', $oldInco->id)->exists())->toBeFalse(); expect(ProductInco::query()->where('product_id', $product->id)->count())->toBe(1); expect(ProductInco::query()->where('product_id', $product->id)->first()?->no_art)->toBe(22222); }); - it('throws when INCO sheet is not found on Arcadia', function () use ($createProduct): void { + it('returns NOT_FOUND_ON_ARCADIA output when INCO sheet is not found on Arcadia', function () use ($createProduct): void { // GIVEN $product = $createProduct(); $arcadiaService = \Mockery::mock(ArcadiaIncoService::class); @@ -156,10 +158,36 @@ describe('AssociateProductInco action', function (): void { ->andReturnNull(); $action = new AssociateProductInco($arcadiaService); - $input = new AssociateProductIncoInput(product: $product, no_art: 99999); + $input = new AssociateProductIncoInput(productId: $product->getId(), no_art: 99999); - // WHEN & THEN - expect(fn () => $action($input))->toThrow(\RuntimeException::class); + // WHEN + $output = $action($input); + + // THEN + expect($output->status)->toBe(ProductIncoSyncStatus::NOT_FOUND_ON_ARCADIA) + ->and($output->inco)->toBeNull() + ->and($output->errorMessage)->toBe('INCO sheet #99999 was not found on Arcadia API.'); + }); + + it('returns API_ERROR output when Arcadia API throws RuntimeException', function () use ($createProduct): void { + // GIVEN + $product = $createProduct(); + $arcadiaService = \Mockery::mock(ArcadiaIncoService::class); + $arcadiaService->shouldReceive('fetchInco') + ->once() + ->with(88888) + ->andThrow(new \RuntimeException('Arcadia unavailable')); + + $action = new AssociateProductInco($arcadiaService); + $input = new AssociateProductIncoInput(productId: $product->getId(), no_art: 88888); + + // WHEN + $output = $action($input); + + // THEN + expect($output->status)->toBe(ProductIncoSyncStatus::API_ERROR) + ->and($output->inco)->toBeNull() + ->and($output->errorMessage)->toBe('Arcadia unavailable'); }); it('throws when invalid input is passed', function (): void { @@ -170,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/ProductIncos/SyncProductIncoTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php new file mode 100644 index 00000000..9ad307d7 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SyncProductIncoTest.php @@ -0,0 +1,163 @@ +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(); + + return $product; + }; + + it('synchronizes an existing product INCO sheet', function () use ($createProduct): void { + // GIVEN + $product = $createProduct(); + $inco = new ProductInco(); + $inco->no_art = 27996; + $inco->product()->associate($product); + $inco->save(); + + $arcadiaService = \Mockery::mock(ArcadiaIncoService::class); + $incoData = new ArcadiaIncoDataDto( + noArt: 27996, + name: 'POULET FERMIER', + libelle: 'Poulet Fermier', + brand: 'Loué', + ingredients: '

MAJ

', + preparation: '

Four

', + servings: '4', + allergens: 'Aucun', + sellingArgument: null, + nutriscore: Nutriscore::A, + nutriscoreArgs: null, + nutrition: new NutritionalValues(refWeightG: 100.0, kj: 650.0, kcal: 155.0), + ); + $arcadiaService->shouldReceive('fetchInco') + ->once() + ->with(27996) + ->andReturn($incoData); + + $action = new SyncProductInco($arcadiaService); + $input = new SyncProductIncoInput(productId: $product->getId()); + + // WHEN + $output = $action($input); + + // THEN + expect($output->status)->toBe(ProductIncoSyncStatus::SUCCESS) + ->and($output->inco?->ingredients)->toBe('

MAJ

'); + }); + + it('returns NOT_ASSOCIATED when product has no associated INCO sheet', function () use ($createProduct): void { + // GIVEN + $product = $createProduct(); + $arcadiaService = \Mockery::mock(ArcadiaIncoService::class); + $action = new SyncProductInco($arcadiaService); + $input = new SyncProductIncoInput(productId: $product->getId()); + + // WHEN + $output = $action($input); + + // THEN + expect($output->status)->toBe(ProductIncoSyncStatus::NOT_ASSOCIATED) + ->and($output->inco)->toBeNull() + ->and($output->errorMessage)->toBe('Product does not have an associated INCO sheet to sync.'); + }); + + it('returns NOT_FOUND_ON_ARCADIA when sheet is missing on Arcadia API', function () use ($createProduct): void { + // GIVEN + $product = $createProduct(); + $inco = new ProductInco(); + $inco->no_art = 99999; + $inco->product()->associate($product); + $inco->save(); + + $arcadiaService = \Mockery::mock(ArcadiaIncoService::class); + $arcadiaService->shouldReceive('fetchInco') + ->once() + ->with(99999) + ->andReturnNull(); + + $action = new SyncProductInco($arcadiaService); + $input = new SyncProductIncoInput(productId: $product->getId()); + + // WHEN + $output = $action($input); + + // THEN + expect($output->status)->toBe(ProductIncoSyncStatus::NOT_FOUND_ON_ARCADIA) + ->and($output->inco)->toBeNull() + ->and($output->errorMessage)->toBe('INCO sheet #99999 was not found on Arcadia API.'); + }); + + it('returns API_ERROR when Arcadia API throws RuntimeException', function () use ($createProduct): void { + // GIVEN + $product = $createProduct(); + $inco = new ProductInco(); + $inco->no_art = 27996; + $inco->product()->associate($product); + $inco->save(); + + $arcadiaService = \Mockery::mock(ArcadiaIncoService::class); + $arcadiaService->shouldReceive('fetchInco') + ->once() + ->with(27996) + ->andThrow(new \RuntimeException('Connection refused')); + + $action = new SyncProductInco($arcadiaService); + $input = new SyncProductIncoInput(productId: $product->getId()); + + // WHEN + $output = $action($input); + + // THEN + expect($output->status)->toBe(ProductIncoSyncStatus::API_ERROR) + ->and($output->inco)->toBeNull() + ->and($output->errorMessage)->toBe('Connection refused'); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php similarity index 58% rename from tests/Integration/WithApp/App/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php index c139e76f..563cb707 100644 --- a/tests/Integration/WithApp/App/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php @@ -2,12 +2,15 @@ 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; 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,11 +19,14 @@ 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 Illuminate\Cache\ArrayStore; +use Illuminate\Cache\Repository as CacheRepository; +use Illuminate\Support\Facades\DB; +use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; +use Infrastructure\Adapters\Locks\LaravelCacheLock; use Money\Money; use Psr\Log\LoggerInterface; - -uses(RefreshDatabase::class); +use Psr\Log\NullLogger; describe('SynchronizeProductIncosWithArcadiaApi action', function (): void { $createProductWithInco = function (int $noArt): ProductInco { @@ -122,4 +128,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/Cqs/Actions/Products/CreateProductTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php new file mode 100644 index 00000000..a8df85d1 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Products/CreateProductTest.php @@ -0,0 +1,253 @@ +name = 'Gamme Produit ' . uniqid(); + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + return $range; +} + +describe('CreateProduct action', function (): void { + it('creates a product with tags, associated products, and S3 pictures', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $range = makeCreateProductRange(); + + $existingTag = Tag::factory()->create([ + 'label' => 'Déjà existant', + 'status' => true, + ]); + + $associated1 = new Product([ + 'range_id' => $range->id, + 'name' => 'Associé 1 ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_5_5, + 'description' => 'Desc 1', + 'status' => true, + ]); + $associated1->price = Money::EUR(500); + $associated1->picture_alt = 'a1'; + $associated1->picture_title = 't1'; + $associated1->picture_large_alt = 'al1'; + $associated1->picture_large_title = 'tl1'; + $associated1->saveOrFail(); + + $associated2 = new Product([ + 'range_id' => $range->id, + 'name' => 'Associé 2 ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_5_5, + 'description' => 'Desc 2', + 'status' => true, + ]); + $associated2->price = Money::EUR(700); + $associated2->picture_alt = 'a2'; + $associated2->picture_title = 't2'; + $associated2->picture_large_alt = 'al2'; + $associated2->picture_large_title = 'tl2'; + $associated2->saveOrFail(); + + $disk = new PublicS3Disk('https://cdn.test'); + $picturePath = new StorageFilePath('products/create-pic.jpg'); + $largePath = new StorageFilePath('products/create-large.jpg'); + + /** @var \Uwil\Storage\Contracts\StorageService&\Mockery\MockInterface $storage */ + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeFileOntoDisk') + ->twice() + ->andReturn($picturePath, $largePath); + $storage->shouldNotReceive('removeFromDisk'); + + $action = new CreateProduct( + $storage, + $disk, + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); + + $orderableStart = CarbonImmutable::parse('2026-11-01 08:00:00'); + $orderableEnd = CarbonImmutable::parse('2026-12-31 20:00:00'); + + $input = new CreateProductInput( + name: 'Poulet Fermier Bio', + shortDescription: 'Courte description', + description: '

Description complète

', + price: Money::EUR(1990), + invoicingUnit: InvoicingUnit::KGM, + stock: 15, + rangeId: $range->id, + sellUnit: SellUnit::PCE, + orderUnit: OrderUnit::COLIS, + taxRate: TaxRate::TVA_5_5, + brand: ProductBrand::loue, + weight: 1400, + weightVariable: true, + orderableStart: $orderableStart, + orderableEnd: $orderableEnd, + star: true, + status: true, + picture: UploadedFile::fake()->image('pic.jpg', 300, 300), + pictureAlt: 'Alt pic', + pictureTitle: 'Title pic', + pictureLarge: UploadedFile::fake()->image('large.jpg', 800, 800), + pictureLargeAlt: 'Alt large', + pictureLargeTitle: 'Title large', + tags: [ + ['id' => $existingTag->id, 'label' => $existingTag->label], + ['label' => 'Nouveau Tag Bio'], + ], + associatedProductsIds: [$associated2->id, $associated1->id], + ); + + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN + $product = $executor->execute($action, $input); + + // THEN + expect($product->name)->toBe('Poulet Fermier Bio') + ->and($product->price->getAmount())->toBe('1990') + ->and($product->stock)->toBe(15) + ->and($product->weight)->toBe(1400) + ->and($product->weight_variable)->toBeTrue() + ->and($product->star)->toBeTrue() + ->and($product->status)->toBeTrue() + ->and($product->picture?->value)->toBe('products/create-pic.jpg') + ->and($product->picture_large?->value)->toBe('products/create-large.jpg') + ->and($product->tags()->pluck('label')->all())->toBe(['Déjà existant', 'Nouveau Tag Bio']); + + $associatedOrder = $product->products + ->pluck('id') + ->all(); + expect($associatedOrder)->toBe([$associated2->id, $associated1->id]); + + $this->assertDatabaseHas('products', [ + 'id' => $product->id, + 'name' => 'Poulet Fermier Bio', + 'range_id' => $range->id, + ]); + }); + + it('cleans up uploaded S3 files when persistence fails inside executor transaction', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $disk = new PublicS3Disk('https://cdn.test'); + $orphanPic = new StorageFilePath('products/orphan-pic.jpg'); + $orphanLarge = new StorageFilePath('products/orphan-large.jpg'); + + /** @var \Uwil\Storage\Contracts\StorageService&\Mockery\MockInterface $storage */ + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeFileOntoDisk') + ->twice() + ->andReturn($orphanPic, $orphanLarge); + $storage->shouldReceive('fileExistsOnDisk') + ->once() + ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/orphan-pic.jpg'), $disk->disk) + ->andReturnTrue(); + $storage->shouldReceive('removeFromDisk') + ->once() + ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/orphan-pic.jpg'), $disk->disk) + ->andReturnTrue(); + $storage->shouldReceive('fileExistsOnDisk') + ->once() + ->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, + ) + ->andReturnTrue(); + + $action = new CreateProduct( + $storage, + $disk, + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); + + // Non-existent rangeId triggers FK constraint violation on saveOrFail() + $input = new CreateProductInput( + name: 'Produit Échec FK', + shortDescription: 'Court', + description: 'Description', + price: Money::EUR(1000), + invoicingUnit: InvoicingUnit::PCE, + stock: 1, + rangeId: 999999, + sellUnit: SellUnit::PCE, + orderUnit: OrderUnit::PCE, + taxRate: TaxRate::TVA_20, + brand: ProductBrand::loue, + picture: UploadedFile::fake()->image('pic.jpg', 200, 200), + pictureAlt: 'alt', + pictureTitle: 'title', + pictureLarge: UploadedFile::fake()->image('large.jpg', 400, 400), + pictureLargeAlt: 'alt large', + pictureLargeTitle: 'title large', + ); + + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN & THEN + expect(fn () => $executor->execute($action, $input)) + ->toThrow(QueryException::class); + + $this->assertDatabaseMissing('products', [ + 'name' => 'Produit Échec FK', + ]); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Products/DeleteProductTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Products/DeleteProductTest.php new file mode 100644 index 00000000..49fd2462 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Products/DeleteProductTest.php @@ -0,0 +1,73 @@ +name = 'Gamme Suppression ' . uniqid(); + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $product = new Product([ + 'range_id' => $range->id, + 'name' => 'Produit À Archiver', + '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(1200); + $product->short_description = 'Court'; + $product->picture = new StorageFilePath('products/keep-after-soft-delete.jpg'); + $product->picture_large = new StorageFilePath('products/keep-large-after-soft-delete.jpg'); + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt large'; + $product->picture_large_title = 'title large'; + $product->saveOrFail(); + + /** @var \Uwil\Storage\Contracts\StorageService&\Mockery\MockInterface $storage */ + $storage = $this->mock(StorageService::class); + $storage->shouldNotReceive('fileExistsOnDisk'); + $storage->shouldNotReceive('removeFromDisk'); + + $action = new DeleteProduct(); + + // WHEN + $deleted = $action(new DeleteProductInput($product->getId())); + + // THEN + expect($deleted)->toBeTrue() + ->and(Product::query()->find($product->id))->toBeNull(); + + $trashed = Product::query()->withTrashed()->find($product->id); + expect($trashed)->not->toBeNull() + ->and($trashed?->deleted_at)->not->toBeNull() + ->and($trashed?->picture?->value)->toBe('products/keep-after-soft-delete.jpg') + ->and($trashed?->picture_large?->value)->toBe('products/keep-large-after-soft-delete.jpg'); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Products/UpdateProductTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Products/UpdateProductTest.php new file mode 100644 index 00000000..a2affc95 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Products/UpdateProductTest.php @@ -0,0 +1,193 @@ +name = 'Gamme Test ' . uniqid(); + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $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', + 'status' => true, + ]); + $product->price = Money::EUR(1500); + $product->short_description = 'Court'; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt large'; + $product->picture_large_title = 'title large'; + if ($picture !== null) { + $product->picture = $picture; + } + if ($pictureLarge !== null) { + $product->picture_large = $pictureLarge; + } + $product->saveOrFail(); + + return $product; +} + +describe('UpdateProduct action', function (): void { + it('deletes previous S3 images when replacing picture and picture_large', function (): void { + // GIVEN + $oldPicture = new StorageFilePath('products/old-pic.jpg'); + $oldPictureLarge = new StorageFilePath('products/old-large.jpg'); + $newPicture = new StorageFilePath('products/new-pic.jpg'); + $newPictureLarge = new StorageFilePath('products/new-large.jpg'); + + $product = makeUpdateProductFixture($oldPicture, $oldPictureLarge); + $disk = new PublicS3Disk('https://cdn.test'); + + /** @var \Uwil\Storage\Contracts\StorageService&\Mockery\MockInterface $storage */ + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeFileOntoDisk') + ->twice() + ->andReturn($newPicture, $newPictureLarge); + $storage->shouldReceive('fileExistsOnDisk') + ->once() + ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/old-pic.jpg'), $disk->disk) + ->andReturnTrue(); + $storage->shouldReceive('removeFromDisk') + ->once() + ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/old-pic.jpg'), $disk->disk) + ->andReturnTrue(); + $storage->shouldReceive('fileExistsOnDisk') + ->once() + ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/old-large.jpg'), $disk->disk) + ->andReturnTrue(); + $storage->shouldReceive('removeFromDisk') + ->once() + ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/old-large.jpg'), $disk->disk) + ->andReturnTrue(); + + $action = new UpdateProduct( + new PublicImageStorageService( + $storage, + $disk, + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ), + ); + + $input = new UpdateProductInput( + productId: $product->getId(), + name: $product->name, + shortDescription: 'Nouveau court', + description: 'Nouvelle description', + price: Money::EUR(2000), + invoicingUnit: InvoicingUnit::PCE, + stock: 5, + rangeId: $product->range_id, + sellUnit: SellUnit::PCE, + orderUnit: OrderUnit::PCE, + taxRate: TaxRate::TVA_20, + brand: ProductBrand::loue, + picture: UploadedFile::fake()->image('new-pic.jpg', 300, 300), + pictureAlt: 'alt', + pictureTitle: 'title', + pictureLarge: UploadedFile::fake()->image('new-large.jpg', 800, 800), + pictureLargeAlt: 'alt large', + pictureLargeTitle: 'title large', + ); + + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN + $updated = $executor->execute($action, $input); + + // THEN + expect($updated->picture?->value)->toBe('products/new-pic.jpg') + ->and($updated->picture_large?->value)->toBe('products/new-large.jpg'); + }); + + it('keeps existing S3 images untouched when no new files are uploaded', function (): void { + // GIVEN + $existingPicture = new StorageFilePath('products/keep-pic.jpg'); + $existingPictureLarge = new StorageFilePath('products/keep-large.jpg'); + $product = makeUpdateProductFixture($existingPicture, $existingPictureLarge); + + /** @var \Uwil\Storage\Contracts\StorageService&\Mockery\MockInterface $storage */ + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $storage->shouldNotReceive('fileExistsOnDisk'); + $storage->shouldNotReceive('removeFromDisk'); + + $action = new UpdateProduct( + new PublicImageStorageService( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ), + ); + + $input = new UpdateProductInput( + productId: $product->getId(), + name: $product->name, + shortDescription: 'Court', + description: 'Description', + price: Money::EUR(1800), + invoicingUnit: InvoicingUnit::PCE, + stock: 3, + rangeId: $product->range_id, + sellUnit: SellUnit::PCE, + orderUnit: OrderUnit::PCE, + taxRate: TaxRate::TVA_20, + brand: ProductBrand::loue, + pictureAlt: 'alt', + pictureTitle: 'title', + pictureLargeAlt: 'alt large', + pictureLargeTitle: 'title large', + ); + + // WHEN + $updated = $action($input); + + // THEN + expect($updated->picture?->value)->toBe('products/keep-pic.jpg') + ->and($updated->picture_large?->value)->toBe('products/keep-large.jpg'); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php new file mode 100644 index 00000000..15d128cf --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/CreateRangeTest.php @@ -0,0 +1,136 @@ +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

', + picture: UploadedFile::fake()->image('range.jpg', 500, 500), + pictureMetadata: new PictureMetadata(alt: 'Image alt range', title: 'Image title range'), + status: true, + ); + + // WHEN + $range = $action($input); + + // THEN + 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') + ->and($range->picture_title)->toBe('Image title range') + ->and($range->status)->toBeTrue() + ->and($range->exists)->toBeTrue(); + + $this->assertDatabaseHas('ranges', [ + 'id' => $range->id, + 'name' => 'Gamme Décoration', + 'slug' => 'gamme-decoration', + ]); + }); + + test('it throws when an invalid input is passed', function () { + // GIVEN + $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 + { + }; + + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + + // WHEN & THEN + expect(fn () => $callable($invalidInput)) + ->toThrow(\InvalidArgumentException::class); + }); + + test('it cleans up uploaded S3 picture when SQL persistence rolls back', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + $existing = new Range(); + $existing->name = 'Gamme Existante'; + $existing->picture_alt = 'Alt'; + $existing->picture_title = 'Title'; + $existing->status = true; + $existing->save(); + + $disk = new PublicS3Disk('https://cdn.test'); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeFileOntoDisk') + ->once() + ->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, + ) + ->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, + ) + ->andReturnTrue(); + + $action = new CreateRange( + $storage, + $disk, + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); + $input = new CreateRangeInput( + name: 'Gamme Existante', + description: 'Duplicate trigger', + picture: UploadedFile::fake()->image('range.jpg', 500, 500), + pictureMetadata: new PictureMetadata(alt: 'Alt valide', title: 'Titre valide'), + status: true, + ); + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN & THEN + expect(fn () => $executor->execute($action, $input))->toThrow(\Exception::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php new file mode 100644 index 00000000..7719010c --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/DeleteRangeTest.php @@ -0,0 +1,119 @@ +name = 'Gamme Temporaire'; + $range->picture_alt = 'Alt'; + $range->picture_title = 'Title'; + $range->status = true; + $range->save(); + + // 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 + $result = $action($input); + + // THEN + expect($result)->toBeTrue(); + $this->assertDatabaseMissing('ranges', [ + 'id' => $range->id, + ]); + }); + + 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')); + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN + $result = $executor->execute($action, new DeleteRangeInput(range: $range)); + + // THEN + expect($result)->toBeTrue(); + $this->assertDatabaseMissing('ranges', ['id' => $range->id]); + }); + + test('it preserves S3 picture when DeleteRange triggers failure hook before commit', function (): void { + // GIVEN + $range = new Range(); + $range->name = 'Gamme Protégée'; + $range->picture_alt = 'Alt'; + $range->picture_title = 'Title'; + $range->status = true; + $range->picture = new StorageFilePath('media/keep-range.jpg'); + $range->save(); + + /** @var StorageService&\Mockery\MockInterface $storage */ + $storage = \Mockery::spy(StorageService::class); + + $action = new DeleteRange($storage, new PublicS3Disk('https://cdn.test')); + $input = new DeleteRangeInput(range: $range); + + // WHEN + $action($input); + $action->onFailure($input, new \RuntimeException('Simulated rollback')); + + // THEN + expect(Range::query()->find($range->id))->toBeNull(); + $storage->shouldNotHaveReceived('fileExistsOnDisk'); + $storage->shouldNotHaveReceived('removeFromDisk'); + }); + + test('it throws when an invalid input is passed', function () { + // GIVEN + $storage = \Mockery::mock(StorageService::class); + $action = new DeleteRange($storage, new PublicS3Disk('https://cdn.test')); + $invalidInput = new class () implements ActionInput + { + }; + + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + + // WHEN & THEN + 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 new file mode 100644 index 00000000..6756cdfa --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Ranges/UpdateRangeTest.php @@ -0,0 +1,219 @@ +name = 'Gamme Initiale'; + $range->description = 'Ancien contenu'; + $range->picture_alt = 'Ancien alt'; + $range->picture_title = 'Ancien title'; + $range->status = true; + $range->save(); + + // 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( + new PublicImageStorageService( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ), + ); + $input = new UpdateRangeInput( + range: $range, + name: 'Gamme Renommée', + description: 'Nouveau contenu', + picture: UploadedFile::fake()->image('new-range.jpg', 500, 500), + pictureMetadata: new PictureMetadata(alt: 'Nouveau alt', title: 'Nouveau title'), + status: false, + ); + + // WHEN + $updatedRange = $action($input); + + // THEN + expect($updatedRange->id)->toBe($range->id) + ->and($updatedRange->name)->toBe('Gamme Renommée') + ->and($updatedRange->slug)->toBe('gamme-renommee') + ->and($updatedRange->description)->toBe('Nouveau contenu') + ->and($updatedRange->picture_alt)->toBe('Nouveau alt') + ->and($updatedRange->picture_title)->toBe('Nouveau title') + ->and($updatedRange->status)->toBeFalse(); + + $this->assertDatabaseHas('ranges', [ + 'id' => $range->id, + 'name' => 'Gamme Renommée', + 'status' => 0, + ]); + }); + + test('it deletes previous S3 picture when replacing range image', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + $oldPicture = new StorageFilePath('media/old-range.jpg'); + $newPicture = new StorageFilePath('media/new-range.jpg'); + + $range = new Range(); + $range->name = 'Gamme Avec Image'; + $range->description = 'Contenu'; + $range->picture = $oldPicture; + $range->picture_alt = 'Ancien alt'; + $range->picture_title = 'Ancien title'; + $range->status = true; + $range->save(); + + $disk = new PublicS3Disk('https://cdn.test'); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeFileOntoDisk')->once()->andReturn($newPicture); + $storage->shouldReceive('fileExistsOnDisk') + ->once() + ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'media/old-range.jpg'), $disk->disk) + ->andReturnTrue(); + $storage->shouldReceive('removeFromDisk') + ->once() + ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'media/old-range.jpg'), $disk->disk) + ->andReturnTrue(); + + $action = new UpdateRange( + new PublicImageStorageService( + $storage, + $disk, + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ), + ); + $input = new UpdateRangeInput( + range: $range, + name: 'Gamme Avec Nouvelle Image', + description: 'Contenu', + picture: UploadedFile::fake()->image('new-range.jpg', 500, 500), + pictureMetadata: new PictureMetadata(alt: 'Nouveau alt', title: 'Nouveau title'), + status: true, + ); + + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN + $updatedRange = $executor->execute($action, $input); + + // THEN + expect($updatedRange->picture?->value)->toBe('media/new-range.jpg'); + }); + + test('it removes uploaded picture and preserves previous picture on rollback', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + $oldPicture = new StorageFilePath('media/old-range.jpg'); + $newPicture = new StorageFilePath('media/orphan-new-range.jpg'); + + $range = new Range(); + $range->name = 'Gamme Stable'; + $range->description = 'Contenu'; + $range->picture = $oldPicture; + $range->picture_alt = 'Ancien alt'; + $range->picture_title = 'Ancien title'; + $range->status = true; + $range->save(); + + $duplicate = new Range(); + $duplicate->name = 'Nom Déjà Pris'; + $duplicate->picture_alt = 'Alt'; + $duplicate->picture_title = 'Title'; + $duplicate->status = true; + $duplicate->save(); + + $disk = new PublicS3Disk('https://cdn.test'); + $storage = \Mockery::mock(StorageService::class); + $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, + ) + ->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, + ) + ->andReturnTrue(); + + $action = new UpdateRange( + new PublicImageStorageService( + $storage, + $disk, + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ), + ); + $input = new UpdateRangeInput( + range: $range, + name: 'Nom Déjà Pris', + description: 'Contenu', + picture: UploadedFile::fake()->image('new-range.jpg', 500, 500), + pictureMetadata: new PictureMetadata(alt: 'Nouveau alt', title: 'Nouveau title'), + status: true, + ); + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN & THEN + expect(fn () => $executor->execute($action, $input))->toThrow(\Exception::class); + }); + + test('it throws when an invalid input is passed', function () { + // GIVEN + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new UpdateRange( + new PublicImageStorageService( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ), + ); + $invalidInput = new class () implements ActionInput + { + }; + + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + + // WHEN & THEN + expect(fn () => $callable($invalidInput)) + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Settings/UpdateSettingsTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php similarity index 80% rename from tests/Integration/WithApp/App/Actions/Settings/UpdateSettingsTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php index e279a8a8..73c84e4e 100644 --- a/tests/Integration/WithApp/App/Actions/Settings/UpdateSettingsTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Settings/UpdateSettingsTest.php @@ -2,13 +2,12 @@ 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; use Domain\Models\ValueObjects\ShopperSiteCode; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('UpdateSettings', function (): void { it('updates employee sites configuration', function (): void { @@ -25,8 +24,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 new file mode 100644 index 00000000..0f73e66a --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/CreateShopTest.php @@ -0,0 +1,116 @@ +name)->toBe('Boutique Bastille') + ->and($shop->address)->toBe('5 Place de la Bastille') + ->and($shop->postcode)->toBe('75011') + ->and($shop->city)->toBe('Paris') + ->and($shop->phone)->toBe('+33140506070') + ->and((float) $shop->latitude)->toBe(48.8530) + ->and((float) $shop->longitude)->toBe(2.3690) + ->and($shop->default)->toBeTrue() + ->and($shop->exists)->toBeTrue(); + + $this->assertDatabaseHas('shops', [ + 'id' => $shop->id, + 'name' => 'Boutique Bastille', + ]); + }); + + test('it throws when an invalid input is passed', function () { + // GIVEN + $action = new CreateShop(); + $invalidInput = new class () implements ActionInput + { + }; + + /** @var \Closure(\App\Contracts\ActionInput): mixed $callable */ + $callable = \Closure::fromCallable($action); + + // WHEN & THEN + expect(fn () => $callable($invalidInput)) + ->toThrow(\InvalidArgumentException::class); + }); + + test('it automatically attaches synced public holidays for current and future years', function () { + // GIVEN + Date::setTestNow(Date::parse('2026-06-15 10:00:00', 'Europe/Paris')); + + try { + $pastAutoHoliday = PickupException::query()->forceCreate([ + 'date' => '2025-12-25', + 'label' => 'Noël 2025', + 'repeatable' => true, + 'repeat_frequency' => RepeatFrequency::YEARLY, + 'auto_updated' => true, + ]); + $currentAutoHoliday = PickupException::query()->forceCreate([ + 'date' => '2026-07-14', + 'label' => 'Fête Nationale', + 'repeatable' => true, + 'repeat_frequency' => RepeatFrequency::YEARLY, + 'auto_updated' => true, + ]); + $manualException = PickupException::query()->forceCreate([ + 'date' => '2026-08-01', + 'label' => 'Fermeture exceptionnelle', + 'repeatable' => false, + 'repeat_frequency' => RepeatFrequency::WEEKLY, + 'auto_updated' => false, + ]); + + $action = new CreateShop(); + $input = new CreateShopInput( + name: 'Boutique Lyon', + address: '10 Rue de la République', + postcode: '69001', + city: 'Lyon', + phone: null, + coordinates: null, + default: false, + ); + + // WHEN + $shop = $action($input); + + // THEN + $attachedIds = $shop->pickupExceptions()->pluck('pickup_exceptions.id')->all(); + expect($attachedIds)->toContain($currentAutoHoliday->id); + expect($attachedIds)->not->toContain($pastAutoHoliday->id); + expect($attachedIds)->not->toContain($manualException->id); + } finally { + Date::setTestNow(); + } + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Shops/DeleteShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php similarity index 80% rename from tests/Integration/WithApp/App/Actions/Shops/DeleteShopTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php index 0185c097..26712129 100644 --- a/tests/Integration/WithApp/App/Actions/Shops/DeleteShopTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/DeleteShopTest.php @@ -2,13 +2,12 @@ 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; use App\Models\Shop; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('DeleteShop action', function () { test('it deletes a shop from database', function () { @@ -35,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/Actions/Shops/UpdateShopPickupExceptionsTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php similarity index 89% rename from tests/Integration/WithApp/App/Actions/Shops/UpdateShopPickupExceptionsTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php index c4333ceb..8e130c96 100644 --- a/tests/Integration/WithApp/App/Actions/Shops/UpdateShopPickupExceptionsTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsTest.php @@ -2,14 +2,13 @@ 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; 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 () { @@ -59,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/Actions/Shops/UpdateShopTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php similarity index 89% rename from tests/Integration/WithApp/App/Actions/Shops/UpdateShopTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php index dbb9ab51..1ac678b6 100644 --- a/tests/Integration/WithApp/App/Actions/Shops/UpdateShopTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Shops/UpdateShopTest.php @@ -2,15 +2,14 @@ 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; 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 () { @@ -63,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/Actions/Slides/CreateSlideTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Slides/CreateSlideTest.php similarity index 64% rename from tests/Integration/WithApp/App/Actions/Slides/CreateSlideTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Slides/CreateSlideTest.php index 0ae8ff06..0d5f8f41 100644 --- a/tests/Integration/WithApp/App/Actions/Slides/CreateSlideTest.php +++ b/tests/Integration/WithApp/App/Cqs/Actions/Slides/CreateSlideTest.php @@ -2,16 +2,30 @@ 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; +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); @@ -30,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') @@ -46,7 +59,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/Cqs/Actions/Slides/DeleteSlideTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Slides/DeleteSlideTest.php new file mode 100644 index 00000000..ab37793b --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Slides/DeleteSlideTest.php @@ -0,0 +1,100 @@ +title = 'Slide à supprimer'; + $slide->text = '

Contenu

'; + $slide->saveOrFail(); + + // 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); + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN + $result = $executor->execute($action, $input); + + // 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); + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN + $result = $executor->execute($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 + $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 & THEN + expect( + /** @phpstan-ignore argument.type */ + fn () => $action($invalidInput) + )->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlideTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlideTest.php new file mode 100644 index 00000000..7f1e08ce --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlideTest.php @@ -0,0 +1,211 @@ +title = 'Ancien Titre'; + $slide->text = '

Ancien texte

'; + $slide->saveOrFail(); + + // Strict double: no picture in this input, so storeFileOntoDisk must never be touched. + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new UpdateSlide( + new PublicImageStorageService( + $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); + + $input = new UpdateSlideInput( + slide: $slide, + title: 'Titre Mis à Jour', + text: '

Texte mis à jour

', + link: 'https://example.com/updated', + linkLabel: 'Lien mis à jour', + linkNewTab: true, + connected: true, + period: $period, + ); + + // WHEN + $updatedSlide = $action($input); + + // THEN + expect($updatedSlide->id)->toBe($slide->id) + ->and($updatedSlide->title)->toBe('Titre Mis à Jour') + ->and($updatedSlide->text)->toBe('

Texte mis à jour

') + ->and($updatedSlide->link)->toBe('https://example.com/updated') + ->and($updatedSlide->link_label)->toBe('Lien mis à jour') + ->and($updatedSlide->link_new_tab)->toBeTrue() + ->and($updatedSlide->connected)->toBeTrue(); + + $fresh = Slide::query()->find($slide->id); + 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( + new PublicImageStorageService( + $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('deletes previous S3 picture when replacing slide image', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $oldPicture = new StorageFilePath('slides/old-slide.jpg'); + $newPicture = new StorageFilePath('slides/new-slide.jpg'); + + $slide = new Slide(); + $slide->title = 'Ancien Titre'; + $slide->text = '

Ancien texte

'; + $slide->picture = $oldPicture; + $slide->saveOrFail(); + + $disk = new PublicS3Disk('https://cdn.test'); + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeFileOntoDisk')->once()->andReturn($newPicture); + $storage->shouldReceive('fileExistsOnDisk') + ->once() + ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'slides/old-slide.jpg'), $disk->disk) + ->andReturnTrue(); + $storage->shouldReceive('removeFromDisk') + ->once() + ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'slides/old-slide.jpg'), $disk->disk) + ->andReturnTrue(); + + $action = new UpdateSlide( + new PublicImageStorageService( + $storage, + $disk, + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ), + ); + + $input = new UpdateSlideInput( + slide: $slide, + title: 'Titre Mis à Jour', + text: '

Texte

', + picture: UploadedFile::fake()->image('new-slide.jpg', 600, 400), + pictureAlt: 'Nouvel alt', + pictureTitle: 'Nouveau titre', + ); + + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN + $updatedSlide = $executor->execute($action, $input); + + // THEN + expect($updatedSlide->picture?->value)->toBe('slides/new-slide.jpg'); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $storage = \Mockery::mock(StorageService::class); + $storage->shouldNotReceive('storeFileOntoDisk'); + $action = new UpdateSlide( + new PublicImageStorageService( + $storage, + new PublicS3Disk('https://cdn.test'), + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ), + ); + $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/Cqs/Actions/Slides/UpdateSlidesStatusTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlidesStatusTest.php new file mode 100644 index 00000000..5462997d --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Slides/UpdateSlidesStatusTest.php @@ -0,0 +1,95 @@ +addHour(); + $publishEnd = Date::now()->addDay(); + $unpublishStart = Date::now()->subHour(); + $unpublishEnd = Date::now()->addHour(); + + $toPublish = Slide::factory()->create([ + 'date_start' => $publishStart, + 'date_end' => $publishEnd, + ]); + $toUnpublish = Slide::factory()->create([ + 'date_start' => $unpublishStart, + 'date_end' => $unpublishEnd, + ]); + + expect($toPublish->status)->toBeFalse() + ->and($toUnpublish->status)->toBeTrue(); + + Date::setTestNow('2026-11-14 12:00:00'); + $action = new UpdateSlidesStatus(new NullLogger()); + + // WHEN + $action(new ActionInputEmpty()); + + // THEN + $toPublish->refresh(); + $toUnpublish->refresh(); + + expect($toPublish->status)->toBeTrue() + ->and($toPublish->date_start?->format('Y-m-d H:i:s'))->toBe($publishStart->format('Y-m-d H:i:s')) + ->and($toPublish->date_end?->format('Y-m-d H:i:s'))->toBe($publishEnd->format('Y-m-d H:i:s')) + ->and($toUnpublish->status)->toBeFalse() + ->and($toUnpublish->date_start?->format('Y-m-d H:i:s'))->toBe($unpublishStart->format('Y-m-d H:i:s')) + ->and($toUnpublish->date_end?->format('Y-m-d H:i:s'))->toBe($unpublishEnd->format('Y-m-d H:i:s')); + + Date::setTestNow(); + }); + + it('does not re-publish an already expired unpublished slide on subsequent runs', function (): void { + // GIVEN + Date::setTestNow('2026-11-14 10:00:00'); + $expiredSlide = Slide::factory()->create([ + 'date_start' => Date::now()->subDays(3), + 'date_end' => Date::now()->subDay(), + ]); + + expect($expiredSlide->status)->toBeFalse(); + + $action = new UpdateSlidesStatus(new NullLogger()); + + // WHEN + $action(new ActionInputEmpty()); + + // THEN + $expiredSlide->refresh(); + + expect($expiredSlide->status)->toBeFalse() + ->and($expiredSlide->date_start)->not->toBeNull() + ->and($expiredSlide->date_end)->not->toBeNull(); + + Date::setTestNow(); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $action = new UpdateSlidesStatus(new NullLogger()); + $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/Tags/CreateTagTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Tags/CreateTagTest.php similarity index 88% rename from tests/Integration/WithApp/App/Actions/Tags/CreateTagTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Tags/CreateTagTest.php index 0ed3c304..570f5efb 100644 --- a/tests/Integration/WithApp/App/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; @@ -17,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/Actions/Tags/DeleteTagTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Tags/DeleteTagTest.php similarity index 94% rename from tests/Integration/WithApp/App/Actions/Tags/DeleteTagTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Tags/DeleteTagTest.php index e4ff9530..76a72aa9 100644 --- a/tests/Integration/WithApp/App/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/Actions/Tags/UpdateTagTest.php b/tests/Integration/WithApp/App/Cqs/Actions/Tags/UpdateTagTest.php similarity index 95% rename from tests/Integration/WithApp/App/Actions/Tags/UpdateTagTest.php rename to tests/Integration/WithApp/App/Cqs/Actions/Tags/UpdateTagTest.php index 827b41af..e4f3b903 100644 --- a/tests/Integration/WithApp/App/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 new file mode 100644 index 00000000..da186dbc --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Actions/Users/CreateUserTest.php @@ -0,0 +1,54 @@ +firstname)->toBe('Jean') + ->and($user->lastname)->toBe('Dupont') + ->and($user->email)->toBe('jean.dupont@ldc.fr') + ->and($user->role)->toBe(UserRole::Admin) + ->and($user->email_verified_at)->not->toBeNull() + ->and(Hash::check('SecretPassword123!', $user->password))->toBeTrue() + ->and(User::query()->find($user->id))->not->toBeNull(); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $action = new CreateUser(); + $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/Cqs/Queries/Basket/GetBasketQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Basket/GetBasketQueryTest.php new file mode 100644 index 00000000..3513e394 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/Basket/GetBasketQueryTest.php @@ -0,0 +1,173 @@ +id : new BasketId(UuidHelper::v7()); + $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(UuidHelper::fromString($publishedProduct->id)); + $unpublishedId = new ProductId(UuidHelper::fromString($unpublishedProduct->id)); + + $basket = new Basket(new BasketId(UuidHelper::v7()), [ + 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/Queries/Customers/GetCustomerByEmailQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php similarity index 76% rename from tests/Integration/WithApp/App/Queries/Customers/GetCustomerByEmailQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php index 23a4c25f..060033c9 100644 --- a/tests/Integration/WithApp/App/Queries/Customers/GetCustomerByEmailQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Customers/GetCustomerByEmailQueryTest.php @@ -2,26 +2,25 @@ 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; use Domain\Models\ValueObjects\Email; use Domain\Models\ValueObjects\Entities\ShopperId; -use Illuminate\Foundation\Testing\RefreshDatabase; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; use Shared\ValueObjects\CrmHashcode; -uses(RefreshDatabase::class); - describe('GetCustomerByEmailQuery', function (): void { it('returns ShopperId when customer with email exists', 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 = app(GetCustomerByEmailQuery::class); + $query = new GetCustomerByEmailQuery(); $input = new GetCustomerByEmailQueryInput($email); // WHEN @@ -29,13 +28,13 @@ 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 { // GIVEN $email = new Email('nonexistent@example.com'); - $query = app(GetCustomerByEmailQuery::class); + $query = new GetCustomerByEmailQuery(); $input = new GetCustomerByEmailQueryInput($email); // WHEN 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 68% rename from tests/Integration/WithApp/App/Queries/Discounts/GetPaginatedDiscountsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Discounts/GetPaginatedDiscountsQueryTest.php index 0ee7988e..2eab9eea 100644 --- a/tests/Integration/WithApp/App/Queries/Discounts/GetPaginatedDiscountsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Discounts/GetPaginatedDiscountsQueryTest.php @@ -7,15 +7,22 @@ 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; use Domain\Models\ValueObjects\DiscountValue; +use Illuminate\Http\Request; +use Illuminate\Session\NullSessionHandler; +use Illuminate\Session\Store; +use Illuminate\Support\Facades\Schema; use Shared\Pagination\PageNumber; use Shared\Pagination\PageSize; use Shared\Pagination\Pagination; +afterEach(function (): void { + DataTableService::clearColumnsCache(); +}); + describe('GetPaginatedDiscountsQuery', function (): void { it('returns a paginator of DiscountDto instances', function (): void { // GIVEN @@ -31,7 +38,13 @@ describe('GetPaginatedDiscountsQuery', function (): void { $discount2->is_old_price_displayed = false; $discount2->save(); - $query = new GetPaginatedDiscountsQuery(app(DataTableService::class)); + $query = new GetPaginatedDiscountsQuery( + new DataTableService( + Request::create('/'), + new Store('test', new NullSessionHandler()), + static fn (string $table): array => Schema::getColumnListing($table), + ), + ); $input = new GetPaginatedDiscountsQueryInput( pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), ); @@ -41,14 +54,18 @@ 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 { // GIVEN - $query = new GetPaginatedDiscountsQuery(app(DataTableService::class)); + $query = new GetPaginatedDiscountsQuery( + new DataTableService( + Request::create('/'), + new Store('test', new NullSessionHandler()), + static fn (string $table): array => Schema::getColumnListing($table), + ), + ); $invalidInput = new class () implements QueryInput { }; diff --git a/tests/Integration/WithApp/App/Queries/Faqs/GetFaqsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php similarity index 67% rename from tests/Integration/WithApp/App/Queries/Faqs/GetFaqsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php index 3e02f970..1e838f9c 100644 --- a/tests/Integration/WithApp/App/Queries/Faqs/GetFaqsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetFaqsQueryTest.php @@ -2,14 +2,12 @@ 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; use App\Models\Faq; -use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Support\Collection; - -uses(RefreshDatabase::class); describe('GetFaqsQuery', function (): void { it('returns a collection of FaqDto instances ordered by order', function (): void { @@ -26,16 +24,15 @@ describe('GetFaqsQuery', function (): void { $faq1->order = 1; $faq1->save(); - $query = app(GetFaqsQuery::class); + $query = new GetFaqsQuery(); // WHEN $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?'); + ->and($faqs->first()?->question)->toBe('First question?') + ->and($faqs->last()?->question)->toBe('Second question?'); }); }); diff --git a/tests/Integration/WithApp/App/Queries/Faqs/GetPaginatedFaqsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php similarity index 62% rename from tests/Integration/WithApp/App/Queries/Faqs/GetPaginatedFaqsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php index 23e3707b..c340593b 100644 --- a/tests/Integration/WithApp/App/Queries/Faqs/GetPaginatedFaqsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Faqs/GetPaginatedFaqsQueryTest.php @@ -2,14 +2,24 @@ 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; use App\Models\Faq; +use App\Services\DataTableService; +use Illuminate\Http\Request; +use Illuminate\Session\NullSessionHandler; +use Illuminate\Session\Store; +use Illuminate\Support\Facades\Schema; use Shared\Pagination\PageNumber; use Shared\Pagination\PageSize; use Shared\Pagination\Pagination; +afterEach(function (): void { + DataTableService::clearColumnsCache(); +}); + describe('GetPaginatedFaqsQuery', function (): void { it('returns a paginator of FaqDto instances', function (): void { // GIVEN @@ -23,8 +33,13 @@ describe('GetPaginatedFaqsQuery', function (): void { $faq2->answer = 'Second answer.'; $faq2->save(); - /** @var GetPaginatedFaqsQuery $query */ - $query = app(GetPaginatedFaqsQuery::class); + $query = new GetPaginatedFaqsQuery( + new DataTableService( + Request::create('/'), + new Store('test', new NullSessionHandler()), + static fn (string $table): array => Schema::getColumnListing($table), + ), + ); $input = new GetPaginatedFaqsQueryInput( pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), ); @@ -35,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/GetBoPaginatedOrdersQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoPaginatedOrdersQueryTest.php new file mode 100644 index 00000000..af0825fc --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetBoPaginatedOrdersQueryTest.php @@ -0,0 +1,371 @@ +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) UuidHelper::v7($createdAt); + } + $order->reference = new OrderReference(UuidHelper::v7()); + $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); + }); + + 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..63e8dda4 --- /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(UuidHelper::v7()); + $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 new file mode 100644 index 00000000..c60d6e05 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetFoCustomerPaginatedOrdersQueryTest.php @@ -0,0 +1,208 @@ +email = new Email('customer-' . uniqid() . '@example.com'); + $customer->hashcode = new CrmHashcode(UuidHelper::v4()); + $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(UuidHelper::v7()); + $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); + }); + + 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/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php similarity index 78% rename from tests/Integration/WithApp/App/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php index 33c1fb23..402674a6 100644 --- a/tests/Integration/WithApp/App/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php @@ -6,11 +6,9 @@ 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; use Domain\Enums\OrderStatus; use Domain\Enums\OrderTunnelStep; use Domain\Models\ValueObjects\DeliveryAddress; @@ -21,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 { @@ -34,12 +32,12 @@ 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; $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( @@ -58,31 +56,26 @@ describe('GetTunnelOrderConfirmedQuery', function (): void { ); $order->save(); - /** @var GetTunnelOrderConfirmedQuery $query */ - $query = app(GetTunnelOrderConfirmedQuery::class); + $query = new GetTunnelOrderConfirmedQuery(new MapUrlService()); $input = new GetTunnelOrderConfirmedQueryInput($order); // WHEN $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 { // GIVEN - $reference = new OrderReference(Uuid::uuid7()); + $reference = new OrderReference(UuidHelper::v7()); $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( @@ -101,8 +94,7 @@ describe('GetTunnelOrderConfirmedQuery', function (): void { ); $order->save(); - /** @var GetTunnelOrderConfirmedQuery $query */ - $query = app(GetTunnelOrderConfirmedQuery::class); + $query = new GetTunnelOrderConfirmedQuery(new MapUrlService()); $input = new GetTunnelOrderConfirmedQueryInput($order); // WHEN & THEN diff --git a/tests/Integration/WithApp/App/Queries/Pages/GetPageBySlugQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php similarity index 81% rename from tests/Integration/WithApp/App/Queries/Pages/GetPageBySlugQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php index 598a16fc..ccbfe937 100644 --- a/tests/Integration/WithApp/App/Queries/Pages/GetPageBySlugQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Pages/GetPageBySlugQueryTest.php @@ -2,9 +2,10 @@ 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; use App\Models\Page; use Domain\Enums\StaticPageSlug; use Domain\Models\ValueObjects\Slug; @@ -21,15 +22,13 @@ describe('GetPageBySlugQuery', function (): void { $page->content = '

Contenu des mentions légales

'; $page->save(); - /** @var GetPageQuery $query */ - $query = app(GetPageQuery::class); + $query = new GetPageQuery(); // WHEN $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'); @@ -45,22 +44,19 @@ describe('GetPageBySlugQuery', function (): void { $page->content = '

Contenu CGV

'; $page->save(); - /** @var GetPageQuery $query */ - $query = app(GetPageQuery::class); + $query = new GetPageQuery(); // WHEN $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); }); it('throws ModelNotFoundException when page does not exist', function (): void { // GIVEN - /** @var GetPageQuery $query */ - $query = app(GetPageQuery::class); + $query = new GetPageQuery(); // WHEN expect(fn () => $query(new GetPageQueryInput(new Slug('non-existent-slug')))) diff --git a/tests/Integration/WithApp/App/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php similarity index 59% rename from tests/Integration/WithApp/App/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php index 561ec7c1..2c61bede 100644 --- a/tests/Integration/WithApp/App/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php @@ -2,25 +2,34 @@ 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; 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; +use Illuminate\Session\Store; +use Illuminate\Support\Facades\Schema; use Shared\Pagination\PageNumber; use Shared\Pagination\PageSize; use Shared\Pagination\Pagination; -uses(RefreshDatabase::class); +afterEach(function (): void { + DataTableService::clearColumnsCache(); +}); describe('GetPaginatedPickupExceptionsQuery', function () { test('it executes and returns paginated pickup exception DTOs', function () { // GIVEN PickupException::factory()->count(3)->create(); - $dataTableService = resolve(DataTableService::class); + $dataTableService = new DataTableService( + Request::create('/'), + new Store('test', new NullSessionHandler()), + static fn (string $table): array => Schema::getColumnListing($table), + ); $query = new GetPaginatedPickupExceptionsQuery($dataTableService); $input = new GetPaginatedPickupExceptionsQueryInput( pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), @@ -30,9 +39,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/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryTest.php new file mode 100644 index 00000000..f02a2286 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/PickupExceptions/HasAutoUpdatedPickupExceptionsForYearQueryTest.php @@ -0,0 +1,42 @@ +create([ + 'date' => '2026-05-01', + 'label' => 'Manual exception', + 'repeatable' => false, + 'repeat_frequency' => RepeatFrequency::YEARLY, + 'auto_updated' => false, + ]); + + $query = new HasAutoUpdatedPickupExceptionsForYearQuery(); + + // WHEN + $beforeAuto = $query(new HasAutoUpdatedPickupExceptionsForYearQueryInput(2026)); + + PickupException::factory()->create([ + 'date' => '2026-01-01', + 'label' => '1er janvier', + 'repeatable' => true, + 'repeat_frequency' => RepeatFrequency::YEARLY, + 'auto_updated' => true, + ]); + + $afterAuto = $query(new HasAutoUpdatedPickupExceptionsForYearQueryInput(2026)); + + // THEN + expect($beforeAuto)->toBeFalse() + ->and($afterAuto)->toBeTrue(); + }); +}); diff --git a/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php new file mode 100644 index 00000000..c00ba0a7 --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/ProductIncos/GetProductIncoForEditQueryTest.php @@ -0,0 +1,93 @@ +name = 'Gamme ' . uniqid(); + $range->status = true; + $range->order = random_int(1, 9999); + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $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->id = UuidHelper::v7()->toString(); + $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->saveOrFail(); + + return $product; +} + +describe('GetProductIncoForEditQuery', function (): void { + it('returns immutable ProductDto and null inco when product has no INCO sheet', function (): void { + // GIVEN + $product = createTestProductForIncoQuery(); + $query = new GetProductIncoForEditQuery( + new ProductDtoAssemblerService(new EloquentProductRepository()), + ); + + // WHEN + $output = $query(new GetProductIncoForEditQueryInput($product->getId())); + + // THEN + expect($output->product->id)->toBe($product->id) + ->and($output->inco)->toBeNull(); + }); + + it('returns immutable ProductDto and ProductIncoDto when product has an INCO sheet', function (): void { + // GIVEN + $product = createTestProductForIncoQuery(); + $inco = new ProductInco(); + $inco->no_art = 12345; + $inco->product()->associate($product); + $inco->saveOrFail(); + + $query = new GetProductIncoForEditQuery( + new ProductDtoAssemblerService(new EloquentProductRepository()), + ); + + // WHEN + $output = $query(new GetProductIncoForEditQueryInput($product->getId())); + + // THEN + 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/Queries/Products/GetBoPaginatedProductsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetBoPaginatedProductsQueryTest.php similarity index 83% rename from tests/Integration/WithApp/App/Queries/Products/GetBoPaginatedProductsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Products/GetBoPaginatedProductsQueryTest.php index 1456943c..29d94092 100644 --- a/tests/Integration/WithApp/App/Queries/Products/GetBoPaginatedProductsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetBoPaginatedProductsQueryTest.php @@ -9,6 +9,8 @@ use App\Cqs\Queries\Products\GetBoPaginatedProductsQueryInput; use App\Models\Discount; use App\Models\Product; use App\Models\Range; +use App\Services\DataTableService; +use App\Services\ProductDtoAssemblerService; use Domain\Enums\DiscountType; use Domain\Enums\ProductBrand; use Domain\Enums\SellUnit; @@ -16,11 +18,22 @@ use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; use Domain\Models\ValueObjects\DiscountValue; +use Illuminate\Http\Request; +use Illuminate\Session\NullSessionHandler; +use Illuminate\Session\Store; +use Illuminate\Support\Facades\Schema; +use Infrastructure\Adapters\Repositories\EloquentProductRepository; +use Money\Currencies\ISOCurrencies; +use Money\Formatter\IntlMoneyFormatter; use Money\Money; use Shared\Pagination\PageNumber; use Shared\Pagination\PageSize; use Shared\Pagination\Pagination; +afterEach(function (): void { + DataTableService::clearColumnsCache(); +}); + describe('GetBoPaginatedProductsQuery', function (): void { $createRange = function (): Range { $range = new Range(); @@ -77,7 +90,15 @@ describe('GetBoPaginatedProductsQuery', function (): void { $prod2 = $createProduct('Prod with Discount 2', $range, $discount2->id); $prod3 = $createProduct('Prod without Discount', $range, null); - $query = app(GetBoPaginatedProductsQuery::class); + $query = new GetBoPaginatedProductsQuery( + new DataTableService( + Request::create('/'), + new Store('test', new NullSessionHandler()), + static fn (string $table): array => Schema::getColumnListing($table), + ), + new IntlMoneyFormatter(new \NumberFormatter('fr_FR', \NumberFormatter::CURRENCY), new ISOCurrencies()), + new ProductDtoAssemblerService(new EloquentProductRepository()), + ); $pagination = Pagination::ofPage(new PageNumber(1), new PageSize(10)); // WHEN: no filter 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/GetFoProductIndexPageQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoProductIndexPageQueryTest.php new file mode 100644 index 00000000..01f43b0c --- /dev/null +++ b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetFoProductIndexPageQueryTest.php @@ -0,0 +1,52 @@ +name = 'Gamme Active'; + $publishedRange->status = true; + $publishedRange->order = 1; + $publishedRange->picture_alt = 'alt'; + $publishedRange->picture_title = 'title'; + $publishedRange->saveOrFail(); + + $disabledRange = new Range(); + $disabledRange->name = 'Gamme Désactivée'; + $disabledRange->status = false; + $disabledRange->order = 2; + $disabledRange->picture_alt = 'alt'; + $disabledRange->picture_title = 'title'; + $disabledRange->saveOrFail(); + + $query = new GetFoProductIndexPageQuery( + new ProductDtoAssemblerService(new EloquentProductRepository()), + ); + $input = new GetFoProductIndexPageQueryInput( + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), + ); + + // WHEN + $output = $query($input); + + // THEN + $rangeIds = $output->rangeList->map(static fn (RangeDto $dto): int => $dto->id)->all(); + + expect($rangeIds)->toContain($publishedRange->id) + ->and($rangeIds)->not->toContain($disabledRange->id); + }); +}); 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/Queries/Products/GetProductFormDataQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductFormDataQueryTest.php similarity index 76% rename from tests/Integration/WithApp/App/Queries/Products/GetProductFormDataQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductFormDataQueryTest.php index 4ff512c3..f8804950 100644 --- a/tests/Integration/WithApp/App/Queries/Products/GetProductFormDataQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Products/GetProductFormDataQueryTest.php @@ -8,15 +8,16 @@ 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; +use App\Services\ProductDtoAssemblerService; use Domain\Enums\ProductBrand; use Domain\Enums\SellUnit; use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; +use Infrastructure\Adapters\Repositories\EloquentProductRepository; use Money\Money; describe('GetProductFormDataQuery', function (): void { @@ -65,14 +66,14 @@ describe('GetProductFormDataQuery', function (): void { $tag = new Tag(['label' => 'Tag ' . uniqid(), 'status' => true]); $tag->save(); - $query = new GetProductFormDataQuery(); + $query = new GetProductFormDataQuery(new ProductDtoAssemblerService(new EloquentProductRepository())); $input = new GetProductFormDataQueryInput(); // WHEN $output = $query($input); // THEN - expect($output)->toBeInstanceOf(ProductFormDataDto::class) + 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) @@ -86,17 +87,26 @@ describe('GetProductFormDataQuery', function (): void { $mainProduct = $createProduct('Principal', $range); $productAssociated = $createProduct('Associe', $range); $productNotAssociated = $createProduct('NonAssocie', $range); + $tag = new Tag(['label' => 'Tag Edit ' . uniqid(), 'status' => true]); + $tag->save(); $mainProduct->products()->attach($productAssociated->id, ['sort_order' => 1]); + $mainProduct->tags()->attach($tag->id); - $query = new GetProductFormDataQuery(); - $input = new GetProductFormDataQueryInput(product: $mainProduct); + $query = new GetProductFormDataQuery(new ProductDtoAssemblerService(new EloquentProductRepository())); + $input = new GetProductFormDataQueryInput(productId: $mainProduct->getId()); // WHEN $output = $query($input); // THEN - expect($output)->toBeInstanceOf(ProductFormDataDto::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) + ->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 !== 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) @@ -107,7 +117,7 @@ describe('GetProductFormDataQuery', function (): void { it('throws when an invalid input is passed', function (): void { // GIVEN - $query = new GetProductFormDataQuery(); + $query = new GetProductFormDataQuery(new ProductDtoAssemblerService(new EloquentProductRepository())); $invalidInput = new class () implements QueryInput { }; 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..99b4209c --- /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(UuidHelper::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(UuidHelper::v7()))); + + // THEN + expect($bySlug)->toBeNull() + ->and($byId)->toBeNull(); + }); +}); 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([]); + }); +}); diff --git a/tests/Integration/WithApp/App/Queries/Ranges/GetPaginatedRangesQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php similarity index 69% rename from tests/Integration/WithApp/App/Queries/Ranges/GetPaginatedRangesQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php index 1adefb8a..371520e8 100644 --- a/tests/Integration/WithApp/App/Queries/Ranges/GetPaginatedRangesQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Ranges/GetPaginatedRangesQueryTest.php @@ -2,17 +2,23 @@ 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; 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; +use Illuminate\Support\Facades\Schema; use Shared\Pagination\PageNumber; use Shared\Pagination\PageSize; use Shared\Pagination\Pagination; -uses(RefreshDatabase::class); +afterEach(function (): void { + DataTableService::clearColumnsCache(); +}); describe('GetPaginatedRangesQuery', function () { test('it executes and returns paginated RangeDto collection', function () { @@ -31,7 +37,11 @@ describe('GetPaginatedRangesQuery', function () { $range2->status = true; $range2->save(); - $dataTableService = resolve(DataTableService::class); + $dataTableService = new DataTableService( + Request::create('/'), + new Store('test', new NullSessionHandler()), + static fn (string $table): array => Schema::getColumnListing($table), + ); $query = new GetPaginatedRangesQuery($dataTableService); $input = new GetPaginatedRangesQueryInput( pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), @@ -42,8 +52,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/Queries/Settings/GetSettingsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php similarity index 73% rename from tests/Integration/WithApp/App/Queries/Settings/GetSettingsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php index f762a335..96923965 100644 --- a/tests/Integration/WithApp/App/Queries/Settings/GetSettingsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Settings/GetSettingsQueryTest.php @@ -2,13 +2,11 @@ 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; use App\Models\Setting; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); describe('GetSettingsQuery', function (): void { it('returns settings as SettingDto', function (): void { @@ -23,8 +21,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/Queries/Shops/GetPaginatedShopsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php similarity index 72% rename from tests/Integration/WithApp/App/Queries/Shops/GetPaginatedShopsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php index 2c68b2b5..496782e7 100644 --- a/tests/Integration/WithApp/App/Queries/Shops/GetPaginatedShopsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetPaginatedShopsQueryTest.php @@ -2,20 +2,25 @@ 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; use App\Dto\PickupExceptionDto; -use App\Dto\ShopDto; 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; +use Illuminate\Support\Facades\Schema; use Shared\Pagination\PageNumber; use Shared\Pagination\PageSize; use Shared\Pagination\Pagination; -uses(RefreshDatabase::class); +afterEach(function (): void { + DataTableService::clearColumnsCache(); +}); describe('GetPaginatedShopsQuery', function () { test('it executes and returns paginated shops and pickup exceptions', function () { @@ -24,7 +29,11 @@ describe('GetPaginatedShopsQuery', function () { $shop2 = Shop::factory()->create(['name' => 'Shop B']); $exception = PickupException::factory()->create(); - $dataTableService = resolve(DataTableService::class); + $dataTableService = new DataTableService( + Request::create('/'), + new Store('test', new NullSessionHandler()), + static fn (string $table): array => Schema::getColumnListing($table), + ); $query = new GetPaginatedShopsQuery($dataTableService); $input = new GetPaginatedShopsQueryInput( pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), @@ -34,10 +43,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); }); @@ -50,7 +57,11 @@ describe('GetPaginatedShopsQuery', function () { $shop1->pickupExceptions()->attach($exception->id); - $dataTableService = resolve(DataTableService::class); + $dataTableService = new DataTableService( + Request::create('/'), + new Store('test', new NullSessionHandler()), + static fn (string $table): array => Schema::getColumnListing($table), + ); $query = new GetPaginatedShopsQuery($dataTableService); $input = new GetPaginatedShopsQueryInput( pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), diff --git a/tests/Integration/WithApp/App/Queries/Shops/GetShopPickupExceptionsQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php similarity index 54% rename from tests/Integration/WithApp/App/Queries/Shops/GetShopPickupExceptionsQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php index 0ec5838e..3bac85c0 100644 --- a/tests/Integration/WithApp/App/Queries/Shops/GetShopPickupExceptionsQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopPickupExceptionsQueryTest.php @@ -2,32 +2,31 @@ 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; -use App\Dto\ShopDto; use App\Models\Shop; -use Illuminate\Foundation\Testing\RefreshDatabase; - -uses(RefreshDatabase::class); +use Domain\Services\PickupSchedulingService; +use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; +use Infrastructure\Adapters\Repositories\EloquentShopRepository; describe('GetShopPickupExceptionsQuery', function () { test('it executes and returns pickup exceptions output for a shop', function () { // GIVEN $shop = Shop::factory()->create(); - /** @var GetShopPickupExceptionsQuery $query */ - $query = app(GetShopPickupExceptionsQuery::class); + $query = new GetShopPickupExceptionsQuery( + new EloquentShopRepository(), + new PickupSchedulingService(new EloquentPickupExceptionRepository()), + ); $input = new GetShopPickupExceptionsQueryInput(shop: $shop); // WHEN $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/Queries/Shops/GetShopQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopQueryTest.php similarity index 77% rename from tests/Integration/WithApp/App/Queries/Shops/GetShopQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopQueryTest.php index 8983d26c..a871fd58 100644 --- a/tests/Integration/WithApp/App/Queries/Shops/GetShopQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Shops/GetShopQueryTest.php @@ -7,12 +7,13 @@ 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; use Domain\Enums\RepeatFrequency; use Illuminate\Database\Eloquent\ModelNotFoundException; +use Illuminate\Support\Carbon; +use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; +use Infrastructure\Adapters\Repositories\EloquentShopRepository; describe('GetShopQuery', function (): void { it('returns the default shop mapped as ShopDto with pickup exceptions', function (): void { @@ -38,26 +39,23 @@ describe('GetShopQuery', function (): void { 'order_deadline_at' => '2026-12-24 12:00:00', ]); - /** @var GetShopQuery $query */ - $query = app(GetShopQuery::class); + $query = new GetShopQuery(new EloquentShopRepository(), new EloquentPickupExceptionRepository()); $input = new GetShopQueryInput(); // WHEN $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) - ->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 { // GIVEN - /** @var GetShopQuery $query */ - $query = app(GetShopQuery::class); + $query = new GetShopQuery(new EloquentShopRepository(), new EloquentPickupExceptionRepository()); $input = new GetShopQueryInput(); // WHEN & THEN @@ -66,8 +64,7 @@ describe('GetShopQuery', function (): void { it('throws InvalidArgumentException when invalid input is passed', function (): void { // GIVEN - /** @var GetShopQuery $query */ - $query = app(GetShopQuery::class); + $query = new GetShopQuery(new EloquentShopRepository(), new EloquentPickupExceptionRepository()); $invalidInput = new class () implements QueryInput { }; diff --git a/tests/Integration/WithApp/App/Queries/Slides/GetPaginatedSlidesQueryTest.php b/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php similarity index 67% rename from tests/Integration/WithApp/App/Queries/Slides/GetPaginatedSlidesQueryTest.php rename to tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php index 1a21db33..3bad50bb 100644 --- a/tests/Integration/WithApp/App/Queries/Slides/GetPaginatedSlidesQueryTest.php +++ b/tests/Integration/WithApp/App/Cqs/Queries/Slides/GetPaginatedSlidesQueryTest.php @@ -2,15 +2,38 @@ 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; 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; use Illuminate\Support\Facades\Date; +use Illuminate\Support\Facades\Schema; 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 { it('returns a paginator of SlideDto instances', function (): void { // GIVEN @@ -26,8 +49,13 @@ describe('GetPaginatedSlidesQuery', function (): void { $slide2->order = 2; $slide2->save(); - /** @var GetPaginatedSlidesQuery $query */ - $query = app(GetPaginatedSlidesQuery::class); + $query = new GetPaginatedSlidesQuery( + new DataTableService( + Request::create('/'), + new Store('test', new NullSessionHandler()), + static fn (string $table): array => Schema::getColumnListing($table), + ), + ); $input = new GetPaginatedSlidesQueryInput( pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), ); @@ -37,9 +65,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 { @@ -68,8 +94,13 @@ describe('GetPaginatedSlidesQuery', function (): void { $futureSlide->date_end = $now->copy()->addDays(5); $futureSlide->save(); - /** @var GetPaginatedSlidesQuery $query */ - $query = app(GetPaginatedSlidesQuery::class); + $query = new GetPaginatedSlidesQuery( + new DataTableService( + Request::create('/'), + new Store('test', new NullSessionHandler()), + static fn (string $table): array => Schema::getColumnListing($table), + ), + ); $input = new GetPaginatedSlidesQueryInput( pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), publishedOnly: true, 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..79721470 --- /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(UuidHelper::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(UuidHelper::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); + }); +}); diff --git a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php index acfae274..6331d804 100644 --- a/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/OrderLineDtoTest.php @@ -2,10 +2,14 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Dto; + 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; @@ -21,31 +25,48 @@ 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; +use Shared\Helpers\UuidHelper; -uses(RefreshDatabase::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('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([ - 'id' => Uuid::uuid7()->toString(), + $order = Order::query()->forceCreate([ + '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(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(), ]); $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, @@ -92,6 +113,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/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/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php b/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php index 8024198f..004336f7 100644 --- a/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/PickupExceptionDtoTest.php @@ -2,12 +2,11 @@ declare(strict_types=1); +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 () { @@ -18,9 +17,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 () { @@ -35,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/RangeDtoTest.php b/tests/Integration/WithApp/App/Dto/RangeDtoTest.php index 472735f5..f3bc055c 100644 --- a/tests/Integration/WithApp/App/Dto/RangeDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/RangeDtoTest.php @@ -2,11 +2,10 @@ declare(strict_types=1); +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 () { @@ -31,6 +30,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..2e5df4b9 100644 --- a/tests/Integration/WithApp/App/Dto/ShopDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/ShopDtoTest.php @@ -2,12 +2,11 @@ declare(strict_types=1); +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 () { @@ -32,7 +31,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 () { @@ -49,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 ef6291ef..5accd241 100644 --- a/tests/Integration/WithApp/App/Dto/SlideDtoTest.php +++ b/tests/Integration/WithApp/App/Dto/SlideDtoTest.php @@ -2,12 +2,28 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Dto; + use App\Dto\SlideDto; +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 { - it('creates a DTO from Slide model with booted application', 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'); $dateEnd = Carbon::parse('2026-06-30 20:00:00'); @@ -16,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'; @@ -35,7 +51,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') @@ -46,6 +62,47 @@ 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 { + // 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/App/Models/EmployeeTest.php b/tests/Integration/WithApp/App/Models/EmployeeTest.php new file mode 100644 index 00000000..d95e17ae --- /dev/null +++ b/tests/Integration/WithApp/App/Models/EmployeeTest.php @@ -0,0 +1,93 @@ +create([ + 'matricule' => new Matricule($matricule), + 'code' => new Code($code), + 'nom' => 'Dupont', + 'prenom' => 'Jean', + 'start_date' => $startDate, + 'end_date' => $endDate, + 'etablissement' => new ShopperEstablishmentCode('ETAB01'), + 'site' => new ShopperSiteCode('SITE'), + 'service' => new ShopperServiceCode('101'), + ]); + }; + + it('evaluates is_active and active scope consistently across start_date and end_date', function () use ($createEmployee): void { + // GIVEN + $frozenNow = Date::parse('2026-11-15 10:00:00'); + Date::setTestNow($frozenNow); + + try { + $activeNoDates = $createEmployee('1000001', 'ABCDEF1', null, null); + $activeStartedToday = $createEmployee('1000002', 'ABCDEF2', '2026-11-15', null); + $activeInWindow = $createEmployee('1000003', 'ABCDEF3', '2026-11-01', '2026-11-16'); + $inactiveFutureStart = $createEmployee('1000004', 'ABCDEF4', '2026-11-16', null); + $inactiveFutureBoth = $createEmployee('1000005', 'ABCDEF5', '2026-11-16', '2026-11-30'); + $inactiveEndedToday = $createEmployee('1000006', 'ABCDEF6', '2026-11-01', '2026-11-15'); + $inactiveEndedPast = $createEmployee('1000007', 'ABCDEF7', '2026-11-01', '2026-11-14'); + + // WHEN + $activeIds = Employee::query() + ->active() + ->pluck('id') + ->all(); + + // THEN + expect($activeNoDates->is_active)->toBeTrue() + ->and($activeStartedToday->is_active)->toBeTrue() + ->and($activeInWindow->is_active)->toBeTrue() + ->and($inactiveFutureStart->is_active)->toBeFalse() + ->and($inactiveFutureBoth->is_active)->toBeFalse() + ->and($inactiveEndedToday->is_active)->toBeFalse() + ->and($inactiveEndedPast->is_active)->toBeFalse() + ->and($activeIds)->toEqualCanonicalizing([ + $activeNoDates->id, + $activeStartedToday->id, + $activeInWindow->id, + ]); + } finally { + Date::setTestNow(); + } + }); + + it('uses Europe/Paris day boundaries for is_active and active scope when UTC date is previous day', function () use ($createEmployee): void { + // GIVEN: 2026-05-07 22:30:00 UTC === 2026-05-08 00:30:00 Europe/Paris + Date::setTestNow(Date::parse('2026-05-07 22:30:00', 'UTC')); + + try { + $startedAtParisMidnight = $createEmployee('2000001', 'ABCDEF8', '2026-05-08', null); + $endedAtParisMidnight = $createEmployee('2000002', 'ABCDEF9', '2026-05-01', '2026-05-08'); + + // WHEN + $activeIds = Employee::query()->active()->pluck('id')->all(); + + // THEN + expect($startedAtParisMidnight->is_active)->toBeTrue() + ->and($endedAtParisMidnight->is_active)->toBeFalse() + ->and($activeIds)->toContain($startedAtParisMidnight->id) + ->and($activeIds)->not->toContain($endedAtParisMidnight->id); + } finally { + Date::setTestNow(); + } + }); +}); 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/Models/ProductTest.php b/tests/Integration/WithApp/App/Models/ProductTest.php new file mode 100644 index 00000000..f0d34ea2 --- /dev/null +++ b/tests/Integration/WithApp/App/Models/ProductTest.php @@ -0,0 +1,131 @@ + $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, + 'orderable_start' => $orderableStart, + 'orderable_end' => $orderableEnd, + ]); + $product->id = UuidHelper::v7()->toString(); + $product->order = random_int(1, 999999); + $product->price = Money::EUR(1000); + $product->short_description = 'Description courte'; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt'; + $product->picture_large_title = 'title'; + $product->saveOrFail(); + + $inco = new ProductInco(); + $inco->no_art = random_int(10000, 99999); + $inco->product()->associate($product); + $inco->saveOrFail(); + + return $product; +} + +describe('Product::scopeOrderable', function (): void { + it('includes product when current date equals orderable_start and excludes when current date equals orderable_end', function (): void { + // GIVEN + $now = Date::parse('2026-11-15 12:00:00'); + Date::setTestNow($now); + + $range = new Range(); + $range->name = 'Gamme ' . uniqid(); + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $startsNow = createOrderableTestProduct($range, orderableStart: $now, orderableEnd: $now->copy()->addHour()); + $endsNow = createOrderableTestProduct($range, orderableStart: $now->copy()->subHour(), orderableEnd: $now); + $inRange = createOrderableTestProduct($range, orderableStart: $now->copy()->subHour(), orderableEnd: $now->copy()->addHour()); + $future = createOrderableTestProduct($range, orderableStart: $now->copy()->addSecond(), orderableEnd: $now->copy()->addHour()); + + // WHEN + $orderableIds = Product::query()->orderable()->pluck('id')->all(); + + // THEN + expect($orderableIds)->toContain($startsNow->id, $inRange->id) + ->and($orderableIds)->not->toContain($endsNow->id, $future->id); + + 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/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/Unit/App/Policies/Frontend/OrderTunnelStepPolicyTest.php b/tests/Integration/WithApp/App/Policies/Frontend/OrderTunnelStepPolicyTest.php similarity index 77% rename from tests/Unit/App/Policies/Frontend/OrderTunnelStepPolicyTest.php rename to tests/Integration/WithApp/App/Policies/Frontend/OrderTunnelStepPolicyTest.php index a8688c79..43a3f6ed 100644 --- a/tests/Unit/App/Policies/Frontend/OrderTunnelStepPolicyTest.php +++ b/tests/Integration/WithApp/App/Policies/Frontend/OrderTunnelStepPolicyTest.php @@ -2,10 +2,12 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Policies\Frontend; + use App\Models\Customer; use App\Models\User; use App\Policies\Frontend\OrderTunnelStepPolicy; -use Domain\Enums\OrderTunnelStep; +use Domain\Services\BasketService; use Domain\Services\OrderTunnelService; use Illuminate\Support\Facades\Gate; @@ -19,7 +21,7 @@ function createFakeGate(bool $returns): object { } - public function allows($ability, $arguments = []) + public function allows(string $ability, mixed $arguments = []): bool { return $this->returns; } @@ -31,7 +33,8 @@ describe('OrderTunnelStepPolicy', function () { it('returns false when user is a User instance', function () { // GIVEN $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $policy = new OrderTunnelStepPolicy($orderTunnelService); + $basketService = \Mockery::mock(BasketService::class); + $policy = new OrderTunnelStepPolicy($orderTunnelService, $basketService); $user = new User(); // WHEN @@ -44,7 +47,8 @@ describe('OrderTunnelStepPolicy', function () { it('returns false when gate denies customerPassOrders', function () { // GIVEN $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $policy = new OrderTunnelStepPolicy($orderTunnelService); + $basketService = \Mockery::mock(BasketService::class); + $policy = new OrderTunnelStepPolicy($orderTunnelService, $basketService); $customer = new Customer(); Gate::swap(createFakeGate(false)); @@ -56,17 +60,17 @@ describe('OrderTunnelStepPolicy', function () { expect($result)->toBeFalse(); }); - it('returns false when orderTunnelService denies access to REVIEW step', function () { + it('returns false when basketService reports empty basket', function () { // GIVEN $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $policy = new OrderTunnelStepPolicy($orderTunnelService); + $basketService = \Mockery::mock(BasketService::class); + $policy = new OrderTunnelStepPolicy($orderTunnelService, $basketService); $customer = new Customer(); Gate::swap(createFakeGate(true)); - $orderTunnelService->shouldReceive('canAccessStep') + $basketService->shouldReceive('hasItems') ->once() - ->with(OrderTunnelStep::REVIEW) ->andReturn(false); // WHEN @@ -76,17 +80,17 @@ describe('OrderTunnelStepPolicy', function () { expect($result)->toBeFalse(); }); - it('returns true when gate allows and orderTunnelService allows', function () { + it('returns true when gate allows and basket has items', function () { // GIVEN $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $policy = new OrderTunnelStepPolicy($orderTunnelService); + $basketService = \Mockery::mock(BasketService::class); + $policy = new OrderTunnelStepPolicy($orderTunnelService, $basketService); $customer = new Customer(); Gate::swap(createFakeGate(true)); - $orderTunnelService->shouldReceive('canAccessStep') + $basketService->shouldReceive('hasItems') ->once() - ->with(OrderTunnelStep::REVIEW) ->andReturn(true); // WHEN @@ -101,7 +105,8 @@ describe('OrderTunnelStepPolicy', function () { it('returns false when user is a User instance', function () { // GIVEN $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $policy = new OrderTunnelStepPolicy($orderTunnelService); + $basketService = \Mockery::mock(BasketService::class); + $policy = new OrderTunnelStepPolicy($orderTunnelService, $basketService); $user = new User(); // WHEN @@ -114,7 +119,8 @@ describe('OrderTunnelStepPolicy', function () { it('returns false when gate denies customerPassOrders', function () { // GIVEN $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $policy = new OrderTunnelStepPolicy($orderTunnelService); + $basketService = \Mockery::mock(BasketService::class); + $policy = new OrderTunnelStepPolicy($orderTunnelService, $basketService); $customer = new Customer(); Gate::swap(createFakeGate(false)); @@ -129,14 +135,14 @@ describe('OrderTunnelStepPolicy', function () { it('returns false when orderTunnelService denies access to BOOKING step', function () { // GIVEN $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $policy = new OrderTunnelStepPolicy($orderTunnelService); + $basketService = \Mockery::mock(BasketService::class); + $policy = new OrderTunnelStepPolicy($orderTunnelService, $basketService); $customer = new Customer(); Gate::swap(createFakeGate(true)); - $orderTunnelService->shouldReceive('canAccessStep') + $orderTunnelService->shouldReceive('canAccessBooking') ->once() - ->with(OrderTunnelStep::BOOKING) ->andReturn(false); // WHEN @@ -149,14 +155,14 @@ describe('OrderTunnelStepPolicy', function () { it('returns true when gate allows and orderTunnelService allows', function () { // GIVEN $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $policy = new OrderTunnelStepPolicy($orderTunnelService); + $basketService = \Mockery::mock(BasketService::class); + $policy = new OrderTunnelStepPolicy($orderTunnelService, $basketService); $customer = new Customer(); Gate::swap(createFakeGate(true)); - $orderTunnelService->shouldReceive('canAccessStep') + $orderTunnelService->shouldReceive('canAccessBooking') ->once() - ->with(OrderTunnelStep::BOOKING) ->andReturn(true); // WHEN @@ -171,7 +177,8 @@ describe('OrderTunnelStepPolicy', function () { it('returns false when user is a User instance', function () { // GIVEN $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $policy = new OrderTunnelStepPolicy($orderTunnelService); + $basketService = \Mockery::mock(BasketService::class); + $policy = new OrderTunnelStepPolicy($orderTunnelService, $basketService); $user = new User(); // WHEN @@ -184,7 +191,8 @@ describe('OrderTunnelStepPolicy', function () { it('returns false when gate denies customerPassOrders', function () { // GIVEN $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $policy = new OrderTunnelStepPolicy($orderTunnelService); + $basketService = \Mockery::mock(BasketService::class); + $policy = new OrderTunnelStepPolicy($orderTunnelService, $basketService); $customer = new Customer(); Gate::swap(createFakeGate(false)); @@ -199,14 +207,14 @@ describe('OrderTunnelStepPolicy', function () { it('returns false when orderTunnelService denies access to CONFIRMATION step', function () { // GIVEN $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $policy = new OrderTunnelStepPolicy($orderTunnelService); + $basketService = \Mockery::mock(BasketService::class); + $policy = new OrderTunnelStepPolicy($orderTunnelService, $basketService); $customer = new Customer(); Gate::swap(createFakeGate(true)); - $orderTunnelService->shouldReceive('canAccessStep') + $orderTunnelService->shouldReceive('canAccessConfirmation') ->once() - ->with(OrderTunnelStep::CONFIRMATION) ->andReturn(false); // WHEN @@ -219,14 +227,14 @@ describe('OrderTunnelStepPolicy', function () { it('returns true when gate allows and orderTunnelService allows', function () { // GIVEN $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $policy = new OrderTunnelStepPolicy($orderTunnelService); + $basketService = \Mockery::mock(BasketService::class); + $policy = new OrderTunnelStepPolicy($orderTunnelService, $basketService); $customer = new Customer(); Gate::swap(createFakeGate(true)); - $orderTunnelService->shouldReceive('canAccessStep') + $orderTunnelService->shouldReceive('canAccessConfirmation') ->once() - ->with(OrderTunnelStep::CONFIRMATION) ->andReturn(true); // WHEN diff --git a/tests/Integration/WithApp/App/Rules/AdultTest.php b/tests/Integration/WithApp/App/Rules/AdultTest.php new file mode 100644 index 00000000..b588bef7 --- /dev/null +++ b/tests/Integration/WithApp/App/Rules/AdultTest.php @@ -0,0 +1,80 @@ + $birthDate], + ['birth_date' => ['required', new Adult()]], + ); + + // THEN + expect($validator->passes())->toBeTrue(); + })->with([ + 'exact 18th birthday SQL' => ['2008-11-16'], + 'older SQL' => ['1990-01-15'], + 'exact 18th birthday form' => ['16/11/2008'], + 'older form' => ['15/01/1990'], + ]); + + it('rejects minor birth dates with translated message in fr and en', function (string $locale, string $expectedMessage): void { + // GIVEN + Date::setTestNow(CarbonImmutable::parse('2026-11-16 12:00:00')); + App::setLocale($locale); + + // WHEN + $validator = Validator::make( + ['birth_date' => '2008-11-17'], + ['birth_date' => ['required', new Adult()]], + ); + + // THEN + expect($validator->fails())->toBeTrue() + ->and($validator->errors()->first('birth_date'))->toBe($expectedMessage); + })->with([ + 'french' => ['fr', 'Vous devez être majeur pour vous inscrire.'], + 'english' => ['en', 'You must be of legal age to register.'], + ]); + + it('rejects non-string or malformed dates with translated message in fr and en', function ( + string $locale, + mixed $value, + string $expectedMessage, + ): void { + // GIVEN + App::setLocale($locale); + + // WHEN + $validator = Validator::make( + ['birth_date' => $value], + ['birth_date' => [new Adult()]], + ); + + // THEN + expect($validator->fails())->toBeTrue() + ->and($validator->errors()->first('birth_date'))->toBe($expectedMessage); + })->with([ + 'french invalid format' => ['fr', 'invalid-date', 'Veuillez entrer une date de naissance valide.'], + 'english invalid format' => ['en', 'invalid-date', 'Please enter a valid birth date.'], + 'french non-string' => ['fr', 12345, 'Veuillez entrer une date de naissance valide.'], + 'english non-string' => ['en', 12345, 'Please enter a valid birth date.'], + ]); +}); diff --git a/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php b/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php index a4808de7..a3922c21 100644 --- a/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php +++ b/tests/Integration/WithApp/App/Services/ActionExecutorServiceTest.php @@ -2,10 +2,28 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Services; + +use App\Attributes\Locked; +use App\Attributes\WithoutTransaction; use App\Contracts\Action; use App\Contracts\ActionInput; +use App\Contracts\HandlesFailure; +use App\Contracts\HandlesLockTimeout; +use App\Contracts\HandlesSuccess; +use App\Contracts\ProvidesLockKey; +use App\Models\Tag; use App\Services\ActionExecutorService; +use Illuminate\Cache\ArrayStore; +use Illuminate\Cache\Repository; +use Illuminate\Support\Facades\DB; +use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; +use Infrastructure\Adapters\Locks\LaravelCacheLock; use Psr\Log\AbstractLogger; +use Psr\Log\LoggerInterface; +use Shared\Concurrency\Lock; +use Shared\Concurrency\LockTimeoutException; +use Shared\DDD\Event; describe('ActionExecutorService', function (): void { it('executes action in transaction and logs success', function (): void { @@ -34,7 +52,9 @@ describe('ActionExecutorService', function (): void { $input = new class () implements ActionInput { }; - $executor = new ActionExecutorService($logger); + $lock = new LaravelCacheLock(new Repository(new ArrayStore())); + $eventDispatcher = new LaravelDomainEventDispatcher(); + $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); // WHEN $result = $executor->execute($action, $input); @@ -72,7 +92,9 @@ describe('ActionExecutorService', function (): void { $input = new class () implements ActionInput { }; - $executor = new ActionExecutorService($logger); + $lock = new LaravelCacheLock(new Repository(new ArrayStore())); + $eventDispatcher = new LaravelDomainEventDispatcher(); + $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); // WHEN expect(fn () => $executor->execute($action, $input)) @@ -83,4 +105,756 @@ describe('ActionExecutorService', function (): void { ->and($logger->logs[0])->toContain('Executing') ->and($logger->logs[1])->toContain('Failed'); }); + + it('acquires lock before DB transaction starts and releases it after transaction commits', function (): void { + // GIVEN + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldIgnoreMissing(); + $store = new ArrayStore(); + $innerLock = new LaravelCacheLock(new Repository($store)); + $initialLevel = DB::transactionLevel(); + $lvl1 = null; + $lvl2 = null; + $held2 = false; + $lvl3 = null; + $held3 = false; + $key = null; + $ttl = null; + $wait = null; + + $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 &$lvl1, + public ?int &$lvl3, + public bool &$held3, + public ?string &$key, + public ?int &$ttl, + public ?int &$wait, + ) { + } + + #[\Override] + public function synchronize( + string $key, + callable $callback, + int $ttlSeconds = 30, + int $waitSeconds = 10, + ): mixed { + $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->lvl3 = DB::transactionLevel(); + $this->held3 = ! $this->store->lock($key, $ttlSeconds)->get(); + + return $result; + }, + ttlSeconds: $ttlSeconds, + waitSeconds: $waitSeconds, + ); + } + }; + + $action = new #[Locked(ttlSeconds: 45, waitSeconds: 7)] class ($store, $lvl2, $held2) implements Action, ProvidesLockKey + { + public function __construct( + private readonly ArrayStore $store, + public ?int &$lvl2, + public bool &$held2, + ) { + } + + #[\Override] + public function lockKey(ActionInput $input): string + { + return 'test:lock:order'; + } + + #[\Override] + public function __invoke(ActionInput $input): string + { + $this->lvl2 = DB::transactionLevel(); + $this->held2 = ! $this->store->lock('test:lock:order', 45)->get(); + + return 'committed'; + } + }; + + $input = new class () implements ActionInput + { + }; + $eventDispatcher = new LaravelDomainEventDispatcher(); + $executor = new ActionExecutorService($recordingLock, $logger, $eventDispatcher); + + // WHEN + $result = $executor->execute($action, $input); + + // THEN + expect($result)->toBe('committed') + ->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(); + }); + + it('uses Locked attribute key when ProvidesLockKey is not implemented', function (): void { + // GIVEN + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldIgnoreMissing(); + $lock = \Mockery::mock(Lock::class); + $lock->shouldReceive('synchronize') + ->once() + ->with('custom-key', \Mockery::type(\Closure::class), 30, 10) + ->andReturnUsing(static fn (string $key, callable $callback): mixed => $callback()); + + $action = new #[Locked(key: 'custom-key')] class () implements Action + { + #[\Override] + public function __invoke(ActionInput $input): string + { + return 'custom-key-result'; + } + }; + + $input = new class () implements ActionInput + { + }; + $eventDispatcher = new LaravelDomainEventDispatcher(); + $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); + + // WHEN + $result = $executor->execute($action, $input); + + // THEN + expect($result)->toBe('custom-key-result'); + }); + + it('defaults lock key to action FQCN when neither Locked key nor ProvidesLockKey is provided', function (): void { + // GIVEN + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldIgnoreMissing(); + $action = new #[Locked] class () implements Action + { + #[\Override] + public function __invoke(ActionInput $input): string + { + return 'fqcn-key-result'; + } + }; + + $lock = \Mockery::mock(Lock::class); + $lock->shouldReceive('synchronize') + ->once() + ->with($action::class, \Mockery::type(\Closure::class), 30, 10) + ->andReturnUsing(static fn (string $key, callable $callback): mixed => $callback()); + + $input = new class () implements ActionInput + { + }; + $eventDispatcher = new LaravelDomainEventDispatcher(); + $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); + + // WHEN + $result = $executor->execute($action, $input); + + // THEN + expect($result)->toBe('fqcn-key-result'); + }); + + it('returns onLockTimeout, logs warning, and skips action on LockTimeoutException when HandlesLockTimeout is implemented', function (): void { + // GIVEN + $logger = new class () extends AbstractLogger + { + /** @var array */ + public array $entries = []; + + #[\Override] + public function log($level, string | \Stringable $message, array $context = []): void + { + $this->entries[] = [ + 'level' => $level, + 'message' => (string) $message, + ]; + } + }; + + $lock = \Mockery::mock(Lock::class); + $lock->shouldReceive('synchronize') + ->once() + ->with('test:lock:busy', \Mockery::type(\Closure::class), 30, 10) + ->andThrow(new LockTimeoutException('Timed out waiting for lock')); + + $invoked = false; + $action = new #[Locked(ttlSeconds: 30, waitSeconds: 10)] class ($invoked) implements Action, HandlesLockTimeout, ProvidesLockKey + { + public function __construct( + public bool &$invoked, + ) { + } + + #[\Override] + public function lockKey(ActionInput $input): string + { + return 'test:lock:busy'; + } + + #[\Override] + public function onLockTimeout(ActionInput $input): string + { + return 'lock-timeout-output'; + } + + #[\Override] + public function __invoke(ActionInput $input): string + { + $this->invoked = true; + + return 'should-not-run'; + } + }; + + $input = new class () implements ActionInput + { + }; + $eventDispatcher = new LaravelDomainEventDispatcher(); + $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); + + // WHEN + $result = $executor->execute($action, $input); + + // THEN + expect($result)->toBe('lock-timeout-output') + ->and($invoked)->toBeFalse() + ->and($logger->entries)->toHaveCount(2) + ->and($logger->entries[0]['message'])->toContain('Executing') + ->and($logger->entries[1]['level'])->toBe('warning') + ->and($logger->entries[1]['message'])->toContain('Lock timeout'); + }); + + it('rethrows LockTimeoutException and logs error when HandlesLockTimeout is not implemented', function (): void { + // GIVEN + $logger = new class () extends AbstractLogger + { + /** @var array */ + public array $entries = []; + + #[\Override] + public function log($level, string | \Stringable $message, array $context = []): void + { + $this->entries[] = [ + 'level' => $level, + 'message' => (string) $message, + ]; + } + }; + + $lock = \Mockery::mock(Lock::class); + $lock->shouldReceive('synchronize') + ->once() + ->with('test:lock:unhandled', \Mockery::type(\Closure::class), 30, 10) + ->andThrow(new LockTimeoutException('Timed out waiting for lock')); + + $action = new #[Locked(key: 'test:lock:unhandled')] class () implements Action + { + #[\Override] + public function __invoke(ActionInput $input): string + { + return 'should-not-run'; + } + }; + + $input = new class () implements ActionInput + { + }; + $eventDispatcher = new LaravelDomainEventDispatcher(); + $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); + + // WHEN + expect(fn () => $executor->execute($action, $input)) + // THEN + ->toThrow(LockTimeoutException::class, 'Timed out waiting for lock'); + + expect($logger->entries)->toHaveCount(2) + ->and($logger->entries[0]['level'])->toBe('info') + ->and($logger->entries[0]['message'])->toContain('Executing') + ->and($logger->entries[1]['level'])->toBe('error') + ->and($logger->entries[1]['message'])->toContain('Failed'); + }); + + it('flushes buffered events and calls onSucceeded only after transaction commit and lock release', function (): void { + // GIVEN + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldIgnoreMissing(); + + $store = new ArrayStore(); + $innerLock = new LaravelCacheLock(new Repository($store)); + $sequence = []; + + $recordingLock = new class ($innerLock, $sequence) implements Lock + { + /** @param list $sequence */ + public function __construct( + private readonly Lock $inner, + public array &$sequence, + ) { + } + + #[\Override] + public function synchronize( + string $key, + callable $callback, + int $ttlSeconds = 30, + int $waitSeconds = 10, + ): mixed { + $this->sequence[] = 'lock:acquire'; + $result = $this->inner->synchronize($key, $callback, $ttlSeconds, $waitSeconds); + $this->sequence[] = 'lock:release'; + + return $result; + } + }; + + $eventDispatcher = new class ($sequence) extends LaravelDomainEventDispatcher + { + /** @param list $sequence */ + public function __construct( + public array &$sequence, + ) { + } + + #[\Override] + public function beginBuffering(): void + { + $this->sequence[] = 'events:begin'; + } + + #[\Override] + public function dispatch(Event $event): void + { + $this->sequence[] = 'events:dispatch'; + } + + #[\Override] + public function flush(): void + { + $this->sequence[] = 'events:flush'; + } + + #[\Override] + public function discard(): void + { + $this->sequence[] = 'events:discard'; + } + }; + + $action = new #[Locked(key: 'test:post-commit')] class ($sequence, $eventDispatcher) implements Action, HandlesSuccess + { + /** @param list $sequence */ + public function __construct( + public array &$sequence, + private readonly LaravelDomainEventDispatcher $eventDispatcher, + ) { + } + + #[\Override] + public function __invoke(ActionInput $input): string + { + $this->sequence[] = 'action:invoke'; + $this->eventDispatcher->dispatch(new class () implements Event + { + }); + + return 'ok'; + } + + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + assert(is_string($result)); + $this->sequence[] = "action:onSuccess:{$result}"; + } + }; + + $input = new class () implements ActionInput + { + }; + $executor = new ActionExecutorService($recordingLock, $logger, $eventDispatcher); + + // WHEN + $result = $executor->execute($action, $input); + + // THEN + expect($result)->toBe('ok') + ->and($sequence)->toBe([ + 'lock:acquire', + 'events:begin', + 'action:invoke', + 'events:dispatch', + 'lock:release', + 'events:flush', + 'action:onSuccess:ok', + ]); + }); + + it('discards buffered events and skips onSuccess when action throws', function (): void { + // GIVEN + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldIgnoreMissing(); + + $lock = new LaravelCacheLock(new Repository(new ArrayStore())); + $eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class); + $eventDispatcher->shouldReceive('beginBuffering')->once(); + $eventDispatcher->shouldReceive('discard')->once(); + $eventDispatcher->shouldNotReceive('flush'); + + $onSuccessCalled = false; + $action = new class ($onSuccessCalled) implements Action, HandlesSuccess + { + public function __construct( + public bool &$onSuccessCalled, + ) { + } + + #[\Override] + public function __invoke(ActionInput $input): never + { + throw new \RuntimeException('Boom'); + } + + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + $this->onSuccessCalled = true; + } + }; + + $input = new class () implements ActionInput + { + }; + $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); + + // WHEN + expect(fn () => $executor->execute($action, $input)) + // THEN + ->toThrow(\RuntimeException::class, 'Boom'); + + expect($onSuccessCalled)->toBeFalse(); + }); + + it('skips flush and onSuccess when lock timeout occurs and HandlesLockTimeout handles it', function (): void { + // GIVEN + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldIgnoreMissing(); + + $lock = \Mockery::mock(Lock::class); + $lock->shouldReceive('synchronize') + ->once() + ->andThrow(new LockTimeoutException('Busy')); + + $eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class); + $eventDispatcher->shouldNotReceive('beginBuffering'); + $eventDispatcher->shouldNotReceive('flush'); + $eventDispatcher->shouldNotReceive('discard'); + + $onSuccessCalled = false; + $action = new #[Locked(key: 'test:timeout')] class ($onSuccessCalled) implements Action, HandlesLockTimeout, HandlesSuccess + { + public function __construct( + public bool &$onSuccessCalled, + ) { + } + + #[\Override] + public function onLockTimeout(ActionInput $input): string + { + return 'timeout-result'; + } + + #[\Override] + public function __invoke(ActionInput $input): string + { + return 'never'; + } + + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + $this->onSuccessCalled = true; + } + }; + + $input = new class () implements ActionInput + { + }; + $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); + + // WHEN + $result = $executor->execute($action, $input); + + // THEN + expect($result)->toBe('timeout-result') + ->and($onSuccessCalled)->toBeFalse(); + }); + + it('rolls back DB writes, discards events, runs onFailure, skips onSuccess, and rethrows when action fails', function (): void { + // GIVEN + $logger = new class () extends AbstractLogger + { + /** @var array */ + public array $entries = []; + + #[\Override] + public function log($level, string | \Stringable $message, array $context = []): void + { + $this->entries[] = [ + 'level' => $level, + 'message' => (string) $message, + ]; + } + }; + + $lock = new LaravelCacheLock(new Repository(new ArrayStore())); + $eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class); + $eventDispatcher->shouldReceive('beginBuffering')->once(); + $eventDispatcher->shouldReceive('discard')->once(); + $eventDispatcher->shouldNotReceive('flush'); + + $onSuccessCalled = false; + $capturedException = null; + $action = new class ($onSuccessCalled, $capturedException) implements Action, HandlesFailure, HandlesSuccess + { + public function __construct( + public bool &$onSuccessCalled, + public ?\Throwable &$capturedException, + ) { + } + + #[\Override] + public function __invoke(ActionInput $input): string + { + Tag::query()->create([ + 'label' => 'Should be rolled back', + 'status' => true, + ]); + + throw new \DomainException('Domain failure after DB write'); + } + + #[\Override] + public function onFailure(ActionInput $input, \Throwable $exception): void + { + $this->capturedException = $exception; + } + + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + $this->onSuccessCalled = true; + } + }; + + $input = new class () implements ActionInput + { + }; + $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); + + // WHEN + expect(fn () => $executor->execute($action, $input)) + // THEN + ->toThrow(\DomainException::class, 'Domain failure after DB write'); + + expect(Tag::query()->where('label', 'Should be rolled back')->exists())->toBeFalse() + ->and($onSuccessCalled)->toBeFalse() + ->and($capturedException)->toBeInstanceOf(\DomainException::class) + ->and($logger->entries)->toHaveCount(2) + ->and($logger->entries[1]['level'])->toBe('error'); + }); + + it('rolls back DB writes and calls onFailure after releasing lock when Locked action implements HandlesFailure', function (): void { + // GIVEN + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldIgnoreMissing(); + + $store = new ArrayStore(); + $lock = new LaravelCacheLock(new Repository($store)); + $eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class); + $eventDispatcher->shouldReceive('beginBuffering')->once(); + $eventDispatcher->shouldReceive('discard')->once(); + $eventDispatcher->shouldNotReceive('flush'); + + $ok = false; + $free = false; + $action = new #[Locked(key: 'test:locked:failure')] class ($ok, $free, $store) implements Action, HandlesFailure, HandlesSuccess + { + public function __construct( + public bool &$ok, + public bool &$free, + private readonly ArrayStore $store, + ) { + } + + #[\Override] + public function __invoke(ActionInput $input): string + { + Tag::query()->create([ + 'label' => 'Locked rollback test', + 'status' => true, + ]); + + throw new \DomainException('Locked domain failure'); + } + + #[\Override] + public function onFailure(ActionInput $input, \Throwable $exception): void + { + $lock = $this->store->lock('test:locked:failure', 30); + $this->free = (bool) $lock->get(); + + if ($this->free) { + $lock->release(); + } + } + + #[\Override] + public function onSuccess(ActionInput $input, mixed $result): void + { + $this->ok = true; + } + }; + + $input = new class () implements ActionInput + { + }; + $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); + + // WHEN + expect(fn () => $executor->execute($action, $input)) + // THEN + ->toThrow(\DomainException::class, 'Locked domain failure'); + + expect(Tag::query()->where('label', 'Locked rollback test')->exists())->toBeFalse() + ->and($ok)->toBeFalse() + ->and($free)->toBeTrue() + ->and($store->lock('test:locked:failure', 30)->get())->toBeTrue(); + }); + + it('calls onFailure and rethrows LockTimeoutException when Locked action does not implement HandlesLockTimeout', function (): void { + // GIVEN + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldIgnoreMissing(); + + $lock = \Mockery::mock(Lock::class); + $lock->shouldReceive('synchronize') + ->once() + ->andThrow(new LockTimeoutException('Busy')); + + $eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class); + $eventDispatcher->shouldNotReceive('beginBuffering'); + $eventDispatcher->shouldNotReceive('flush'); + $eventDispatcher->shouldNotReceive('discard'); + + $capturedException = null; + $action = new #[Locked(key: 'test:timeout:failure')] class ($capturedException) implements Action, HandlesFailure + { + public function __construct( + public ?\Throwable &$capturedException, + ) { + } + + #[\Override] + public function __invoke(ActionInput $input): string + { + return 'never'; + } + + #[\Override] + public function onFailure(ActionInput $input, \Throwable $exception): void + { + $this->capturedException = $exception; + } + }; + + $input = new class () implements ActionInput + { + }; + $executor = new ActionExecutorService($lock, $logger, $eventDispatcher); + + // WHEN + expect(fn () => $executor->execute($action, $input)) + // THEN + ->toThrow(LockTimeoutException::class, 'Busy'); + + 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(); + + $txLevel = null; + $action = new #[WithoutTransaction] class ($txLevel, $postHookEvent, $eventDispatcher) implements Action, HandlesSuccess + { + public function __construct( + public ?int &$txLevel, + private readonly Event $event, + private readonly LaravelDomainEventDispatcher $dispatcher, + ) { + } + + #[\Override] + public function __invoke(ActionInput $input): string + { + $this->txLevel = 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($txLevel)->toBe($baseTx); + }); }); 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(); + }); + }); +}); diff --git a/tests/Integration/WithApp/App/Services/CrmServiceTest.php b/tests/Integration/WithApp/App/Services/CrmServiceTest.php new file mode 100644 index 00000000..27dc5184 --- /dev/null +++ b/tests/Integration/WithApp/App/Services/CrmServiceTest.php @@ -0,0 +1,438 @@ +toString(); + + $libCustomer = new Customer([ + 'hashcode' => $uuid, + 'email' => 'john@example.com', + 'password' => 'Secret123!', + 'firstname' => 'John', + 'lastname' => 'Doe', + 'birth_date' => '1990-01-01', + 'phone' => '0123456789', + 'address' => '123 Main St', + 'address2' => null, + 'city' => 'Paris', + 'postcode' => '75000', + 'country' => EnumsCountry::france, + 'opt_in' => true, + 'status' => true, + 'last_connection' => null, + ]); + + $cacheKey = "crm_customer_hashcode_{$uuid}"; + + $cacheRepository->shouldReceive('remember') + ->once() + ->with($cacheKey, \Mockery::any(), \Mockery::on(function (\Closure $closure) use ($crmApi, $libCustomer, $uuid) { + $crmApi->shouldReceive('getCustomer')->with((string) $uuid)->once()->andReturn($libCustomer); + $result = $closure(); + + return $result instanceof CrmCustomer && $result->hashcode === (string) $uuid; + })) + ->andReturn(new CrmCustomer( + hashcode: (string) $uuid, + email: 'john@example.com', + password: 'Secret123!', + firstname: 'John', + lastname: 'Doe', + birthDate: '1990-01-01', + phone: '0123456789', + address: '123 Main St', + address2: null, + city: 'Paris', + postcode: '75000', + country: Country::france, + optIn: true, + status: true, + lastConnection: null, + )); + + $service = new CrmService($crmApi, $cacheRepository); + $hashcode = new CrmHashcode($uuidObj); + + // WHEN + $firstCall = $service->getCustomerFromHashCode($hashcode); + + // Second call should return from internal memory cache without querying CacheRepository again + $secondCall = $service->getCustomerFromHashCode($hashcode); + + // THEN + expect($firstCall)->toBeInstanceOf(CrmCustomer::class) + ->and($firstCall instanceof CrmCustomer ? $firstCall->hashcode : null)->toBe($uuid) + ->and($secondCall)->toBe($firstCall); + }); + + it('returns customer from email with sha256 cache key', function (): void { + // GIVEN + $crmApi = \Mockery::mock(CrmApiV4::class); + $cacheRepository = \Mockery::mock(CacheRepository::class); + + $email = 'test@example.com'; + $cacheKey = 'crm_customer_email_' . hash('sha256', $email); + + $expectedCustomer = new CrmCustomer( + hashcode: (string) UuidHelper::v4(), + email: $email, + password: 'Secret123!', + firstname: 'Jane', + lastname: 'Doe', + birthDate: '1992-05-10', + phone: '0123456789', + address: '456 Side St', + address2: null, + city: 'Lyon', + postcode: '69000', + country: Country::france, + optIn: false, + status: true, + lastConnection: null, + ); + + $cacheRepository->shouldReceive('remember') + ->once() + ->with($cacheKey, \Mockery::any(), \Mockery::type('Closure')) + ->andReturn($expectedCustomer); + + $service = new CrmService($crmApi, $cacheRepository); + + // WHEN + $result = $service->getCustomerFromEmail($email); + + // THEN + expect($result)->toBeInstanceOf(CrmCustomer::class) + ->and($result instanceof CrmCustomer ? $result->email : null)->toBe($email); + }); + + it('returns null on modelNotFound ApiErrorException and caches result', function (): void { + // GIVEN + $crmApi = \Mockery::mock(CrmApiV4::class); + $cacheRepository = \Mockery::mock(CacheRepository::class); + + $uuid = UuidHelper::v4(); + $cacheKey = "crm_customer_hashcode_{$uuid}"; + + $cacheRepository->shouldReceive('remember') + ->once() + ->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); + $res = $closure(); + + return $res === null; + })) + ->andReturnNull(); + + $service = new CrmService($crmApi, $cacheRepository); + + // WHEN + $result = $service->getCustomerFromHashCode(new CrmHashcode($uuid)); + + // THEN + expect($result)->toBeNull(); + }); + + it('invalidates cache on activate', function (): void { + // GIVEN + $crmApi = \Mockery::mock(CrmApiV4::class); + $cacheRepository = \Mockery::mock(CacheRepository::class); + + $uuid = (string) UuidHelper::v4(); + + $customer = new CrmCustomer( + hashcode: $uuid, + email: 'activate@example.com', + password: 'Secret123!', + firstname: 'John', + lastname: 'Doe', + birthDate: '1990-01-01', + phone: '0123456789', + address: '123 Main St', + address2: null, + city: 'Paris', + postcode: '75000', + country: Country::france, + optIn: true, + status: false, + lastConnection: null, + ); + + $expectedHashKey = "crm_customer_hashcode_{$uuid}"; + $expectedEmailKey = 'crm_customer_email_' . hash('sha256', 'activate@example.com'); + + $cacheRepository->shouldReceive('delete')->with($expectedHashKey)->once(); + $cacheRepository->shouldReceive('delete')->with($expectedEmailKey)->once(); + + $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 + $result = $service->activate($customer); + + // THEN + expect($result)->toHaveProperty('result'); + }); + + it('returns CrmServiceException without caching it when CRM fails on hashcode or email lookup', function (): void { + // GIVEN + $crmApi = \Mockery::mock(CrmApiV4::class); + $cacheRepository = new ArrayCacheRepository(new ArrayStore()); + + $uuid = UuidHelper::v4(); + $email = 'error@example.com'; + $hashKey = "crm_customer_hashcode_{$uuid}"; + $emailKey = 'crm_customer_email_' . hash('sha256', $email); + + $apiException = \Mockery::mock(ApiErrorException::class); + $apiException->shouldReceive('getApiError')->andReturn(ApiError::apiAuthFailed); + + $crmApi->shouldReceive('getCustomer')->with((string) $uuid)->twice()->andThrow($apiException); + $crmApi->shouldReceive('getCustomer')->with($email)->twice()->andThrow(new CrmException('Network failure')); + + $service = new CrmService($crmApi, $cacheRepository); + + // WHEN + $hashFirst = $service->getCustomerFromHashCode(new CrmHashcode($uuid)); + $hashSecond = $service->getCustomerFromHashCode(new CrmHashcode($uuid)); + $emailFirst = $service->getCustomerFromEmail($email); + $emailSec = $service->getCustomerFromEmail($email); + + // THEN + expect($hashFirst)->toBeInstanceOf(CrmServiceException::class) + ->and($hashSecond)->toBeInstanceOf(CrmServiceException::class) + ->and($emailFirst)->toBeInstanceOf(CrmServiceException::class) + ->and($emailSec)->toBeInstanceOf(CrmServiceException::class) + ->and($cacheRepository->has($hashKey))->toBeFalse() + ->and($cacheRepository->has($emailKey))->toBeFalse(); + }); + + it('deletes customer by hashcode and clears cache', function (): void { + // GIVEN + $crmApi = \Mockery::mock(CrmApiV4::class); + $cacheRepository = \Mockery::mock(CacheRepository::class); + $uuid = UuidHelper::v4(); + $expectedHashKey = "crm_customer_hashcode_{$uuid->toString()}"; + + $cacheRepository->shouldReceive('get')->with($expectedHashKey)->once()->andReturnNull(); + $cacheRepository->shouldReceive('delete')->with($expectedHashKey)->once(); + + $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(); + }); + + it('returns true when deleting a customer already missing from CRM', function (): void { + // GIVEN + $crmApi = \Mockery::mock(CrmApiV4::class); + $cacheRepository = new ArrayCacheRepository(new ArrayStore()); + $uuid = UuidHelper::v4(); + + $apiException = \Mockery::mock(ApiErrorException::class); + $apiException->shouldReceive('getApiError')->andReturn(ApiError::modelNotFound); + + $apiInterface = \Mockery::mock(ApiInterface::class); + $apiInterface->shouldReceive('call')->once()->andThrow($apiException); + $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(); + }); + + it('throws CrmServiceException when CRM deletion fails', function (): void { + // GIVEN + $crmApi = \Mockery::mock(CrmApiV4::class); + $cacheRepository = new ArrayCacheRepository(new ArrayStore()); + $uuid = UuidHelper::v4(); + + $apiInterface = \Mockery::mock(ApiInterface::class); + $apiInterface->shouldReceive('call')->once()->andThrow(new CrmException('CRM delete error')); + $refProp = new \ReflectionProperty(ClientModel::class, 'apiInterface'); + $refProp->setValue(null, $apiInterface); + + $service = new CrmService($crmApi, $cacheRepository); + + // WHEN & THEN + 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 = UuidHelper::v4(); + $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 = UuidHelper::v4(); + $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(); + }); +}); diff --git a/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php b/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php index f14f8624..06ce0514 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; @@ -10,15 +12,15 @@ 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; use Domain\Models\ValueObjects\ShopperSiteCode; -use Illuminate\Contracts\Cache\Repository as CacheRepository; -use Illuminate\Foundation\Testing\RefreshDatabase; -use Psr\Log\LoggerInterface; - -uses(RefreshDatabase::class); +use Illuminate\Cache\ArrayStore; +use Illuminate\Cache\Repository as CacheRepository; +use Illuminate\Support\Carbon; +use Psr\Log\NullLogger; afterEach(function (): void { \Mockery::close(); @@ -31,8 +33,8 @@ describe('EmployeeSyncService', function (): void { $setting->employee_sites = ['PA', 'LY']; $setting->saveOrFail(); - $logger = app(LoggerInterface::class); - $cache = app(CacheRepository::class); + $logger = new NullLogger(); + $cache = new CacheRepository(new ArrayStore()); $upsertService = \Mockery::mock(EmployeeUpsertService::class); $employee = new ArcadiaEmployee( @@ -48,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( @@ -81,7 +87,7 @@ describe('EmployeeSyncService', function (): void { $cache, $arcadiaService, $upsertService, - app(GetSettingsQuery::class) + new GetSettingsQuery() ); // WHEN @@ -93,8 +99,8 @@ describe('EmployeeSyncService', function (): void { it('can use explicitly provided sites instead of settings', function (): void { // GIVEN - $logger = app(LoggerInterface::class); - $cache = app(CacheRepository::class); + $logger = new NullLogger(); + $cache = new CacheRepository(new ArrayStore()); $upsertService = \Mockery::mock(EmployeeUpsertService::class); $upsertService->shouldReceive('upsertEmployees') @@ -117,7 +123,7 @@ describe('EmployeeSyncService', function (): void { $cache, $arcadiaService, $upsertService, - app(GetSettingsQuery::class) + new GetSettingsQuery() ); // WHEN @@ -126,4 +132,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(); + }); }); diff --git a/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php b/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php index 08d662a2..1682ea30 100644 --- a/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php +++ b/tests/Integration/WithApp/App/Services/EmployeeUpsertServiceTest.php @@ -2,21 +2,21 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Services; + 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; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Ports\Services\EmployeeImportStorageService; -use Illuminate\Foundation\Testing\RefreshDatabase; -use Psr\Log\LoggerInterface; - -uses(RefreshDatabase::class); +use Kwaadpepper\Serial\Converters\NativeBaseConverter; +use Kwaadpepper\Serial\SerialCasterBuilder; +use Psr\Log\NullLogger; afterEach(function (): void { \Mockery::close(); @@ -29,8 +29,8 @@ describe('EmployeeUpsertService', function (): void { $setting->employee_sites = ['PA', 'LY']; $setting->saveOrFail(); - $logger = app(LoggerInterface::class); - $codeService = app(CodeGenerationService::class); + $logger = new NullLogger(); + $codeService = new CodeGenerationService(new SerialCasterBuilder(new NativeBaseConverter())); $storageService = \Mockery::mock(EmployeeImportStorageService::class); $employee = new ArcadiaEmployee( @@ -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') @@ -68,6 +72,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/FlashMessageServiceTest.php b/tests/Integration/WithApp/App/Services/FlashMessageServiceTest.php index ba92e410..b98d2b92 100644 --- a/tests/Integration/WithApp/App/Services/FlashMessageServiceTest.php +++ b/tests/Integration/WithApp/App/Services/FlashMessageServiceTest.php @@ -2,109 +2,95 @@ 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/App/Services/MailRegateServiceTest.php b/tests/Integration/WithApp/App/Services/MailRegateServiceTest.php new file mode 100644 index 00000000..59dda112 --- /dev/null +++ b/tests/Integration/WithApp/App/Services/MailRegateServiceTest.php @@ -0,0 +1,133 @@ +shouldReceive('generate') + ->once() + ->with( + \Mockery::type('array'), + \Mockery::on(function (array $rows) use ($orderReferenceValue): bool { + return count($rows) === 3 + && 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'); + + /** @var Mailer $mailer */ + $mailer = Mail::getFacadeRoot(); + $service = new MailRegateService($csvGenerator, $mailer); + + // WHEN + $service->processOrder($reference, $employeeMatricule, $pickupDay, [$line1, $line2, $line3]); + + // THEN + Mail::assertSent(RegateOrderMail::class, function (RegateOrderMail $mail) use ($orderReferenceValue): bool { + $attachments = $mail->attachments(); + + return $mail->hasTo('regate@example.com') + && count($attachments) === 1 + && str_contains((string) $attachments[0]->as, sprintf('BTQ-%s-', $orderReferenceValue)); + }); + }); + + it('throws RegateExportFailedException when mailer throws', function (): void { + // GIVEN + Config::set('mail.to.regate', 'regate@example.com'); + + $reference = new OrderReference(UuidHelper::v7()); + $employeeMatricule = new Matricule('1234567'); + $pickupDay = CarbonImmutable::parse('2025-01-01'); + + $csvGenerator = \Mockery::mock(CsvGenerator::class); + $csvGenerator->shouldReceive('generate')->once()->andReturn('csv_content'); + + $pendingMail = \Mockery::mock(PendingMail::class); + $pendingMail->shouldReceive('send') + ->once() + ->with(\Mockery::type(RegateOrderMail::class)) + ->andThrow(new \RuntimeException('SMTP connection refused')); + + $mailer = \Mockery::mock(Mailer::class); + $mailer->shouldReceive('to') + ->once() + ->andReturn($pendingMail); + + $service = new MailRegateService($csvGenerator, $mailer); + + // WHEN + $action = fn () => $service->processOrder($reference, $employeeMatricule, $pickupDay, []); + + // THEN + expect($action)->toThrow(RegateExportFailedException::class, 'SMTP connection refused'); + }); +}); diff --git a/tests/Integration/WithApp/App/Services/OrderServiceTest.php b/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php similarity index 53% rename from tests/Integration/WithApp/App/Services/OrderServiceTest.php rename to tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php index c8a1aeda..add14fea 100644 --- a/tests/Integration/WithApp/App/Services/OrderServiceTest.php +++ b/tests/Integration/WithApp/App/Services/OrderOwnershipServiceTest.php @@ -2,10 +2,13 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\App\Services; + use App\Models\Customer; use App\Models\Employee; use App\Models\Order; -use App\Services\OrderService; +use App\Services\OrderOwnershipService; +use Carbon\Carbon; use Carbon\CarbonImmutable; use Domain\Enums\OrderStatus; use Domain\Models\ValueObjects\Code; @@ -17,25 +20,36 @@ 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 Illuminate\Support\Facades\Date; use Money\Currency; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; -uses(RefreshDatabase::class); +covers(OrderOwnershipService::class); -covers(OrderService::class); +beforeEach(function (): void { + $now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris'); + Date::setTestNow($now); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); -describe('OrderService', function () { +afterEach(function (): void { + Date::setTestNow(); + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); + +describe('OrderOwnershipService', function () { it('returns true if order is owned by customer', function () { // GIVEN - $customer = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('owner@example.com'), ]); - Employee::forceCreate([ + Employee::query()->forceCreate([ 'id' => 301, 'customer_id' => $customer->id, 'matricule' => new Matricule('1000301'), @@ -49,16 +63,23 @@ describe('OrderService', function () { 'updated_at' => CarbonImmutable::now(), ]); - $order = Order::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), + $order = Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'reference' => new OrderReference(UuidHelper::v7()), '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'), ]); - $service = new OrderService(); + $service = new OrderOwnershipService(); // WHEN $result = $service->isOrderOwnedBy($order, $customer); @@ -69,13 +90,13 @@ describe('OrderService', function () { it('returns false if order is not owned by customer', function () { // GIVEN - $customer = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('notowner@example.com'), ]); - Employee::forceCreate([ + Employee::query()->forceCreate([ 'id' => 302, 'customer_id' => $customer->id, 'matricule' => new Matricule('1000302'), @@ -89,16 +110,23 @@ describe('OrderService', function () { 'updated_at' => CarbonImmutable::now(), ]); - $order = Order::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), + $order = Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'reference' => new OrderReference(UuidHelper::v7()), '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'), ]); - $service = new OrderService(); + $service = new OrderOwnershipService(); // WHEN $result = $service->isOrderOwnedBy($order, $customer); @@ -109,22 +137,29 @@ describe('OrderService', function () { it('returns false if customer has no employee', function () { // GIVEN - $customer = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), 'email' => new Email('noemp@example.com'), ]); - $order = Order::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), + $order = Order::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'reference' => new OrderReference(UuidHelper::v7()), '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'), ]); - $service = new OrderService(); + $service = new OrderOwnershipService(); // WHEN $result = $service->isOrderOwnedBy($order, $customer); diff --git a/tests/Integration/WithApp/App/Services/ProductDtoAssemblerTest.php b/tests/Integration/WithApp/App/Services/ProductDtoAssemblerTest.php new file mode 100644 index 00000000..1ea85f28 --- /dev/null +++ b/tests/Integration/WithApp/App/Services/ProductDtoAssemblerTest.php @@ -0,0 +1,161 @@ +name = "Gamme {$name}"; + $range->status = true; + $range->order = $sequence; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + $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' => $status, + ]); + $product->order = $sequence; + $product->price = Money::EUR(1000); + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt'; + $product->picture_large_title = 'title'; + $product->save(); + + return $product; +} + +describe('ProductDtoAssemblerService', function (): void { + it('maps several products with a constant number of queries', function (): void { + // GIVEN + $products = collect(range(1, 5)) + ->map(fn (int $i): Product => assemblerTestProduct("Produit {$i}")); + $fresh = Product::query()->whereIn('id', $products->pluck('id'))->get(); + + $assembler = new ProductDtoAssemblerService(new EloquentProductRepository()); + + // WHEN + DB::enableQueryLog(); + $dtos = $assembler->toDtosWithPricing($fresh); + $queryCount = count(DB::getQueryLog()); + DB::disableQueryLog(); + + // THEN + expect($dtos)->toHaveCount(5) + ->and($queryCount)->toBeLessThanOrEqual(3); // range + inco + validDiscount (0 requêtes sur products) + }); + + it('executes zero queries when relations are already eager-loaded on products', function (): void { + // GIVEN + $products = collect(range(1, 5)) + ->map(fn (int $i): Product => assemblerTestProduct("Produit Préchargé {$i}")); + $eagerLoaded = Product::query() + ->with(['range', 'inco', 'validDiscount']) + ->whereIn('id', $products->pluck('id')) + ->get(); + + $assembler = new ProductDtoAssemblerService(new EloquentProductRepository()); + + // WHEN + DB::enableQueryLog(); + $dtos = $assembler->toDtosWithPricing($eagerLoaded); + $queryCount = count(DB::getQueryLog()); + DB::disableQueryLog(); + + // THEN + expect($dtos)->toHaveCount(5) + ->and($queryCount)->toBe(0); + }); + + it('preserves input order and flags a product without INCO as not orderable', function (): void { + // GIVEN + $first = assemblerTestProduct('Premier'); + $second = assemblerTestProduct('Second'); + + $assembler = new ProductDtoAssemblerService(new EloquentProductRepository()); + + // WHEN + $dtos = $assembler->toDtos([$second, $first]); + + // THEN + expect($dtos[0]->name)->toBe('Second') + ->and($dtos[1]->name)->toBe('Premier') + ->and($dtos[0]->is_orderable)->toBeFalse(); + }); +}); + +describe('GetPublishedProductWithPricingQuery', function (): void { + it('returns the pricing DTO of a published product', function (): void { + // GIVEN + $product = assemblerTestProduct('Produit Publié'); + + // WHEN + $query = new GetPublishedProductWithPricingQuery(new ProductDtoAssemblerService(new EloquentProductRepository())); + $dto = $query( + new GetPublishedProductWithPricingQueryInput(new Slug((string) $product->slug)) + ); + + // THEN + assert($dto !== null); + expect($dto->product->name)->toBe('Produit Publié') + ->and($dto->pricing->hasDiscount)->toBeFalse(); + }); + + it('returns null for an unpublished product', function (): void { + // GIVEN + $product = assemblerTestProduct('Produit Masqué', status: false); + + // WHEN + $query = new GetPublishedProductWithPricingQuery(new ProductDtoAssemblerService(new EloquentProductRepository())); + $dto = $query( + new GetPublishedProductWithPricingQueryInput(new Slug((string) $product->slug)) + ); + + // THEN + expect($dto)->toBeNull(); + }); + + it('returns null for an unknown slug', function (): void { + // GIVEN + $slug = new Slug('slug-inexistant'); + + // WHEN + $query = new GetPublishedProductWithPricingQuery(new ProductDtoAssemblerService(new EloquentProductRepository())); + $dto = $query( + new GetPublishedProductWithPricingQueryInput($slug) + ); + + // THEN + expect($dto)->toBeNull(); + }); +}); diff --git a/tests/Integration/WithApp/App/Services/PublicHolidaysApiServiceTest.php b/tests/Integration/WithApp/App/Services/PublicHolidaysApiServiceTest.php new file mode 100644 index 00000000..7c2e4384 --- /dev/null +++ b/tests/Integration/WithApp/App/Services/PublicHolidaysApiServiceTest.php @@ -0,0 +1,57 @@ + Http::response([ + '2026-01-01' => '1er janvier', + '2026-12-25' => 'Jour de Noël', + ], 200), + ]); + + $service = new PublicHolidaysApiService(); + + // WHEN + $holidays = $service->fetchForYear(2026); + + // THEN + expect($holidays)->toHaveCount(2) + ->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') + ->and($holidays[1]->label)->toBe('Jour de Noël'); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://calendrier.api.gouv.fr/jours-feries/metropole/2026.json'); + }); + + it('throws when the API returns a non-successful status', function (): void { + // GIVEN + Http::fake([ + '*' => Http::response([], 503), + ]); + + $service = new PublicHolidaysApiService(); + + // WHEN / THEN + expect(fn () => $service->fetchForYear(2026)) + ->toThrow(\UnexpectedValueException::class, 'Failed to fetch calendar from api'); + }); + + it('throws when year is before 2026', function (): void { + // GIVEN + $service = new PublicHolidaysApiService(); + + // WHEN / THEN + expect(fn () => $service->fetchForYear(2025)) + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Services/StatsServiceTest.php b/tests/Integration/WithApp/App/Services/StatsServiceTest.php new file mode 100644 index 00000000..055d6113 --- /dev/null +++ b/tests/Integration/WithApp/App/Services/StatsServiceTest.php @@ -0,0 +1,340 @@ +forceCreate([ + 'id' => $id, + 'customer_id' => $customer?->id, + 'matricule' => new Matricule($matricule), + 'code' => new Code('ABCDE' . $codeSuffix), + 'nom' => 'Doe', + 'prenom' => 'John', + 'etablissement' => 'ETAB', + 'site' => 'SITE', + 'service' => '101', + 'created_at' => $timestamp, + 'updated_at' => $timestamp, + ]); + }; + + $createOrder = function ( + OrderStatus $status, + string $matricule, + CarbonImmutable $createdAt, + ?CarbonImmutable $pickupDay = null, + int $totalCents = 1000, + ): Order { + return Order::query()->forceCreate([ + 'id' => UuidHelper::v7($createdAt)->toString(), + 'reference' => new OrderReference(UuidHelper::v7()), + 'status' => $status->value, + 'total' => new Money($totalCents, new Currency('EUR')), + 'pickup_day' => $pickupDay, + 'employee' => new OrderEmployee( + new Matricule($matricule), + 'John', + 'Doe', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), + ), + 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), + ]); + }; + + it('calculates membership percentage and returns 0 when no active employees exist', function () use ($createEmployee): void { + // GIVEN + $service = new StatsService(new Currency('EUR')); + expect($service->getMembershipPercentage())->toBe(0.0); + + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), + 'email' => new Email('member@example.com'), + ]); + $createEmployee(101, '1000101', $customer); + $createEmployee(102, '1000102', null); + $createEmployee(103, '1000103', null); + $createEmployee(104, '1000104', null); + + // WHEN + $percentage = $service->getMembershipPercentage(); + + // THEN + expect($percentage)->toBe(25.0); + }); + + it('calculates membership rate within period and previous period', function () use ($createEmployee): void { + // GIVEN + $service = new StatsService(new Currency('EUR')); + $now = CarbonImmutable::now(); + $inRange = $now->subDays(3); + $outRange = $now->subDays(20); + $customer1 = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), + 'email' => new Email('range1@example.com'), + ]); + $createEmployee(201, '1000201', $customer1, $inRange); + $createEmployee(202, '1000202', null, $inRange); + $createEmployee(203, '1000203', null, $outRange); + + $start = $now->subDays(10); + $end = $now; + + // WHEN + $rate = $service->getMembershipRate($start, $end); + $previousPeriod = $service->getPreviousPeriod($start, $end); + + // THEN + expect($rate)->toBe(50.0) + ->and($previousPeriod->getStartDate()->toDateString())->toBe($start->copy()->subDays(11)->toDateString()) + ->and($previousPeriod->getIncludedEndDate()->toDateString())->toBe($start->copy()->subDays(1)->toDateString()); + }); + + it('computes customer and shop stats over current and previous periods', function () use ($createEmployee, $createOrder): void { + // GIVEN + $service = new StatsService(new Currency('EUR')); + $now = CarbonImmutable::now(); + $customer = Customer::query()->forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), + 'email' => new Email('stats@example.com'), + ]); + $createEmployee(301, '1000301', $customer, $now->subDays(3)); + $createEmployee(302, '1000302', null, $now->subDays(15)); + + $validatedOrder = $createOrder( + OrderStatus::VALIDATED, + '1000301', + $now->subDays(2), + $now->addDays(2), + totalCents: 1200, + ); + $createOrder( + OrderStatus::CANCELED, + '1000301', + $now->subDays(2), + $now->addDays(10), + ); + + $productVo = new OrderLineProduct( + incoId: new IncoId(1), + originalId: new ProductId(UuidHelper::v7()), + name: 'Poulet', + weight: new ProductWeight(1000, false), + brand: ProductBrand::loue, + orderUnit: OrderUnit::PCE, + price: new Money(1055, new Currency('EUR')), + discountedPrice: new Money(1055, new Currency('EUR')), + priceKgTtc: new Money(1055, new Currency('EUR')), + taxRate: TaxRate::TVA_5_5, + ); + OrderLine::query()->forceCreate([ + 'order_id' => $validatedOrder->id, + 'product' => $productVo, + 'quantity' => 2, + 'unit_price' => new Money(1000, new Currency('EUR')), + 'unit_tax' => new Money(55, new Currency('EUR')), + 'unit_discount' => new Money(0, new Currency('EUR')), + 'tax_rate' => TaxRate::TVA_5_5, + 'total_ht' => new Money(2000, new Currency('EUR')), + 'total_ttc' => new Money(2110, new Currency('EUR')), + 'total_tax' => new Money(110, new Currency('EUR')), + 'total_discount' => new Money(0, new Currency('EUR')), + ]); + + // WHEN + $customerStats = $service->getStats(StatsCustomerType::cases(), $now->subDays(5), $now); + $shopStats = $service->getStats(StatsShopType::cases(), $now->subDays(5), $now); + + // THEN + expect($customerStats[StatsCustomerType::nbSalarie->value]['current'])->toBe(1) + ->and($customerStats[StatsCustomerType::nbSalarieWithAccount->value]['current'])->toBe(1) + ->and($customerStats[StatsCustomerType::membershipRate->value]['current'])->toBe(100.0) + ->and($shopStats[StatsShopType::nbValidateCmd->value]['current'])->toBe(1) + ->and($shopStats[StatsShopType::nbCanceledCmd->value]['current'])->toBe(1) + ->and($shopStats[StatsShopType::nbWaitingCmd->value]['current'])->toBe(0) + ->and($shopStats[StatsShopType::canceledRate->value]['current'])->toBe(50.0) + ->and($shopStats[StatsShopType::nbActiveClients->value]['current'])->toBe(1) + ->and($shopStats[StatsShopType::nbCmdWith7DayDelay->value]['current'])->toBe(1) + ->and($shopStats[StatsShopType::nbCmdWith14DayDelay->value]['current'])->toBe(0) + ->and($shopStats[StatsShopType::caHt->value]['current'])->toBe(20.0) + ->and($shopStats[StatsShopType::caTtc->value]['current'])->toBe(21.1) + ->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' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->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); + }); + + 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); + }); +}); diff --git a/tests/Integration/WithApp/Casts/OrderLineProductCastTest.php b/tests/Integration/WithApp/Casts/OrderLineProductCastTest.php deleted file mode 100644 index baafe54e..00000000 --- a/tests/Integration/WithApp/Casts/OrderLineProductCastTest.php +++ /dev/null @@ -1,155 +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)->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: '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/Integration/WithApp/Directories/EloquentCustomerDirectoryTest.php b/tests/Integration/WithApp/Directories/EloquentCustomerDirectoryTest.php deleted file mode 100644 index dc9a7790..00000000 --- a/tests/Integration/WithApp/Directories/EloquentCustomerDirectoryTest.php +++ /dev/null @@ -1,68 +0,0 @@ - Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), - 'email' => new Email('test@example.com'), - ]); - - // WHEN - $result = $directory->find(Uuid::fromString($customer->id)); - - // THEN - expect($result)->not->toBeNull(); - expect($result->id)->toBe($customer->id); - }); - - it('returns null if customer not found', function () { - // GIVEN - $directory = new EloquentCustomerDirectory(); - - // WHEN - $result = $directory->find(Uuid::uuid7()); - - // THEN - expect($result)->toBeNull(); - }); - - it('gets a customer by email', function () { - // GIVEN - $directory = new EloquentCustomerDirectory(); - $email = new Email('testfind@example.com'); - $customer = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), - 'email' => $email, - ]); - - // WHEN - $result = $directory->getCustomerByEmail($email); - - // THEN - expect($result)->not->toBeNull(); - expect($result->id)->toBe($customer->id); - }); - - it('returns null if customer by email not found', function () { - // GIVEN - $directory = new EloquentCustomerDirectory(); - $email = new Email('notfound@example.com'); - - // WHEN - $result = $directory->getCustomerByEmail($email); - - // THEN - expect($result)->toBeNull(); - }); -}); diff --git a/tests/Integration/WithApp/Directories/EloquentEmployeeDirectoryTest.php b/tests/Integration/WithApp/Directories/EloquentEmployeeDirectoryTest.php deleted file mode 100644 index 9840cbf6..00000000 --- a/tests/Integration/WithApp/Directories/EloquentEmployeeDirectoryTest.php +++ /dev/null @@ -1,213 +0,0 @@ - 100, - 'customer_id' => null, - 'matricule' => new Matricule('1000100'), - 'code' => new Code('C1111115'), - 'nom' => 'Doe', - 'prenom' => 'John', - 'etablissement' => 'ETAB', - 'site' => 'SITE', - 'service' => '101', - 'created_at' => CarbonImmutable::now(), - 'updated_at' => CarbonImmutable::now(), - ]); - - // WHEN - $result = $directory->find(100); - - // THEN - expect($result)->not->toBeNull(); - expect($result->id)->toBe($employee->id); - }); - - it('returns null if employee not found', function () { - // GIVEN - $directory = new EloquentEmployeeDirectory(); - - // WHEN - $result = $directory->find(9999); - - // THEN - expect($result)->toBeNull(); - }); - - it('gets the number of salaries in date range', function () { - // GIVEN - $directory = new EloquentEmployeeDirectory(); - - Employee::forceCreate([ - 'id' => 101, - 'customer_id' => null, - 'matricule' => new Matricule('1000101'), - 'code' => new Code('C1111116'), - 'nom' => 'Doe', - 'prenom' => 'John', - 'etablissement' => 'ETAB', - 'site' => 'SITE', - 'service' => '101', - 'created_at' => CarbonImmutable::now()->subDays(5), - 'updated_at' => CarbonImmutable::now()->subDays(5), - ]); - - Employee::forceCreate([ - 'id' => 102, - 'customer_id' => null, - 'matricule' => new Matricule('1000102'), - 'code' => new Code('C1111117'), - 'nom' => 'Doe', - 'prenom' => 'John', - 'etablissement' => 'ETAB', - 'site' => 'SITE', - 'service' => '101', - 'created_at' => CarbonImmutable::now()->subDays(15), - 'updated_at' => CarbonImmutable::now()->subDays(15), - ]); - - // WHEN - $start = CarbonImmutable::now()->subDays(10); - $end = CarbonImmutable::now(); - $count = $directory->countActiveEmployeesWithin($start, $end); - - // THEN - expect($count)->toBeGreaterThanOrEqual(1); - }); - it('gets the number of registered active salaries in date range', function () { - // GIVEN - $directory = new EloquentEmployeeDirectory(); - - $customer1 = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), - 'email' => new Email('test1_emp@example.com'), - 'created_at' => CarbonImmutable::now()->subDays(5), - ]); - Employee::forceCreate([ - 'id' => 103, - 'customer_id' => $customer1->id, - 'matricule' => new Matricule('1000103'), - 'code' => new Code('C1111118'), - 'nom' => 'Doe', - 'prenom' => 'John', - 'etablissement' => 'ETAB', - 'site' => 'SITE', - 'service' => '101', - 'created_at' => CarbonImmutable::now()->subDays(5), - 'updated_at' => CarbonImmutable::now()->subDays(5), - ]); - - $customer2 = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), - 'email' => new Email('test2_emp@example.com'), - 'created_at' => CarbonImmutable::now()->subDays(15), - ]); - Employee::forceCreate([ - 'id' => 104, - 'customer_id' => $customer2->id, - 'matricule' => new Matricule('1000104'), - 'code' => new Code('C1111119'), - 'nom' => 'Doe', - 'prenom' => 'John', - 'etablissement' => 'ETAB', - 'site' => 'SITE', - 'service' => '101', - 'created_at' => CarbonImmutable::now()->subDays(15), - 'updated_at' => CarbonImmutable::now()->subDays(15), - ]); - - // Customer without employee - Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), - 'email' => new Email('test3_emp@example.com'), - 'created_at' => CarbonImmutable::now()->subDays(5), - ]); - - // WHEN - $start = CarbonImmutable::now()->subDays(10); - $end = CarbonImmutable::now(); - $count = $directory->countActiveRegisteredEmployeesWithin($start, $end); - - // THEN - expect($count)->toBeGreaterThanOrEqual(1); - }); - - it('gets total registered active salaries', function () { - // GIVEN - $directory = new EloquentEmployeeDirectory(); - - $customer1 = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), - 'email' => new Email('test1t_emp@example.com'), - ]); - Employee::forceCreate([ - 'id' => 105, - 'customer_id' => $customer1->id, - 'matricule' => new Matricule('1000105'), - 'code' => new Code('C111111A'), - 'nom' => 'Doe', - 'prenom' => 'John', - 'etablissement' => 'ETAB', - 'site' => 'SITE', - 'service' => '101', - 'created_at' => CarbonImmutable::now(), - 'updated_at' => CarbonImmutable::now(), - ]); - - $customer2 = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), - 'email' => new Email('test2t_emp@example.com'), - ]); - // no employee for customer2 - - // WHEN - $count = $directory->countActiveRegisteredEmployees(); - - // THEN - expect($count)->toBeGreaterThanOrEqual(1); - }); - - it('gets total active employees', function () { - // GIVEN - $directory = new EloquentEmployeeDirectory(); - - Employee::forceCreate([ - 'id' => 106, - 'customer_id' => null, - 'matricule' => new Matricule('1000106'), - 'code' => new Code('C1111121'), - 'nom' => 'Doe', - 'prenom' => 'John', - 'etablissement' => 'ETAB', - 'site' => 'SITE', - 'service' => '101', - 'created_at' => CarbonImmutable::now(), - 'updated_at' => CarbonImmutable::now(), - ]); - - // WHEN - $count = $directory->countActiveEmployees(); - - // THEN - expect($count)->toBeGreaterThanOrEqual(1); - }); -}); diff --git a/tests/Integration/WithApp/Directories/EloquentOrderDirectoryTest.php b/tests/Integration/WithApp/Directories/EloquentOrderDirectoryTest.php deleted file mode 100644 index da594880..00000000 --- a/tests/Integration/WithApp/Directories/EloquentOrderDirectoryTest.php +++ /dev/null @@ -1,323 +0,0 @@ - Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), - 'email' => new Email('noemp@example.com'), - ]); - - $pagination = Pagination::ofPage(new PageNumber(1), new PageSize(10)); - - // WHEN - $result = $directory->getPaginatedOrdersOf($customer, $pagination); - - // THEN - expect($result->total())->toBe(0); - }); - - it('returns paginated orders for customer with employee', function () { - // GIVEN - $directory = new EloquentOrderDirectory(); - $customer = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), - 'email' => new Email('hasemp@example.com'), - ]); - Employee::forceCreate([ - 'id' => 201, - 'customer_id' => $customer->id, - 'matricule' => new Matricule('1000201'), - 'nom' => 'Doe', - 'prenom' => 'John', - 'code' => new Code('ABCDEF19'), - 'etablissement' => 'ETAB', - 'site' => 'SITE', - 'service' => '101', - 'created_at' => CarbonImmutable::now(), - 'updated_at' => CarbonImmutable::now(), - ]); - - Order::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), - 'status' => OrderStatus::VALIDATED->value, - 'total' => new Money(1000, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('1000201'), 'John', 'Doe', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), - 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), - ]); - - Order::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), - 'status' => OrderStatus::VALIDATED->value, - 'total' => new Money(1000, new Currency('EUR')), - 'employee' => new OrderEmployee(new Matricule('1000999'), 'John', 'Doe', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), - 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), - ]); - - $pagination = Pagination::ofPage(new PageNumber(1), new PageSize(10)); - - // WHEN - $result = $directory->getPaginatedOrdersOf($customer, $pagination); - - // THEN - expect($result->total())->toBe(1); - }); - - it('finds an order by uuid', function () { - // GIVEN - $directory = new EloquentOrderDirectory(); - $order = Order::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), - 'total' => new Money(1000, new Currency('EUR')), - 'status' => OrderStatus::VALIDATED->value, - 'employee' => new OrderEmployee(new Matricule('1000999'), 'John', 'Doe', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), - 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), - ]); - - // WHEN - $result = $directory->find(Uuid::fromString($order->id)); - - // THEN - expect($result)->not->toBeNull(); - expect($result->id)->toBe($order->id); - }); - - it('returns null if order not found', function () { - // GIVEN - $directory = new EloquentOrderDirectory(); - - // WHEN - $result = $directory->find(Uuid::uuid7()); - - // THEN - expect($result)->toBeNull(); - }); - - it('finds order of customer', function () { - // GIVEN - $directory = new EloquentOrderDirectory(); - $customer = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), - 'email' => new Email('findof@example.com'), - ]); - Employee::forceCreate([ - 'id' => 202, - 'customer_id' => $customer->id, - 'matricule' => new Matricule('1000202'), - 'nom' => 'Doe', - 'prenom' => 'John', - 'code' => new Code('ABCDEF22'), - 'etablissement' => 'ETAB', - 'site' => 'SITE', - 'service' => '101', - 'created_at' => CarbonImmutable::now(), - 'updated_at' => CarbonImmutable::now(), - ]); - - $orderId = Uuid::uuid7()->toString(); - Order::forceCreate([ - 'id' => $orderId, - 'reference' => new OrderReference(Uuid::uuid7()), - 'total' => new Money(1000, new Currency('EUR')), - 'status' => OrderStatus::VALIDATED->value, - 'employee' => new OrderEmployee(new Matricule('1000202'), 'John', 'Doe', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), - 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), - ]); - - // WHEN - $result = $directory->findOf($customer, Uuid::fromString($orderId)); - - // THEN - expect($result)->not->toBeNull(); - expect($result->id)->toBe($orderId); - }); - - it('gets validated orders in date range', function () { - // GIVEN - $directory = new EloquentOrderDirectory(); - - $pastDate = CarbonImmutable::now()->subDays(5); - Order::forceCreate([ - 'id' => Uuid::uuid7($pastDate)->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), - 'total' => new Money(1000, new Currency('EUR')), - 'status' => OrderStatus::VALIDATED->value, - 'employee' => new OrderEmployee(new Matricule('1000999'), 'John', 'Doe', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), - 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), - ]); - Order::forceCreate([ - 'id' => Uuid::uuid7($pastDate)->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), - 'total' => new Money(1000, new Currency('EUR')), - 'status' => OrderStatus::WAITING->value, - 'employee' => new OrderEmployee(new Matricule('1000999'), 'John', 'Doe', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), - 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), - ]); - - // WHEN - $start = CarbonImmutable::now()->subDays(10); - $end = CarbonImmutable::now(); - $results = $directory->getValidatedOrders($start, $end); - - // THEN - expect($results->count())->toBeGreaterThanOrEqual(1); - }); - - it('gets orders by status in date range', function () { - // GIVEN - $directory = new EloquentOrderDirectory(); - - $pastDate = CarbonImmutable::now()->subDays(5); - Order::forceCreate([ - 'id' => Uuid::uuid7($pastDate)->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), - 'total' => new Money(1000, new Currency('EUR')), - 'status' => OrderStatus::CANCELED->value, - 'employee' => new OrderEmployee(new Matricule('1000999'), 'John', 'Doe', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), - 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), - ]); - - // WHEN - $start = CarbonImmutable::now()->subDays(10); - $end = CarbonImmutable::now(); - $results = $directory->getOrdersByStatus(OrderStatus::CANCELED, $start, $end); - - // THEN - expect($results)->toBeInstanceOf(Collection::class); - }); - - it('gets number of active clients in date range', function () { - // GIVEN - $directory = new EloquentOrderDirectory(); - - $customer = Customer::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'hashcode' => Uuid::uuid4()->toString(), - 'email' => new Email('active@example.com'), - ]); - Employee::forceCreate([ - 'id' => 203, - 'customer_id' => $customer->id, - 'matricule' => new Matricule('1000203'), - 'nom' => 'Doe', - 'prenom' => 'John', - 'code' => new Code('ABCDEF21'), - 'etablissement' => 'ETAB', - 'site' => 'SITE', - 'service' => '101', - 'created_at' => CarbonImmutable::now(), - 'updated_at' => CarbonImmutable::now(), - ]); - - $pastDate = CarbonImmutable::now()->subDays(5); - Order::forceCreate([ - 'id' => Uuid::uuid7($pastDate)->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), - 'total' => new Money(1000, new Currency('EUR')), - 'status' => OrderStatus::VALIDATED->value, - 'employee' => new OrderEmployee(new Matricule('1000203'), 'John', 'Doe', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), - 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), - ]); - - // WHEN - $start = CarbonImmutable::now()->subDays(10); - $end = CarbonImmutable::now(); - $count = $directory->getNbActiveClients($start, $end); - - // THEN - expect($count)->toBeGreaterThanOrEqual(1); - }); - - it('gets CA HT', function () { - // GIVEN - $directory = new EloquentOrderDirectory(); - - $pastDate = CarbonImmutable::now()->subDays(5); - $order = Order::forceCreate([ - 'id' => Uuid::uuid7($pastDate)->toString(), - 'reference' => new OrderReference(Uuid::uuid7()), - 'total' => new Money(1000, new Currency('EUR')), - 'status' => OrderStatus::VALIDATED->value, - 'employee' => new OrderEmployee(new Matricule('1000999'), 'John', 'Doe', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), - 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), - ]); - - OrderLine::forceCreate([ - 'id' => 1, - 'order_id' => $order->id, - 'quantity' => 2, - 'unit_price' => new Money(500, new Currency('EUR')), - 'unit_tax' => new Money(100, new Currency('EUR')), - 'unit_discount' => new Money(0, new Currency('EUR')), - 'tax_rate' => TaxRate::TVA_20, - 'total_ht' => new Money(1000, new Currency('EUR')), - 'total_tax' => new Money(200, new Currency('EUR')), - 'total_discount' => new Money(0, new Currency('EUR')), - 'total_ttc' => new Money(1200, new Currency('EUR')), - 'product' => new OrderLineProduct( - incoId: new IncoId(12345), - originalId: new ProductId(Uuid::uuid7()), - name: 'test product', - weight: new ProductWeight(1000, false), - brand: ProductBrand::none, - orderUnit: OrderUnit::PCE, - price: new Money(500, new Currency('EUR')), - discountedPrice: new Money(500, new Currency('EUR')), - priceKgTtc: new Money(600, new Currency('EUR')), - taxRate: TaxRate::TVA_20 - ), - ]); - - // WHEN - $start = CarbonImmutable::now()->subDays(10); - $end = CarbonImmutable::now(); - $caHt = $directory->getCaHt($start, $end); - $caTtc = $directory->getCaTtc($start, $end); - $qty = $directory->getTotalQuantity($start, $end); - - // THEN - expect($caHt)->toBeGreaterThanOrEqual(10.0); - expect($caTtc)->toBeGreaterThanOrEqual(12.0); - expect($qty)->toBeGreaterThanOrEqual(2); - }); -}); 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/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(); @@ -23,7 +23,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']]) @@ -35,7 +35,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('_-_'); @@ -46,73 +46,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('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-'); - 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/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..c0032a65 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Directories/EloquentShopDirectoryTest.php @@ -2,86 +2,68 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Infra\Adapters\Directories; + 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; +use Shared\Helpers\UuidHelper; -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([ - 'name' => 'Shop 1', - 'address' => 'Addr 1', - 'postcode' => '75000', - 'city' => 'Paris', - 'default' => false, - ]); - Shop::forceCreate([ - 'name' => 'Shop 2', - 'address' => 'Addr 2', - 'postcode' => '75001', - 'city' => 'Paris', - 'default' => false, - ]); - $directory = new EloquentShopDirectory(); - - // WHEN - $shops = $directory->getAll(); - - // THEN - expect($shops)->toHaveCount(2) - ->and($shops[0])->toBeInstanceOf(\Domain\Models\Entities\Shop::class); -}); - -it('finds a shop by its identifier', function () { - // GIVEN - $model = Shop::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(); +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(); + + // 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/Events/LaravelDomainEventDispatcherTest.php b/tests/Integration/WithApp/Infra/Adapters/Events/LaravelDomainEventDispatcherTest.php new file mode 100644 index 00000000..19c39153 --- /dev/null +++ b/tests/Integration/WithApp/Infra/Adapters/Events/LaravelDomainEventDispatcherTest.php @@ -0,0 +1,68 @@ +dispatch($event); + + // THEN + Event::assertDispatched($event::class, 1); + }); + + it('buffers events and dispatches them only on outermost flush', function (): void { + // GIVEN + Event::fake(); + $dispatcher = new LaravelDomainEventDispatcher(); + $event = new class () implements DomainEvent + { + }; + + // WHEN + $dispatcher->beginBuffering(); + $dispatcher->beginBuffering(); + $dispatcher->dispatch($event); + + Event::assertNothingDispatched(); + + $dispatcher->flush(); + Event::assertNothingDispatched(); + + $dispatcher->flush(); + + // THEN + Event::assertDispatched($event::class, 1); + }); + + it('discards buffered events without dispatching them', function (): void { + // GIVEN + Event::fake(); + $dispatcher = new LaravelDomainEventDispatcher(); + $event = new class () implements DomainEvent + { + }; + + // WHEN + $dispatcher->beginBuffering(); + $dispatcher->dispatch($event); + $dispatcher->discard(); + $dispatcher->flush(); + + // THEN + Event::assertNothingDispatched(); + }); +}); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php index d6c22341..aa3d4154 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php @@ -2,97 +2,154 @@ 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; -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; +use Shared\Helpers\UuidHelper; +use Webmozart\Assert\Assert; -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(); - }); - } +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')); - 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(); - }); - } + // WHEN + $result = $repo->find($orderId); - DB::table('orders')->delete(); - DB::table('order_lines')->delete(); -}); - -it('returns null when finding a non-existent order by id', function () { - // GIVEN - $repo = new EloquentOrderRepository(new Currency('EUR')); - $orderId = new OrderId(Uuid::fromString('018e4567-e89b-72d3-a456-426614174001')); - - // 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(new Currency('EUR')); - - $domainOrder = $repo->find(new OrderId(Uuid::fromString('018e4567-e89b-72d3-a456-426614174002'))); - $domainOrder->status = OrderStatus::VALIDATED; - - // WHEN - $repo->persist($domainOrder); - - // THEN - $updatedOrder = DB::table('orders')->where('id', '018e4567-e89b-72d3-a456-426614174002')->first(); - expect($updatedOrder->status)->toBe(OrderStatus::VALIDATED->value); + // 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 0718e9db..13a0d326 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php @@ -2,156 +2,121 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Infra\Adapters\Repositories; + 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\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Schema; use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; -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(); - }); - } +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', + ]); - 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(); - }); - } + $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, + ]); - 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('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('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(); - $shop = Shop::forceCreate(['id' => $shopUuid->toString(), 'name' => 'Shop 1', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']); - - $exUuid = Uuid::uuid7(); - $ex1 = PickupException::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); - $period = CarbonPeriod::create('2023-01-01', '2023-01-31'); - - $repo = new EloquentPickupExceptionRepository(); - - // WHEN - $result = $repo->getExceptionsForShop($shopId, $period); - - // 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'); -}); - -it('retrieves all exceptions', function () { - // GIVEN - $exUuid = Uuid::uuid7(); - PickupException::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])->toBeInstanceOf(PickupExceptionOnDate::class) - ->and($result[0]->id->value->toString())->toBe($exUuid->toString()); -}); - -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']); - - $exUuid = Uuid::uuid7(); - $ex1 = PickupException::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])->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'); + $shopId = new ShopId($shopUuid); + $period = CarbonPeriod::create('2023-01-01', '2023-01-31'); + + $repo = new EloquentPickupExceptionRepository(); + + // 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 = 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 37d35260..def8aca2 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php @@ -2,140 +2,262 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Infra\Adapters\Repositories; + 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; +use Shared\Helpers\UuidHelper; -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); + return $range->id; +} - // Required for toDomain - $table->string('status')->nullable(); - $table->integer('price')->nullable(); - $table->integer('price_kg')->nullable(); - $table->string('origin_country')->nullable(); - $table->text('conservation')->nullable(); +describe('EloquentProductRepository', function (): void { + it('retrieves a basket product', function () { + // GIVEN + $uuid = UuidHelper::v7()->toString(); + $currency = new Currency('EUR'); + $rangeId = createRepoTestProductRange(); - $table->timestamps(); - }); - } + 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]); - DB::table('products')->delete(); -}); - -it('retrieves a basket product', function () { - // GIVEN - $uuid = Uuid::uuid7()->toString(); - $currency = new Currency('EUR'); - - Product::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' => 1, - '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), - ]); - - $id = new ProductId(Uuid::fromString($uuid)); - - $repo = new EloquentProductRepository(); - - // WHEN - $result = $repo->getBasketProduct($id, 2); - - // THEN - expect($result)->toBeInstanceOf(BasketProduct::class) - ->and($result->name)->toBe('Product Name') - ->and($result->qty)->toBe(2); -}); - -it('finds a product by id', function () { - // GIVEN - $uuid = Uuid::uuid7()->toString(); - - Product::forceCreate([ - 'id' => $uuid, - 'name' => 'Product Name', - 'tax_rate' => 1, - 'weight' => 1000, - 'brand' => 'none', - 'slug' => 'product-name', - 'invoicing_unit' => 'PCE', - 'sell_unit' => 'PCE', - 'range_id' => 1, - '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(); + $id = new ProductId(UuidHelper::fromString($uuid)); + + $repo = new EloquentProductRepository(); + + // 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 = 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 a3b7d31f..7cbb58d4 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; @@ -10,227 +12,186 @@ 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; +use Shared\Helpers\UuidHelper; -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(); - }); - } +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, + ]); - 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(); - }); - } + 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, + ]); - 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(); - }); - } + $repo = new EloquentShopRepository(); - 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([ - 'name' => 'Shop X', - 'address' => 'Addr X', - 'postcode' => '75000', - 'city' => 'Paris', - 'default' => false, - ]); - - Employee::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(); - - // 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::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::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::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::forceCreate([ - 'id' => Uuid::uuid7()->toString(), - 'name' => 'Shop 1', - 'address' => 'Addr 1', - 'postcode' => '75000', - 'city' => 'Paris', - 'default' => false, - ]); - $defaultShop = Shop::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); + // 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(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 d527e4e7..b98a438c 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; @@ -13,197 +15,167 @@ 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; +use Shared\Helpers\UuidHelper; -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(); - }); - } +describe('EloquentShopperRepository', function (): void { + it('retrieves shopper by id', function () { + // GIVEN + $uuid = UuidHelper::v7()->toString(); - 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(); - }); - } + Customer::query()->forceCreate([ + 'id' => $uuid, + 'email' => new Email('test@example.com'), + 'hashcode' => UuidHelper::v4()->toString(), + ]); - DB::table('customers')->delete(); - DB::table('employees')->delete(); -}); - -it('retrieves shopper by id', function () { - // GIVEN - $uuid = Uuid::uuid7()->toString(); - - Customer::forceCreate([ - 'id' => $uuid, - 'email' => new Email('test@example.com'), - 'hashcode' => Uuid::uuid4()->toString(), - ]); - - Employee::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(); - - // WHEN - $result = $repo->find(new ShopperId(Uuid::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::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::forceCreate([ - 'id' => $uuid, - 'email' => new Email('test@example.com'), - 'hashcode' => Uuid::uuid4()->toString(), - ]); - - Employee::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)->toBeInstanceOf(Shopper::class); -}); - -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::forceCreate([ - 'id' => $uuid, - 'email' => new Email('before@example.com'), - 'hashcode' => Uuid::uuid4()->toString(), - ]); - - Employee::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'); + 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(); + + // 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(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/Repositories/SessionBasketRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php similarity index 79% rename from tests/Integration/WithApp/Infra/Repositories/SessionBasketRepositoryTest.php rename to tests/Integration/WithApp/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php index 93e3914b..27527893 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; @@ -14,20 +14,27 @@ 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; +use Shared\Helpers\UuidHelper; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; 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 () { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); // WHEN $basket = getRepository()->find($basketId); @@ -38,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(); @@ -47,14 +54,13 @@ 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()]; - 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()) @@ -64,7 +70,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()) @@ -72,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')), @@ -83,7 +89,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), @@ -91,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')), @@ -114,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/Unit/Infra/Adapters/Services/AppAdminAuthServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/AppAdminAuthServiceTest.php similarity index 95% rename from tests/Unit/Infra/Adapters/Services/AppAdminAuthServiceTest.php rename to tests/Integration/WithApp/Infra/Adapters/Services/AppAdminAuthServiceTest.php index a74d6375..4dcf0514 100644 --- a/tests/Unit/Infra/Adapters/Services/AppAdminAuthServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/AppAdminAuthServiceTest.php @@ -2,8 +2,10 @@ declare(strict_types=1); -use App\Exceptions\AuthServiceException; +namespace Tests\Integration\WithApp\Infra\Adapters\Services; + use App\Models\User; +use Domain\Exceptions\AuthServiceException; use Illuminate\Contracts\Auth\StatefulGuard; use Infrastructure\Adapters\Services\AppAdminAuthService; use Mockery\MockInterface; @@ -91,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); @@ -101,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/Unit/Infra/Adapters/Services/AppCustomerAuthServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php similarity index 80% rename from tests/Unit/Infra/Adapters/Services/AppCustomerAuthServiceTest.php rename to tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php index 016f247d..c34daa12 100644 --- a/tests/Unit/Infra/Adapters/Services/AppCustomerAuthServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/AppCustomerAuthServiceTest.php @@ -2,34 +2,32 @@ declare(strict_types=1); -namespace Tests\Unit\Infra\Adapters\Services; +namespace Tests\Integration\WithApp\Infra\Adapters\Services; -use App\Exceptions\AuthServiceException; use App\Exceptions\CrmServiceException; use App\Models\Customer; use App\Services\CrmService; use Domain\Contracts\CustomerDetails; 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 Illuminate\Contracts\Debug\ExceptionHandler; use Infrastructure\Adapters\Services\AppCustomerAuthService; use Mockery; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; 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'; } @@ -37,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'); @@ -50,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'); @@ -64,37 +61,34 @@ 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(); + $customer->id = (string) UuidHelper::v7(); - $shopperService->shouldReceive('canCustomerPassOrdersApp')->withAnyArgs()->andReturn(true); - $guard->shouldReceive('login')->with($customer)->once(); - - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $service->logIn($customer); // THEN - expect(true)->toBeTrue(); + $guard->shouldHaveReceived('login')->with($customer)->once(); }); it('throws exception if logging in non-authenticatable', 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 @@ -103,28 +97,26 @@ 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); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $service->logout(); // THEN - expect(true)->toBeTrue(); + $guard->shouldHaveReceived('logout')->once(); }); it('checks if user is logged in', 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(); @@ -139,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(); @@ -157,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 { @@ -181,7 +171,7 @@ describe('AppCustomerAuthService', function (): void { return 'password'; } - public function getRememberToken() + public function getRememberToken(): string { return ''; } @@ -197,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(); @@ -210,27 +200,26 @@ 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(); // THEN - expect($returned)->toBeInstanceOf(Customer::class); + expect($returned->id)->toBe('cust-123'); }); it('throws exception when getting customer as mandatory but null', 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,9 +250,8 @@ 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()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $customer->hashcode = $hashcode; // DO NOT MOCK CrmCustomer @@ -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()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $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,9 +307,8 @@ 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()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $customer->hashcode = $hashcode; $crmCustomer = new CrmCustomer( @@ -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()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $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,17 +367,14 @@ 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()); + $hashcode = new CrmHashcode(UuidHelper::v4()); $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); - $service = new AppCustomerAuthService($guard, $crmService, $shopperService); + $service = new AppCustomerAuthService($guard, $crmService); // WHEN $action = fn () => $service->hasVerifiedEmail($customer); 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..d95aff3b --- /dev/null +++ b/tests/Integration/WithApp/Infra/Adapters/Services/AppSessionServiceTest.php @@ -0,0 +1,74 @@ +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 = UuidHelper::v7()->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()); + }); +}); 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..cc15035a --- /dev/null +++ b/tests/Integration/WithApp/Infra/Adapters/Services/DatabaseTunnelAttemptTrackerServiceTest.php @@ -0,0 +1,147 @@ +forceCreate([ + 'id' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), + 'email' => new Email('attempt-reuse@example.com'), + ]); + $shopperId = new ShopperId(UuidHelper::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' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), + 'email' => new Email('attempt-convert@example.com'), + ]); + $shopperId = new ShopperId(UuidHelper::fromString($customer->id)); + + $orderId = UuidHelper::v7()->toString(); + Order::query()->forceCreate([ + 'id' => $orderId, + 'reference' => new OrderReference(UuidHelper::v7()), + '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(UuidHelper::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' => UuidHelper::v7()->toString(), + 'hashcode' => UuidHelper::v4()->toString(), + 'email' => new Email('attempt-clear@example.com'), + ]); + $tracker->recordEntry(new ShopperId(UuidHelper::fromString($customer->id))); + + // WHEN + $listener->handle(new BasketRemoved(new BasketId(UuidHelper::v7()))); + + // THEN + expect($session->has('order_tunnel_attempt_id'))->toBeFalse() + ->and(OrderTunnelAttempt::query()->whereNull('converted_at')->count())->toBe(1); + }); +}); diff --git a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeImportStorageServiceTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeImportStorageServiceTest.php index ee8fa769..f9699af1 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 = []; @@ -65,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', @@ -79,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', @@ -93,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', @@ -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 88483682..4c41a9f8 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/EloquentEmployeeStatisticsServiceTest.php @@ -2,64 +2,112 @@ declare(strict_types=1); +namespace Tests\Integration\WithApp\Infra\Adapters\Services; + +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; +use Shared\Helpers\UuidHelper; -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(); - }); - } +describe('EloquentEmployeeStatisticsService', function (): void { + it('retrieves the weekly order total for a given employee', function () { + // GIVEN + $shop = Shop::factory()->create(); - 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']); - - DB::table('orders')->insert([ - 'id' => '018e4567-e89b-72d3-a456-426614174000', - 'shop_id' => 1, - '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 - ]); - - $service = new EloquentEmployeeStatisticsService(); - $start = CarbonImmutable::parse('2023-01-01'); - $end = CarbonImmutable::parse('2023-01-07'); - - // WHEN - $result = $service->getWeeklyTotalForEmployee(new Matricule('1234567'), $start, $end); - - // THEN - expect($result->getAmount())->toBe('1500') - ->and($result->getCurrency()->getCode())->toBe('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'); + + // 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' => 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/Integration/WithApp/Infra/Adapters/Services/LaravelTransactionManagerTest.php b/tests/Integration/WithApp/Infra/Adapters/Services/LaravelTransactionManagerTest.php index 7d720c0a..5a611a88 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Services/LaravelTransactionManagerTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Services/LaravelTransactionManagerTest.php @@ -2,21 +2,41 @@ declare(strict_types=1); -use Illuminate\Support\Facades\DB; +namespace Tests\Integration\WithApp\Infra\Adapters\Services; + +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(); + }); }); diff --git a/tests/Pest.php b/tests/Pest.php index 579b6d24..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,19 +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'); -pest()->extend(LaravelTestCase::class)->in('Unit/App/Casts'); -pest()->extend(LaravelTestCase::class)->in('Unit/Services'); diff --git a/tests/TestCase.php b/tests/TestCase.php index 7de55c2f..fd665209 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -7,13 +7,13 @@ 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; use LDC\LDCCRM\Transport\ApiInterface; use LDC\LDCCRM\Transport\Response as CrmResponse; use LDC\LDCCRM\Utils; -use Mockery; abstract class TestCase extends BaseTestCase { @@ -24,12 +24,14 @@ abstract class TestCase extends BaseTestCase { parent::setUp(); + Config::set('purifier.cachePath', sys_get_temp_dir() . '/purifier-testing-' . get_current_user()); + $this->mockCrmTransport(); } private function mockCrmTransport(): void { - $apiInterface = Mockery::mock(ApiInterface::class); + $apiInterface = \Mockery::mock(ApiInterface::class); $apiInterface->shouldReceive('call')->byDefault()->andReturn( new CrmResponse( ApiStatus::OK, 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/FinalizeOrderInputTest.php b/tests/Unit/App/Actions/Orders/FinalizeOrderInputTest.php deleted file mode 100644 index a283e7d7..00000000 --- a/tests/Unit/App/Actions/Orders/FinalizeOrderInputTest.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 FinalizeOrderInput(shopperId: $shopperId); - - // THEN - expect($input->shopperId)->toBe($shopperId); - }); -}); diff --git a/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php b/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php deleted file mode 100644 index 3db69d85..00000000 --- a/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php +++ /dev/null @@ -1,73 +0,0 @@ -shouldReceive('getBuilderCompletedOrFail') - ->once() - ->andReturn($builder); - $orderTunnelService->shouldReceive('finalizeOrder') - ->once() - ->with($builder) - ->andReturn($order); - - $action = new FinalizeOrder($orderTunnelService); - - // WHEN - $result = $action($input); - - // THEN - expect($result)->toBeInstanceOf(OrderReference::class) - ->and($result->value)->toBe($orderReference->value); - }); -}); 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/InitializeOrderTunnelTest.php b/tests/Unit/App/Actions/Orders/InitializeOrderTunnelTest.php deleted file mode 100644 index 40d840b9..00000000 --- a/tests/Unit/App/Actions/Orders/InitializeOrderTunnelTest.php +++ /dev/null @@ -1,36 +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/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/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); + }); +}); diff --git a/tests/Unit/App/Casts/OrderLineProductCastTest.php b/tests/Unit/App/Casts/OrderLineProductCastTest.php deleted file mode 100644 index 104d71a7..00000000 --- a/tests/Unit/App/Casts/OrderLineProductCastTest.php +++ /dev/null @@ -1,144 +0,0 @@ -get($model, 'product', null, []); - - // THEN -})->throws(\InvalidArgumentException::class, 'The value cannot be null.'); - -it('throws exception when getting non-string', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); - - // WHEN - $cast->get($model, 'product', 123, []); - - // THEN -})->throws(\InvalidArgumentException::class, 'The value must be a string.'); - -it('gets an order line product', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); - $uuid = Uuid::uuid7()->toString(); - - $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', - ]); - - // WHEN - $product = $cast->get($model, 'product', $json, []); - - // 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'); -}); - -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(); - - $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, - ]); - - // WHEN - $product = $cast->get($model, 'product', $json, []); - - // THEN - expect($product)->toBeInstanceOf(OrderLineProduct::class) - ->and($product->taxRate)->toBe(TaxRate::TVA_20) - ->and($product->picture)->toBeNull(); -}); - -it('throws exception when setting invalid type', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); - - // WHEN - $cast->set($model, 'product', 'invalid', []); - - // THEN -})->throws( - \InvalidArgumentException::class, - 'The given value is not an instance of OrderLineProduct.' -); - -it('sets an order line product', function () { - // GIVEN - $cast = new OrderLineProductCast(); - $model = \Mockery::mock(Model::class); - $currency = resolve(Currency::class); - - $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' - ); - - // WHEN - $value = $cast->set($model, 'product', $product, []); - - // THEN - expect($value)->toBeJson(); -}); diff --git a/tests/Unit/App/Casts/OrderReferenceCastTest.php b/tests/Unit/App/Casts/OrderReferenceCastTest.php deleted file mode 100644 index 2b1b48d9..00000000 --- a/tests/Unit/App/Casts/OrderReferenceCastTest.php +++ /dev/null @@ -1,92 +0,0 @@ -get($model, 'reference', $value, []); - - // THEN - expect($reference)->toBeInstanceOf(OrderReference::class) - ->and((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($reference)->toBeInstanceOf(OrderReference::class) - ->and((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 - $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)); -}); diff --git a/tests/Unit/App/Actions/Common/ChangeModelOrderPositionInputTest.php b/tests/Unit/App/Cqs/Actions/Common/ChangeModelOrderPositionInputTest.php similarity index 96% rename from tests/Unit/App/Actions/Common/ChangeModelOrderPositionInputTest.php rename to tests/Unit/App/Cqs/Actions/Common/ChangeModelOrderPositionInputTest.php index 4a681f65..ec2ae4d6 100644 --- a/tests/Unit/App/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/Actions/Common/ExecuteMassActionInputTest.php b/tests/Unit/App/Cqs/Actions/Common/ExecuteMassActionInputTest.php similarity index 85% rename from tests/Unit/App/Actions/Common/ExecuteMassActionInputTest.php rename to tests/Unit/App/Cqs/Actions/Common/ExecuteMassActionInputTest.php index cb1a478d..c60630f5 100644 --- a/tests/Unit/App/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; @@ -29,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/Actions/Customers/RegisterCustomerInputTest.php b/tests/Unit/App/Cqs/Actions/Customers/RegisterCustomerInputTest.php similarity index 99% rename from tests/Unit/App/Actions/Customers/RegisterCustomerInputTest.php rename to tests/Unit/App/Cqs/Actions/Customers/RegisterCustomerInputTest.php index ece9b841..8604dc8d 100644 --- a/tests/Unit/App/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/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/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..bafe42a4 100644 --- a/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesTest.php +++ b/tests/Unit/App/Cqs/Actions/Employee/ImportEmployeesTest.php @@ -2,10 +2,11 @@ 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; -use App\Cqs\Actions\Employee\ImportEmployeesOutput; use App\Services\ArcadiaEmployee; use App\Services\EmployeeCsvImportLineService; use App\Services\EmployeeCsvReaderService; @@ -70,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/Actions/Faqs/CreateFaqInputTest.php b/tests/Unit/App/Cqs/Actions/Faqs/CreateFaqInputTest.php similarity index 97% rename from tests/Unit/App/Actions/Faqs/CreateFaqInputTest.php rename to tests/Unit/App/Cqs/Actions/Faqs/CreateFaqInputTest.php index 5b0bf469..a7157397 100644 --- a/tests/Unit/App/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/Actions/Faqs/UpdateFaqInputTest.php b/tests/Unit/App/Cqs/Actions/Faqs/UpdateFaqInputTest.php similarity index 97% rename from tests/Unit/App/Actions/Faqs/UpdateFaqInputTest.php rename to tests/Unit/App/Cqs/Actions/Faqs/UpdateFaqInputTest.php index 1cdd118d..b605f2f8 100644 --- a/tests/Unit/App/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/Actions/Orders/ApplyPickTimeSlotTest.php b/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php similarity index 50% rename from tests/Unit/App/Actions/Orders/ApplyPickTimeSlotTest.php rename to tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php index ffc67a68..be4eadf6 100644 --- a/tests/Unit/App/Actions/Orders/ApplyPickTimeSlotTest.php +++ b/tests/Unit/App/Cqs/Actions/Orders/ApplyPickTimeSlotTest.php @@ -2,8 +2,11 @@ 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\Enums\ApplyPickTimeSlotStatus; use Carbon\CarbonImmutable; use Domain\Builders\OrderBuilderWithBasket; use Domain\Models\Entities\Shop; @@ -11,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, @@ -25,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', @@ -57,6 +60,53 @@ describe('ApplyPickTimeSlot', function (): void { $result = $action($input); // THEN - expect($result)->toBe($slot); + expect($result->status)->toBe(ApplyPickTimeSlotStatus::MATCHED) + ->and($result->timeSlot)->toBe($slot); + }); + + it('returns unavailable output when no time slot matches', function (): void { + // GIVEN + $shopperId = new ShopperId(UuidHelper::v7()); + $timeslot = CarbonImmutable::parse('2026-10-15'); + $input = new ApplyPickTimeSlotInput( + shopperId: $shopperId, + timeslot: $timeslot, + ); + + $builder = \Mockery::mock(OrderBuilderWithBasket::class); + $shop = new Shop( + id: new ShopId(UuidHelper::v7()), + name: 'Shop 1', + address: '1 rue Test', + postcode: '75001', + city: 'Paris', + ); + $timeSlots = []; + + $orderTunnelService = \Mockery::mock(OrderTunnelService::class); + $orderTunnelService->shouldReceive('getBuilderFromBasketOrFail') + ->once() + ->andReturn($builder); + $orderTunnelService->shouldReceive('getShopForCustomer') + ->once() + ->with($shopperId) + ->andReturn($shop); + $orderTunnelService->shouldReceive('getAvailableTimeSlots') + ->once() + ->with($shop) + ->andReturn($timeSlots); + $orderTunnelService->shouldReceive('applyTimeSlot') + ->once() + ->with($builder, $shop, $timeslot, $timeSlots) + ->andReturnNull(); + + $action = new ApplyPickTimeSlot($orderTunnelService); + + // WHEN + $result = $action($input); + + // THEN + expect($result->status)->toBe(ApplyPickTimeSlotStatus::UNAVAILABLE) + ->and($result->timeSlot)->toBeNull(); }); }); diff --git a/tests/Unit/App/Cqs/Actions/Orders/CancelOrderTest.php b/tests/Unit/App/Cqs/Actions/Orders/CancelOrderTest.php new file mode 100644 index 00000000..03c99c59 --- /dev/null +++ b/tests/Unit/App/Cqs/Actions/Orders/CancelOrderTest.php @@ -0,0 +1,56 @@ +id = $orderId->value->toString(); + + $orderService = \Mockery::mock(OrderService::class); + $orderService->shouldReceive('cancelOrder') + ->once() + ->with(\Mockery::on(fn (OrderId $id) => $id->equals($orderId))); + + $action = new CancelOrder($orderService); + + // WHEN + $output = $action(new CancelOrderInput($order)); + + // THEN + expect($output)->toBe(CancelOrderOutput::CANCELLED); + }); + + it('returns NOT_FOUND when OrderService throws DomainException', function (): void { + // GIVEN + $orderId = new OrderId(UuidHelper::v7()); + $order = new Order(); + $order->id = $orderId->value->toString(); + + $orderService = \Mockery::mock(OrderService::class); + $orderService->shouldReceive('cancelOrder') + ->once() + ->with(\Mockery::on(fn (OrderId $id) => $id->equals($orderId))) + ->andThrow(new \DomainException('Order not found')); + + $action = new CancelOrder($orderService); + + // WHEN + $output = $action(new CancelOrderInput($order)); + + // THEN + expect($output)->toBe(CancelOrderOutput::NOT_FOUND); + }); +}); diff --git a/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php new file mode 100644 index 00000000..7517aba5 --- /dev/null +++ b/tests/Unit/App/Cqs/Actions/Orders/PlacePendingOrderTest.php @@ -0,0 +1,282 @@ +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->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 when BasketPriceChangedException is thrown', function (): void { + // GIVEN + $input = new PlacePendingOrderInput(); + $builder = \Mockery::mock(OrderBuilderCompleted::class); + $refreshedBasket = new Basket(new BasketId(UuidHelper::v7()), []); + /** @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->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('builds shopper lock key and returns LOCK_TIMEOUT output on lock timeout', function (): void { + // GIVEN + $shopperId = new ShopperId(UuidHelper::v7()); + $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); + + // WHEN + $key = $action->lockKey($input); + $timeout = $action->onLockTimeout($input); + + // THEN + expect($key)->toBe("order:finalize:shopper:{$shopperId->value}") + ->and($timeout->status)->toBe(PlacePendingOrderStatus::LOCK_TIMEOUT); + }); +}); + +describe('ExportOrderToRegate, ConfirmPlacedOrder and FailPendingOrder', function (): void { + it('exports order via OrderTunnelService and handles lock timeout', function (): void { + // GIVEN + $orderId = new OrderId(UuidHelper::v7()); + $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 fails a pending order', function (): void { + // GIVEN + $orderId = new OrderId(UuidHelper::v7()); + $order = new Order( + id: $orderId, + shopId: new ShopId(UuidHelper::v7()), + reference: new OrderReference(UuidHelper::v7()), + 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('failPendingOrder') + ->once() + ->with($orderId); + + $confirmAction = new ConfirmPlacedOrder($orderTunnelService); + $failAction = new FailPendingOrder($orderTunnelService); + + // WHEN + $confirmResult = $confirmAction(new ConfirmPlacedOrderInput($orderId)); + $failResult = $failAction(new FailPendingOrderInput($orderId)); + + // THEN + expect($confirmResult)->toBe(ConfirmPlacedOrderOutput::CONFIRMED) + ->and($failResult)->toBe(FailPendingOrderOutput::FAILED); + }); +}); diff --git a/tests/Unit/App/Actions/Pages/UpdatePageInputTest.php b/tests/Unit/App/Cqs/Actions/Pages/UpdatePageInputTest.php similarity index 98% rename from tests/Unit/App/Actions/Pages/UpdatePageInputTest.php rename to tests/Unit/App/Cqs/Actions/Pages/UpdatePageInputTest.php index 27e6e2fa..b220de5f 100644 --- a/tests/Unit/App/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/Actions/PickupExceptions/CreatePickupExceptionInputTest.php b/tests/Unit/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionInputTest.php similarity index 97% rename from tests/Unit/App/Actions/PickupExceptions/CreatePickupExceptionInputTest.php rename to tests/Unit/App/Cqs/Actions/PickupExceptions/CreatePickupExceptionInputTest.php index dba30af5..926c3e35 100644 --- a/tests/Unit/App/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/Actions/PickupExceptions/UpdatePickupExceptionInputTest.php b/tests/Unit/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionInputTest.php similarity index 97% rename from tests/Unit/App/Actions/PickupExceptions/UpdatePickupExceptionInputTest.php rename to tests/Unit/App/Cqs/Actions/PickupExceptions/UpdatePickupExceptionInputTest.php index 372ffc1e..a5910d6e 100644 --- a/tests/Unit/App/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/Actions/ProductIncos/AssociateProductIncoInputTest.php b/tests/Unit/App/Cqs/Actions/ProductIncos/AssociateProductIncoInputTest.php similarity index 56% rename from tests/Unit/App/Actions/ProductIncos/AssociateProductIncoInputTest.php rename to tests/Unit/App/Cqs/Actions/ProductIncos/AssociateProductIncoInputTest.php index 80d09a5c..447273d8 100644 --- a/tests/Unit/App/Actions/ProductIncos/AssociateProductIncoInputTest.php +++ b/tests/Unit/App/Cqs/Actions/ProductIncos/AssociateProductIncoInputTest.php @@ -5,29 +5,30 @@ declare(strict_types=1); namespace Tests\Unit\App\Cqs\Actions\ProductIncos; use App\Cqs\Actions\ProductIncos\AssociateProductIncoInput; -use App\Models\Product; +use Domain\Models\ValueObjects\Entities\ProductId; +use Shared\Helpers\UuidHelper; describe('AssociateProductIncoInput', function (): void { it('creates input successfully with valid parameters', function (): void { // GIVEN - $product = new Product(); - $noArt = 27996; + $productId = new ProductId(UuidHelper::v7()); + $noArt = 27996; // WHEN - $input = new AssociateProductIncoInput($product, $noArt); + $input = new AssociateProductIncoInput($productId, $noArt); // THEN - expect($input->product)->toBe($product) + expect($input->productId)->toBe($productId) ->and($input->no_art)->toBe(27996); }); it('throws when no_art is less than 1', function (): void { // GIVEN - $product = new Product(); - $noArt = 0; + $productId = new ProductId(UuidHelper::v7()); + $noArt = 0; // WHEN & THEN - expect(fn () => new AssociateProductIncoInput($product, $noArt)) + expect(fn () => new AssociateProductIncoInput($productId, $noArt)) ->toThrow(\InvalidArgumentException::class); }); }); diff --git a/tests/Unit/App/Actions/Settings/UpdateSettingsInputTest.php b/tests/Unit/App/Cqs/Actions/Settings/UpdateSettingsInputTest.php similarity index 96% rename from tests/Unit/App/Actions/Settings/UpdateSettingsInputTest.php rename to tests/Unit/App/Cqs/Actions/Settings/UpdateSettingsInputTest.php index 2acc7d88..5123ad9f 100644 --- a/tests/Unit/App/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/Actions/Shops/CreateShopInputTest.php b/tests/Unit/App/Cqs/Actions/Shops/CreateShopInputTest.php similarity index 98% rename from tests/Unit/App/Actions/Shops/CreateShopInputTest.php rename to tests/Unit/App/Cqs/Actions/Shops/CreateShopInputTest.php index 6c670ff9..a7e78459 100644 --- a/tests/Unit/App/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/Actions/Shops/UpdateShopInputTest.php b/tests/Unit/App/Cqs/Actions/Shops/UpdateShopInputTest.php similarity index 98% rename from tests/Unit/App/Actions/Shops/UpdateShopInputTest.php rename to tests/Unit/App/Cqs/Actions/Shops/UpdateShopInputTest.php index 4ed21ca4..942fbdab 100644 --- a/tests/Unit/App/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/Actions/Shops/UpdateShopPickupExceptionsInputTest.php b/tests/Unit/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsInputTest.php similarity index 99% rename from tests/Unit/App/Actions/Shops/UpdateShopPickupExceptionsInputTest.php rename to tests/Unit/App/Cqs/Actions/Shops/UpdateShopPickupExceptionsInputTest.php index 26e57294..dde4840b 100644 --- a/tests/Unit/App/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/Actions/Slides/UpdateSlideInputTest.php b/tests/Unit/App/Cqs/Actions/Slides/UpdateSlideInputTest.php similarity index 90% rename from tests/Unit/App/Actions/Slides/UpdateSlideInputTest.php rename to tests/Unit/App/Cqs/Actions/Slides/UpdateSlideInputTest.php index 43da336a..4cca2abe 100644 --- a/tests/Unit/App/Actions/Slides/UpdateSlideInputTest.php +++ b/tests/Unit/App/Cqs/Actions/Slides/UpdateSlideInputTest.php @@ -2,14 +2,17 @@ declare(strict_types=1); +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/App/Actions/Tags/CreateTagInputTest.php b/tests/Unit/App/Cqs/Actions/Tags/CreateTagInputTest.php similarity index 96% rename from tests/Unit/App/Actions/Tags/CreateTagInputTest.php rename to tests/Unit/App/Cqs/Actions/Tags/CreateTagInputTest.php index 2f375487..fcd838da 100644 --- a/tests/Unit/App/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/Actions/Tags/UpdateTagInputTest.php b/tests/Unit/App/Cqs/Actions/Tags/UpdateTagInputTest.php similarity index 97% rename from tests/Unit/App/Actions/Tags/UpdateTagInputTest.php rename to tests/Unit/App/Cqs/Actions/Tags/UpdateTagInputTest.php index 3993ce1b..11f4606a 100644 --- a/tests/Unit/App/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/Queries/Orders/GetBasketSummaryQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php similarity index 75% rename from tests/Unit/App/Queries/Orders/GetBasketSummaryQueryTest.php rename to tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php index 10848093..23e88b06 100644 --- a/tests/Unit/App/Queries/Orders/GetBasketSummaryQueryTest.php +++ b/tests/Unit/App/Cqs/Queries/Orders/GetBasketSummaryQueryTest.php @@ -2,19 +2,20 @@ 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; 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() @@ -27,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/Queries/Orders/GetOrderConfirmationQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php similarity index 84% rename from tests/Unit/App/Queries/Orders/GetOrderConfirmationQueryTest.php rename to tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php index 4f22509e..f013ac16 100644 --- a/tests/Unit/App/Queries/Orders/GetOrderConfirmationQueryTest.php +++ b/tests/Unit/App/Cqs/Queries/Orders/GetOrderConfirmationQueryTest.php @@ -2,10 +2,10 @@ 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; -use App\Dto\ShopDto; use Domain\Builders\OrderBuilderCompleted; use Domain\Enums\OrderTunnelStep; use Domain\Models\Entities\Basket; @@ -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); @@ -52,18 +52,16 @@ 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'); }); 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/Queries/Orders/GetPickTimeSlotQueryTest.php b/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php similarity index 80% rename from tests/Unit/App/Queries/Orders/GetPickTimeSlotQueryTest.php rename to tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php index 1b6b2c55..013797b4 100644 --- a/tests/Unit/App/Queries/Orders/GetPickTimeSlotQueryTest.php +++ b/tests/Unit/App/Cqs/Queries/Orders/GetPickTimeSlotQueryTest.php @@ -2,33 +2,35 @@ 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; 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; 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', 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); @@ -53,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 new file mode 100644 index 00000000..6bd85dd1 --- /dev/null +++ b/tests/Unit/App/Cqs/Queries/ProductIncos/GetArcadiaIncoPreviewQueryTest.php @@ -0,0 +1,94 @@ +Poulet

', + energyKcal: 149.0, + energyKj: 623.0 + ); + + $service->shouldReceive('getPreview') + ->once() + ->with(27996) + ->andReturn($previewDto); + + $query = new GetArcadiaIncoPreviewQuery($service); + $input = new GetArcadiaIncoPreviewQueryInput(noArt: 27996); + + // WHEN + $result = $query($input); + + // THEN + expect($result->status)->toBe(ArcadiaIncoPreviewStatus::FOUND) + ->and($result->preview)->toBe($previewDto) + ->and($result->errorMessage)->toBeNull(); + }); + + it('returns NOT_FOUND output when preview does not exist on Arcadia', function (): void { + // GIVEN + $service = \Mockery::mock(ArcadiaIncoService::class); + $service->shouldReceive('getPreview') + ->once() + ->with(99999) + ->andReturnNull(); + + $query = new GetArcadiaIncoPreviewQuery($service); + $input = new GetArcadiaIncoPreviewQueryInput(noArt: 99999); + + // WHEN + $result = $query($input); + + // THEN + expect($result->status)->toBe(ArcadiaIncoPreviewStatus::NOT_FOUND) + ->and($result->preview)->toBeNull(); + }); + + it('returns API_ERROR output when Arcadia service throws RuntimeException', function (): void { + // GIVEN + $service = \Mockery::mock(ArcadiaIncoService::class); + $service->shouldReceive('getPreview') + ->once() + ->with(50000) + ->andThrow(new \RuntimeException('Connection timeout')); + + $query = new GetArcadiaIncoPreviewQuery($service); + $input = new GetArcadiaIncoPreviewQueryInput(noArt: 50000); + + // WHEN + $result = $query($input); + + // THEN + expect($result->status)->toBe(ArcadiaIncoPreviewStatus::API_ERROR) + ->and($result->errorMessage)->toBe('Connection timeout') + ->and($result->preview)->toBeNull(); + }); + + it('throws when noArt is less than 1', function (): void { + // GIVEN + $invalidNoArt = 0; + + // WHEN & THEN + expect(fn () => new GetArcadiaIncoPreviewQueryInput(noArt: $invalidNoArt)) + ->toThrow(\InvalidArgumentException::class); + }); +}); 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 0ca9fce3..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 () { @@ -19,37 +21,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, - 'stock' => 0, - 'sell_unit' => null, - 'range' => null, - 'order' => 0, - 'status' => false, - 'star' => false, - '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..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; @@ -27,24 +29,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..6121d494 100644 --- a/tests/Unit/App/Dto/SettingDtoTest.php +++ b/tests/Unit/App/Dto/SettingDtoTest.php @@ -2,8 +2,9 @@ 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 { @@ -15,11 +16,8 @@ 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') ->and($dto->getShopperSiteCodes()[1]->value)->toBe('LY') ->and($dto->getRouteKey())->toBe(1) diff --git a/tests/Unit/App/Dto/ShopDtoTest.php b/tests/Unit/App/Dto/ShopDtoTest.php index a35702d0..fe52d65c 100644 --- a/tests/Unit/App/Dto/ShopDtoTest.php +++ b/tests/Unit/App/Dto/ShopDtoTest.php @@ -2,48 +2,17 @@ declare(strict_types=1); +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 () { - 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(); + $uuid = UuidHelper::v7(); $shopId = new ShopId($uuid); $domainShop = new Shop( id: $shopId, 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, - ]); - }); -}); diff --git a/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php b/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php new file mode 100644 index 00000000..972f8c2b --- /dev/null +++ b/tests/Unit/App/Listeners/Orders/EmptyBasketOnOrderPlacedTest.php @@ -0,0 +1,99 @@ +allows('find')->andReturn($basket); + + $sessionService = \Mockery::mock(SessionService::class); + $sessionService->shouldReceive('get')->once()->andReturn(new SessionId($sessionUuid)); + + /** @var DomainEventDispatcher&\Mockery\MockInterface $eventDispatcher */ + $eventDispatcher = \Mockery::spy(DomainEventDispatcher::class); + + $basketService = new BasketService( + $basketRepository, + \Mockery::mock(ProductRepository::class), + $sessionService, + $eventDispatcher, + ); + + $listener = new EmptyBasketOnOrderPlaced($basketService); + $event = new AnOrderHasBeenPlaced( + orderId: new OrderId(UuidHelper::v7()), + reference: new OrderReference(UuidHelper::v7()), + totalTtc: Money::EUR(1000), + byMatricule: new Matricule('1234567'), + employee: new OrderEmployee( + matricule: new Matricule('1234567'), + firstname: 'Jean', + lastname: 'Dupont', + facility: new ShopperEstablishmentCode('ETAB01'), + site: new ShopperSiteCode('SITEA'), + service: new ShopperServiceCode('101'), + ), + shop: new OrderPlacedShop( + name: 'Shop', + address: '1 rue Test', + postcode: '75001', + city: 'Paris', + ), + pickupDay: new \DateTimeImmutable('+2 days'), + lines: [ + new OrderPlacedLine( + productName: 'Poulet', + productIncoId: new IncoId(123), + productWeightIsVariable: false, + productPriceKgTtc: Money::EUR(1055), + productOrderUnit: OrderUnit::PCE, + quantity: 1, + totalTtc: Money::EUR(1055), + ), + ], + ); + + // WHEN + $listener->handle($event); + + // THEN + $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 new file mode 100644 index 00000000..b23e81ec --- /dev/null +++ b/tests/Unit/App/Listeners/Orders/InvalidateOrderBuilderOnBasketChangeTest.php @@ -0,0 +1,42 @@ +handle($event); + + // THEN + $manager->shouldHaveReceived('clear')->once(); + }); + + it('clears the order builder session manager when basket is removed', function (): void { + // GIVEN + /** @var OrderBuilderSessionManager&\Mockery\MockInterface $manager */ + $manager = \Mockery::spy(OrderBuilderSessionManager::class); + $listener = new InvalidateOrderBuilderOnBasketChange($manager); + $event = new BasketRemoved(new BasketId(UuidHelper::v7())); + + // WHEN + $listener->handle($event); + + // THEN + $manager->shouldHaveReceived('clear')->once(); + }); +}); 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 f12f0630..8f273f23 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; @@ -129,4 +131,38 @@ describe('OrderPolicy', function () { // THEN 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(); + $user->role = UserRole::Admin; + $order = new Order(); + $order->setRawAttributes(['pickup_day' => '2020-01-01'], true); + $order->status = OrderStatus::VALIDATED; + $policy = new OrderPolicy(); + + // WHEN + $result = $policy->cancel($user, $order); + + // THEN + expect($result)->toBeTrue(); + }); }); 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..16757ddf 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; @@ -13,22 +15,21 @@ 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; +use Shared\Helpers\UuidHelper; 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()), + new ProductId(UuidHelper::v7()), Money::EUR(100), TaxRate::TVA_20, null, @@ -234,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 () { @@ -280,44 +249,12 @@ 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 () { // 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); @@ -334,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); @@ -353,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/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 1987ecf8..d0e0ebe4 100644 --- a/tests/Unit/App/Policies/Frontend/BasketPolicyTest.php +++ b/tests/Unit/App/Policies/Frontend/BasketPolicyTest.php @@ -2,59 +2,44 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Frontend; + +use App\Dto\BasketProductDto; use App\Models\Customer; use App\Models\User; use App\Policies\Frontend\BasketPolicy; -use Domain\Enums\SellUnit; use Domain\Enums\TaxRate; -use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; -use Domain\Models\Entities\Product; use Domain\Models\ValueObjects\BasketProduct; use Domain\Models\ValueObjects\DiscountRate; use Domain\Models\ValueObjects\Entities\ProductId; -use Domain\Ports\Repositories\ProductRepository; use Money\Money; -use Ramsey\Uuid\Uuid; +use Shared\Helpers\UuidHelper; covers(BasketPolicy::class); -function createDummyBasketProduct(): BasketProduct +function createDummyBasketProductDto(bool $isPublished = true): BasketProductDto { - return new BasketProduct( - new ProductId(Uuid::uuid7()), - 'Dummy', - 1, - Money::EUR(1000), - Money::EUR(0), - TaxRate::TVA_20, - 1000, - null, - null, - OrderUnit::PCE, - 'dummy', - null, - null, - false, - DiscountRate::zero(), - Money::EUR(1000) - ); -} - -function createTestDomainProduct(bool $status = true): Product -{ - return new Product( - new ProductId(Uuid::uuid7()), - Money::EUR(1000), - TaxRate::TVA_20, - null, - InvoicingUnit::PCE, - SellUnit::PCE, - null, - $status, - null, - null, - true + return new BasketProductDto( + product: new BasketProduct( + new ProductId(UuidHelper::v7()), + 'Dummy', + 1, + Money::EUR(1000), + Money::EUR(0), + TaxRate::TVA_20, + 1000, + null, + null, + OrderUnit::PCE, + 'dummy', + null, + null, + false, + DiscountRate::zero(), + Money::EUR(1000) + ), + isPublished: $isPublished, ); } @@ -62,9 +47,8 @@ describe('BasketPolicy', function () { describe('viewTotal', function () { it('returns true when user is a Customer instance', function () { // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new BasketPolicy($productRepository); - $customer = \Mockery::mock(Customer::class); + $policy = new BasketPolicy(); + $customer = \Mockery::mock(Customer::class); // WHEN $result = $policy->viewTotal($customer); @@ -75,9 +59,8 @@ describe('BasketPolicy', function () { it('returns true when user is a User instance', function () { // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new BasketPolicy($productRepository); - $user = \Mockery::mock(User::class); + $policy = new BasketPolicy(); + $user = \Mockery::mock(User::class); // WHEN $result = $policy->viewTotal($user); @@ -88,8 +71,7 @@ describe('BasketPolicy', function () { it('returns false when user is null', function () { // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new BasketPolicy($productRepository); + $policy = new BasketPolicy(); // WHEN $result = $policy->viewTotal(null); @@ -102,73 +84,50 @@ describe('BasketPolicy', function () { describe('viewPrices', function () { it('returns false when user is null', function () { // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new BasketPolicy($productRepository); - $product = createDummyBasketProduct(); + $policy = new BasketPolicy(); + $item = createDummyBasketProductDto(); // WHEN - $result = $policy->viewPrices(null, $product); + $result = $policy->viewPrices(null, $item); // THEN expect($result)->toBeFalse(); }); - it('returns true when user is not null and product is published', function () { + it('returns true when user is a Customer and item is published', function () { // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new BasketPolicy($productRepository); - $customer = \Mockery::mock(Customer::class); - $product = createDummyBasketProduct(); - - $domainProduct = createTestDomainProduct(status: true); - - $productRepository->shouldReceive('find') - ->once() - ->with($product->id) - ->andReturn($domainProduct); + $policy = new BasketPolicy(); + $customer = \Mockery::mock(Customer::class); + $item = createDummyBasketProductDto(isPublished: true); // WHEN - $result = $policy->viewPrices($customer, $product); + $result = $policy->viewPrices($customer, $item); // THEN expect($result)->toBeTrue(); }); - it('returns false when user is not null and product is not published', function () { + it('returns true when user is a User and item is published', function () { // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new BasketPolicy($productRepository); - $user = \Mockery::mock(User::class); - $product = createDummyBasketProduct(); - - $domainProduct = createTestDomainProduct(status: false); - - $productRepository->shouldReceive('find') - ->once() - ->with($product->id) - ->andReturn($domainProduct); + $policy = new BasketPolicy(); + $user = \Mockery::mock(User::class); + $item = createDummyBasketProductDto(isPublished: true); // WHEN - $result = $policy->viewPrices($user, $product); + $result = $policy->viewPrices($user, $item); // THEN - expect($result)->toBeFalse(); + expect($result)->toBeTrue(); }); - it('returns false when user is not null and product is not found', function () { + it('returns false when user is not null and item is not published', function () { // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new BasketPolicy($productRepository); - $user = \Mockery::mock(User::class); - $product = createDummyBasketProduct(); - - $productRepository->shouldReceive('find') - ->once() - ->with($product->id) - ->andReturn(null); + $policy = new BasketPolicy(); + $user = \Mockery::mock(User::class); + $item = createDummyBasketProductDto(isPublished: false); // WHEN - $result = $policy->viewPrices($user, $product); + $result = $policy->viewPrices($user, $item); // THEN expect($result)->toBeFalse(); 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 9f7ace55..f9a74743 100644 --- a/tests/Unit/App/Policies/Frontend/OrderPolicyTest.php +++ b/tests/Unit/App/Policies/Frontend/OrderPolicyTest.php @@ -2,11 +2,14 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Frontend; + use App\Models\Customer; use App\Models\Order; use App\Models\User; use App\Policies\Frontend\OrderPolicy; -use App\Services\OrderService; +use App\Services\OrderOwnershipService; +use Domain\Enums\OrderStatus; covers(OrderPolicy::class); @@ -14,7 +17,7 @@ describe('OrderPolicy', function () { describe('viewAnyOwn', function () { it('returns false when user is a User instance', function () { // GIVEN - $orderService = \Mockery::mock(OrderService::class); + $orderService = \Mockery::mock(OrderOwnershipService::class); $policy = new OrderPolicy($orderService); $user = \Mockery::mock(User::class); @@ -27,7 +30,7 @@ describe('OrderPolicy', function () { it('returns true when user is a Customer instance', function () { // GIVEN - $orderService = \Mockery::mock(OrderService::class); + $orderService = \Mockery::mock(OrderOwnershipService::class); $policy = new OrderPolicy($orderService); $customer = \Mockery::mock(Customer::class); @@ -40,7 +43,7 @@ describe('OrderPolicy', function () { it('returns true when user is null', function () { // GIVEN - $orderService = \Mockery::mock(OrderService::class); + $orderService = \Mockery::mock(OrderOwnershipService::class); $policy = new OrderPolicy($orderService); // WHEN @@ -54,7 +57,7 @@ describe('OrderPolicy', function () { describe('viewOwn', function () { it('returns false when user is null', function () { // GIVEN - $orderService = \Mockery::mock(OrderService::class); + $orderService = \Mockery::mock(OrderOwnershipService::class); $policy = new OrderPolicy($orderService); $order = \Mockery::mock(Order::class); @@ -67,7 +70,7 @@ describe('OrderPolicy', function () { it('returns false when user is a User instance', function () { // GIVEN - $orderService = \Mockery::mock(OrderService::class); + $orderService = \Mockery::mock(OrderOwnershipService::class); $policy = new OrderPolicy($orderService); $user = \Mockery::mock(User::class); $order = \Mockery::mock(Order::class); @@ -81,10 +84,11 @@ describe('OrderPolicy', function () { it('returns true when user is a Customer and owns the order', function () { // GIVEN - $orderService = \Mockery::mock(OrderService::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() @@ -100,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(OrderService::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() @@ -116,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], + ]); }); }); diff --git a/tests/Unit/App/Policies/Frontend/ProductPolicyTest.php b/tests/Unit/App/Policies/Frontend/ProductPolicyTest.php index 91596a4c..aaf20c3a 100644 --- a/tests/Unit/App/Policies/Frontend/ProductPolicyTest.php +++ b/tests/Unit/App/Policies/Frontend/ProductPolicyTest.php @@ -2,247 +2,137 @@ declare(strict_types=1); +namespace Tests\Unit\App\Policies\Frontend; + +use App\Dto\ProductDto; +use App\Dto\ProductPricingDto; +use App\Dto\ProductWithPricingDto; +use App\Dto\RangeDto; use App\Models\Customer; -use App\Models\Product as EloquentProduct; use App\Models\User; use App\Policies\Frontend\ProductPolicy; -use Carbon\CarbonImmutable; -use Domain\Enums\SellUnit; -use Domain\Enums\TaxRate; -use Domain\Enums\Units\InvoicingUnit; -use Domain\Models\Entities\Product as DomainProduct; -use Domain\Models\ValueObjects\Entities\ProductId; -use Domain\Models\ValueObjects\ProductWeight; -use Domain\Ports\Repositories\ProductRepository; +use Domain\Models\ValueObjects\DiscountRate; use Money\Money; -use Ramsey\Uuid\Uuid; covers(ProductPolicy::class); -function createDummyDomainProduct( - bool $status = true, - ?CarbonImmutable $orderableStart = null, - ?CarbonImmutable $orderableEnd = null, - bool $hasInco = true -): DomainProduct { - $productId = new ProductId(Uuid::uuid7()); +function policyTestProduct(bool $status, bool $isOrderable): ProductWithPricingDto +{ + $zero = Money::EUR(0); - return new DomainProduct( - $productId, - Money::EUR(1000), - TaxRate::TVA_20, - new ProductWeight(1000, false), - InvoicingUnit::KGM, - SellUnit::KGM, - null, - $status, - $orderableStart ?? CarbonImmutable::now()->subDay(), - $orderableEnd ?? CarbonImmutable::now()->addDay(), - $hasInco + return new ProductWithPricingDto( + product: new ProductDto( + id: '018f6c40-1234-7123-8123-123456789012', + name: 'Poulet', + slug: 'poulet', + 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, + stock: 0, + sell_unit: null, + range: new RangeDto(1, 'Gamme', 'gamme', null, null, 'alt', 'title', 1, true), + status: $status, + is_orderable: $isOrderable, + ), + pricing: new ProductPricingDto($zero, $zero, $zero, $zero, $zero, $zero, DiscountRate::zero(), false), ); } -describe('ProductPolicy', function () { - describe('viewPublished', function () { - it('returns false when domain product is not found', function () { +describe('Frontend ProductPolicy', function (): void { + describe('addToBasket', function (): void { + it('allows an orderable product', function (): void { // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new ProductPolicy($productRepository); - - $productId = new ProductId(Uuid::uuid7()); - $eloquentProduct = \Mockery::mock(EloquentProduct::class); - $eloquentProduct->shouldReceive('getId')->once()->andReturn($productId); - - $productRepository->shouldReceive('find')->once()->with($productId)->andReturn(null); + $policy = new ProductPolicy(); + $product = policyTestProduct(status: true, isOrderable: true); // WHEN - $result = $policy->viewPublished(null, $eloquentProduct); + $result = $policy->addToBasket(new Customer(), $product); + + // THEN + expect($result)->toBeTrue(); + }); + + it('rejects a product that is not orderable', function (): void { + // GIVEN + $policy = new ProductPolicy(); + $product = policyTestProduct(status: true, isOrderable: false); + + // WHEN + $result = $policy->addToBasket(new Customer(), $product); + + // THEN + expect($result)->toBeFalse(); + }); + }); + + describe('viewPrices', function (): void { + it('rejects guests', function (): void { + // GIVEN + $policy = new ProductPolicy(); + $product = policyTestProduct(status: true, isOrderable: true); + + // WHEN + $result = $policy->viewPrices(null, $product); // THEN expect($result)->toBeFalse(); }); - it('returns false when domain product is found but not published', function () { + it('rejects an authenticated user when the product is not published', function (): void { // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new ProductPolicy($productRepository); - - $productId = new ProductId(Uuid::uuid7()); - $eloquentProduct = \Mockery::mock(EloquentProduct::class); - $eloquentProduct->shouldReceive('getId')->once()->andReturn($productId); - - $domainProduct = createDummyDomainProduct(status: false); - - $productRepository->shouldReceive('find')->once()->with($productId)->andReturn($domainProduct); + $policy = new ProductPolicy(); + $product = policyTestProduct(status: false, isOrderable: false); // WHEN - $result = $policy->viewPublished(null, $eloquentProduct); + $result = $policy->viewPrices(new User(), $product); // THEN expect($result)->toBeFalse(); }); - it('returns true when domain product is found and published', function () { + it('allows a customer on a published product', function (): void { // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new ProductPolicy($productRepository); - - $productId = new ProductId(Uuid::uuid7()); - $eloquentProduct = \Mockery::mock(EloquentProduct::class); - $eloquentProduct->shouldReceive('getId')->once()->andReturn($productId); - - $domainProduct = createDummyDomainProduct(status: true); - - $productRepository->shouldReceive('find')->once()->with($productId)->andReturn($domainProduct); + $policy = new ProductPolicy(); + $product = policyTestProduct(status: true, isOrderable: false); // WHEN - $result = $policy->viewPublished(null, $eloquentProduct); + $result = $policy->viewPrices(new Customer(), $product); // THEN expect($result)->toBeTrue(); }); }); - describe('addToBasket', function () { - it('returns false when domain product is not found', function () { + describe('viewPublished', function (): void { + it('allows viewing a published product', function (): void { // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new ProductPolicy($productRepository); - - $productId = new ProductId(Uuid::uuid7()); - $eloquentProduct = \Mockery::mock(EloquentProduct::class); - $eloquentProduct->shouldReceive('getId')->once()->andReturn($productId); - - $productRepository->shouldReceive('find')->once()->with($productId)->andReturn(null); + $policy = new ProductPolicy(); + $product = policyTestProduct(status: true, isOrderable: false); // WHEN - $result = $policy->addToBasket(null, $eloquentProduct); - - // THEN - expect($result)->toBeFalse(); - }); - - it('returns false when domain product is found but not orderable', function () { - // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new ProductPolicy($productRepository); - - $productId = new ProductId(Uuid::uuid7()); - $eloquentProduct = \Mockery::mock(EloquentProduct::class); - $eloquentProduct->shouldReceive('getId')->once()->andReturn($productId); - - $domainProduct = createDummyDomainProduct( - orderableStart: CarbonImmutable::now()->addDays(2), - orderableEnd: CarbonImmutable::now()->addDays(5) - ); - - $productRepository->shouldReceive('find')->once()->with($productId)->andReturn($domainProduct); - - // WHEN - $result = $policy->addToBasket(null, $eloquentProduct); - - // THEN - expect($result)->toBeFalse(); - }); - - it('returns true when domain product is found and orderable', function () { - // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new ProductPolicy($productRepository); - - $productId = new ProductId(Uuid::uuid7()); - $eloquentProduct = \Mockery::mock(EloquentProduct::class); - $eloquentProduct->shouldReceive('getId')->once()->andReturn($productId); - - $domainProduct = createDummyDomainProduct( - orderableStart: CarbonImmutable::now()->subDay(), - orderableEnd: CarbonImmutable::now()->addDay() - ); - - $productRepository->shouldReceive('find')->once()->with($productId)->andReturn($domainProduct); - - // WHEN - $result = $policy->addToBasket(null, $eloquentProduct); + $result = $policy->viewPublished(null, $product); // THEN expect($result)->toBeTrue(); }); - }); - describe('viewPrices', function () { - it('returns false when user is null', function () { + it('rejects viewing an unpublished product', function (): void { // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new ProductPolicy($productRepository); - - $eloquentProduct = \Mockery::mock(EloquentProduct::class); + $policy = new ProductPolicy(); + $product = policyTestProduct(status: false, isOrderable: true); // WHEN - $result = $policy->viewPrices(null, $eloquentProduct); + $result = $policy->viewPublished(new Customer(), $product); // THEN expect($result)->toBeFalse(); }); - - it('returns false when user is a Customer and domain product is not found', function () { - // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new ProductPolicy($productRepository); - - $customer = \Mockery::mock(Customer::class); - $productId = new ProductId(Uuid::uuid7()); - $eloquentProduct = \Mockery::mock(EloquentProduct::class); - $eloquentProduct->shouldReceive('getId')->once()->andReturn($productId); - - $productRepository->shouldReceive('find')->once()->with($productId)->andReturn(null); - - // WHEN - $result = $policy->viewPrices($customer, $eloquentProduct); - - // THEN - expect($result)->toBeFalse(); - }); - - it('returns false when user is a User and domain product is found but not published', function () { - // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new ProductPolicy($productRepository); - - $user = \Mockery::mock(User::class); - $productId = new ProductId(Uuid::uuid7()); - $eloquentProduct = \Mockery::mock(EloquentProduct::class); - $eloquentProduct->shouldReceive('getId')->once()->andReturn($productId); - - $domainProduct = createDummyDomainProduct(status: false); - - $productRepository->shouldReceive('find')->once()->with($productId)->andReturn($domainProduct); - - // WHEN - $result = $policy->viewPrices($user, $eloquentProduct); - - // THEN - expect($result)->toBeFalse(); - }); - - it('returns true when user is a Customer and domain product is found and published', function () { - // GIVEN - $productRepository = \Mockery::mock(ProductRepository::class); - $policy = new ProductPolicy($productRepository); - - $customer = \Mockery::mock(Customer::class); - $productId = new ProductId(Uuid::uuid7()); - $eloquentProduct = \Mockery::mock(EloquentProduct::class); - $eloquentProduct->shouldReceive('getId')->once()->andReturn($productId); - - $domainProduct = createDummyDomainProduct(status: true); - - $productRepository->shouldReceive('find')->once()->with($productId)->andReturn($domainProduct); - - // WHEN - $result = $policy->viewPrices($customer, $eloquentProduct); - - // THEN - expect($result)->toBeTrue(); - }); }); }); diff --git a/tests/Unit/App/Policies/Frontend/ShopPolicyTest.php b/tests/Unit/App/Policies/Frontend/ShopPolicyTest.php index e31ac60c..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; @@ -37,7 +39,7 @@ describe('ShopPolicy', function () { expect($result)->toBeTrue(); }); - it('viewPickupTimeslots returns true when user is null', function () { + it('viewPickupTimeslots returns false when user is null', function () { // GIVEN $policy = new ShopPolicy(); $shop = \Mockery::mock(Shop::class); @@ -46,7 +48,7 @@ describe('ShopPolicy', function () { $result = $policy->viewPickupTimeslots(null, $shop); // THEN - expect($result)->toBeTrue(); + expect($result)->toBeFalse(); }); }); }); diff --git a/tests/Unit/App/Queries/ProductIncos/GetArcadiaIncoPreviewQueryTest.php b/tests/Unit/App/Queries/ProductIncos/GetArcadiaIncoPreviewQueryTest.php deleted file mode 100644 index f008c8cd..00000000 --- a/tests/Unit/App/Queries/ProductIncos/GetArcadiaIncoPreviewQueryTest.php +++ /dev/null @@ -1,52 +0,0 @@ -Poulet

', - energyKcal: 149.0, - energyKj: 623.0 - ); - - $service->shouldReceive('getPreview') - ->once() - ->with(27996) - ->andReturn($previewDto); - - $query = new GetArcadiaIncoPreviewQuery($service); - $input = new GetArcadiaIncoPreviewQueryInput(noArt: 27996); - - // WHEN - $result = $query($input); - - // THEN - expect($result)->toBe($previewDto); - }); - - it('throws when noArt is less than 1', function (): void { - // GIVEN - $invalidNoArt = 0; - - // WHEN & THEN - expect(fn () => new GetArcadiaIncoPreviewQueryInput(noArt: $invalidNoArt)) - ->toThrow(\InvalidArgumentException::class); - }); -}); 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/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'); }); }); 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 07502b08..a1948e5b 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 { @@ -16,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 c7f95c54..a31c5368 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; @@ -40,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 064e92d3..c738df67 100644 --- a/tests/Unit/App/Services/IcsGeneratorServiceTest.php +++ b/tests/Unit/App/Services/IcsGeneratorServiceTest.php @@ -2,12 +2,20 @@ declare(strict_types=1); +namespace Tests\Unit\App\Services; + use App\Dto\IcsContentDto; use App\Services\IcsGeneratorService; -use Illuminate\Support\Carbon; +use Carbon\Carbon; +use Carbon\CarbonImmutable; 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 @@ -38,7 +46,7 @@ describe('IcsGeneratorService', function (): void { $ics = $service->generate($dto); // THEN - expect($ics) + expect($ics->value) ->toContain('BEGIN:VCALENDAR') ->toContain('PRODID:-//MyApp//NONSGML v1.0//EN') ->toContain('UID:uid-123') @@ -47,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 { @@ -68,6 +74,34 @@ describe('IcsGeneratorService', function (): void { $ics = $service->generate($dto); // THEN - expect($ics)->toContain('URL:http://example.com'); + expect($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->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/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 02ce2903..c0e7a9d8 100644 --- a/tests/Unit/Domain/Builders/OrderBuilderTest.php +++ b/tests/Unit/Domain/Builders/OrderBuilderTest.php @@ -2,43 +2,45 @@ declare(strict_types=1); +namespace Tests\Unit\Domain\Builders; + +use Domain\Builders\BasketOrderBuilder; +use Domain\Builders\CompletedOrderBuilder; use Domain\Builders\OrderBuilder; use Domain\Builders\OrderBuilderCompleted; -use Domain\Builders\OrderBuilderType; use Domain\Builders\OrderBuilderWithBasket; use Domain\Models\Entities\Basket; 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 with the correct state', 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); // THEN expect($builder) + ->toBeInstanceOf(BasketOrderBuilder::class) ->toBeInstanceOf(OrderBuilderWithBasket::class) - ->and($builder->getBuilderType())->toBe(OrderBuilderType::FROM_BASKET) - ->and($builder->isFromBasket())->toBeTrue() - ->and($builder->isCompleted())->toBeFalse() + ->not->toBeInstanceOf(OrderBuilderCompleted::class) ->and($builder->getBasket())->toBe($basket) ->and($builder->getShopperId())->toBe($customerId); }); - it('transitions to with_pickup state when adding a timeslot', 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); @@ -48,11 +50,38 @@ describe('OrderBuilder', function (): void { // THEN expect($completedBuilder) + ->toBeInstanceOf(CompletedOrderBuilder::class) ->toBeInstanceOf(OrderBuilderCompleted::class) - ->and($completedBuilder->getBuilderType())->toBe(OrderBuilderType::WITH_PICKUP) - ->and($completedBuilder->isFromBasket())->toBeTrue() - ->and($completedBuilder->isCompleted())->toBeTrue() + ->toBeInstanceOf(OrderBuilderWithBasket::class) + ->not->toBe($builder) + ->and($builder)->not->toBeInstanceOf(OrderBuilderCompleted::class) + ->and($completedBuilder->getBasket())->toBe($basket) + ->and($completedBuilder->getShopperId())->toBe($customerId) ->and($completedBuilder->getShopId())->toBe($shopId) ->and($completedBuilder->getPickupTimeSlot())->toBe($timeSlot); }); + + it('returns a new immutable CompletedOrderBuilder when updating the timeslot', function (): void { + // GIVEN + $basketId = new BasketId(UuidHelper::v7()); + $basket = new Basket($basketId); + $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); + + // WHEN + $secondStep = $firstStep->withPickupTimeSlot($secondShop, $secondSlot); + + // THEN + expect($secondStep) + ->toBeInstanceOf(CompletedOrderBuilder::class) + ->not->toBe($firstStep) + ->and($firstStep->getShopId())->toBe($firstShop) + ->and($firstStep->getPickupTimeSlot())->toBe($firstSlot) + ->and($secondStep->getShopId())->toBe($secondShop) + ->and($secondStep->getPickupTimeSlot())->toBe($secondSlot); + }); }); 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/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/Enums/OrderStatusTest.php b/tests/Unit/Domain/Enums/OrderStatusTest.php new file mode 100644 index 00000000..5f2a9561 --- /dev/null +++ b/tests/Unit/Domain/Enums/OrderStatusTest.php @@ -0,0 +1,90 @@ +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('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::WAITING, + OrderStatus::PENDING, + OrderStatus::VALIDATED, + OrderStatus::FAILED, + OrderStatus::CANCELED, + ]) + ->and($resolvedLegacy)->toBe([null, null, null, null, null]) + ->and($resolvedUppercase)->toBeNull(); + }); +}); diff --git a/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php b/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php index fa95f53e..3a4bd084 100644 --- a/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php +++ b/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php @@ -18,17 +18,24 @@ 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($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 = [ @@ -45,12 +52,19 @@ 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($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/Events/BasketHasBeenModifiedTest.php b/tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php new file mode 100644 index 00000000..81bd38ee --- /dev/null +++ b/tests/Unit/Domain/Events/BasketHasBeenModifiedTest.php @@ -0,0 +1,22 @@ +basketId)->toBe($basketId); + }); +}); diff --git a/tests/Unit/Domain/Events/BasketRemovedTest.php b/tests/Unit/Domain/Events/BasketRemovedTest.php new file mode 100644 index 00000000..1d783442 --- /dev/null +++ b/tests/Unit/Domain/Events/BasketRemovedTest.php @@ -0,0 +1,22 @@ +basketId)->toBe($basketId); + }); +}); diff --git a/tests/Unit/Domain/Events/DtoTest.php b/tests/Unit/Domain/Events/DtoTest.php index 92f2d762..e3962677 100644 --- a/tests/Unit/Domain/Events/DtoTest.php +++ b/tests/Unit/Domain/Events/DtoTest.php @@ -9,7 +9,6 @@ use Domain\Enums\TaxRate; use Domain\Enums\Units\OrderUnit; use Domain\Events\Dto\OrderPlacedLine; use Domain\Events\Dto\OrderPlacedShop; -use Domain\Events\Dto\RegateOrderCsvGenerated; use Domain\Events\Dto\SalariesHaveBeenSynced; use Domain\Models\ValueObjects\DeliveryAddress; use Domain\Models\ValueObjects\Entities\ProductId; @@ -20,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 () { @@ -55,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, @@ -178,21 +177,6 @@ describe('OrderPlacedShop', function () { }); }); -describe('RegateOrderCsvGenerated', function () { - it('creates RegateOrderCsvGenerated correctly', function () { - // GIVEN - $csvContent = 'csv'; - $fileName = 'file.csv'; - - // WHEN - $dto = new RegateOrderCsvGenerated($csvContent, $fileName); - - // THEN - expect($dto->csvContent)->toBe('csv') - ->and($dto->fileName)->toBe('file.csv'); - }); -}); - describe('SalariesHaveBeenSynced', function () { it('creates SalariesHaveBeenSynced correctly', function () { // GIVEN @@ -207,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/Exceptions/ExceptionsTest.php b/tests/Unit/Domain/Exceptions/ExceptionsTest.php deleted file mode 100644 index 473e549e..00000000 --- a/tests/Unit/Domain/Exceptions/ExceptionsTest.php +++ /dev/null @@ -1,86 +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); - }); -}); diff --git a/tests/Unit/Domain/Models/Entities/BasketTest.php b/tests/Unit/Domain/Models/Entities/BasketTest.php index 2535812b..d99a5daf 100644 --- a/tests/Unit/Domain/Models/Entities/BasketTest.php +++ b/tests/Unit/Domain/Models/Entities/BasketTest.php @@ -14,38 +14,43 @@ 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 { + /** + * @param array{ + * id?: ProductId, + * qty?: int, + * } $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' => '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(UuidHelper::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'], + ); } 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); @@ -65,7 +70,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), @@ -82,10 +87,10 @@ 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($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); @@ -95,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 @@ -113,10 +118,10 @@ 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($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); @@ -128,16 +133,16 @@ 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 Basket($basketId, ['not-an-item']); + $action = fn () => (new \ReflectionClass(Basket::class))->newInstance($basketId, ['not-an-item']); // THEN expect($action)->toThrow(\DomainException::class); }); it('returns id', function (): void { // GIVEN - $basketId = new BasketId(Uuid::uuid7()); + $basketId = new BasketId(UuidHelper::v7()); $basket = new Basket($basketId); // WHEN $id = $basket->id(); @@ -147,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); @@ -163,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); @@ -179,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); @@ -191,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); @@ -203,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); @@ -219,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); @@ -231,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 c258cc93..690a1f04 100644 --- a/tests/Unit/Domain/Models/Entities/OrderTest.php +++ b/tests/Unit/Domain/Models/Entities/OrderTest.php @@ -4,12 +4,12 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\Entities; +use Carbon\Carbon; use Carbon\CarbonImmutable; 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; @@ -35,13 +35,27 @@ 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; +/** + * @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( 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, @@ -65,13 +79,26 @@ 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( - 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'), @@ -97,6 +124,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 { @@ -107,8 +145,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); }); @@ -126,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'); @@ -206,18 +254,18 @@ describe('Order - id', function (): void { // WHEN $id = $order->id(); // THEN - expect($id)->toBeInstanceOf(OrderId::class); + expect(strlen($id->value->toString()))->toBe(36); }); }); 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), @@ -228,7 +276,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), @@ -236,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', @@ -257,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', @@ -279,6 +327,98 @@ 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 PENDING status via pendingFromBasket and validates it to VALIDATED', function (): void { + // GIVEN + $basket = new Basket(new BasketId(UuidHelper::v7()), [ + new BasketProduct( + id: new ProductId(UuidHelper::v7()), + 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(UuidHelper::v7()), + 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(UuidHelper::v7()), + name: 'Cocotte Lyon', + address: '12 rue de la Paix', + postcode: '69001', + city: 'Lyon', + phone: '0478123456' + ); + + // WHEN + $order = Order::pendingFromBasket( + new OrderId(UuidHelper::v7()), + new OrderReference(UuidHelper::v7()), + $basket, + new PickupTimeSlot(new \DateTimeImmutable('+1 day 10:00'), new \DateInterval('PT10M')), + $shopper, + $shop + ); + + // THEN + 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($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); + }); }); describe('Order - Domain Events', function (): void { @@ -291,8 +431,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/PickupExceptionOnDateTest.php b/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php index 24331f24..a0de477f 100644 --- a/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php +++ b/tests/Unit/Domain/Models/Entities/PickupExceptionOnDateTest.php @@ -4,16 +4,28 @@ 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; +use Shared\Helpers\UuidHelper; + +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 - $id = new PickupExceptionId(Uuid::uuid7()); + $id = new PickupExceptionId(UuidHelper::v7()); $date = CarbonImmutable::now(); $label = 'Férié'; $repeatable = true; @@ -42,11 +54,11 @@ 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()), + new PickupExceptionId(UuidHelper::v7()), $fridayDate, 'Friday holiday', false, @@ -55,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 135ee112..3660b975 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; @@ -11,10 +12,9 @@ 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; +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, @@ -43,10 +43,21 @@ 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 - $id = new ProductId(Uuid::uuid7()); + $id = new ProductId(UuidHelper::v7()); $price = Money::EUR(1000); $taxRate = TaxRate::TVA_5_5; $weight = new ProductWeight(500, false); @@ -211,6 +222,40 @@ describe('Product', function (): void { expect($result)->toBeFalse(); }); + it('returns true when date equals orderable_start', function (): void { + // GIVEN + $now = CarbonImmutable::parse('2026-11-15 10:00:00'); + $product = makeProduct( + status: true, + orderableStart: $now, + orderableEnd: $now->addDay(), + hasInco: true + ); + + // WHEN + $result = $product->canBeOrderOn($now); + + // THEN + expect($result)->toBeTrue(); + }); + + it('returns false when date equals orderable_end', function (): void { + // GIVEN + $now = CarbonImmutable::parse('2026-11-15 10:00:00'); + $product = makeProduct( + status: true, + orderableStart: $now->subDay(), + orderableEnd: $now, + hasInco: true + ); + + // WHEN + $result = $product->canBeOrderOn($now); + + // THEN + expect($result)->toBeFalse(); + }); + it('returns false when product has no inco', function (): void { // GIVEN $now = CarbonImmutable::now(); @@ -296,8 +341,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/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 50dc9f29..f598d3d7 100644 --- a/tests/Unit/Domain/Models/Entities/ShopperTest.php +++ b/tests/Unit/Domain/Models/Entities/ShopperTest.php @@ -12,12 +12,20 @@ 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 { + 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(Uuid::uuid7()); + $id = new ShopperId(UuidHelper::v7()); $email = new Email('test@example.com'); $matricule = new Matricule('1234567'); $startDate = CarbonImmutable::now()->subDay(); @@ -56,16 +64,16 @@ describe('Shopper', function (): void { it('is inactive when endDate is in the past', function (): void { // GIVEN - $endDate = CarbonImmutable::now()->subDay(); + $endDate = CarbonImmutable::now('Europe/Paris')->subDay(); // WHEN $entity = new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@example.com'), new Matricule('1234567'), 'Nom', 'Prenom', - CarbonImmutable::now()->subDays(2), + CarbonImmutable::now('Europe/Paris')->subDays(2), $endDate, new ShopperEstablishmentCode('ETAB01'), new ShopperSiteCode('SITE'), @@ -78,16 +86,16 @@ describe('Shopper', function (): void { it('is active when endDate is in the future', function (): void { // GIVEN - $endDate = CarbonImmutable::now()->addDay(); + $endDate = CarbonImmutable::now('Europe/Paris')->addDay(); // WHEN $entity = new Shopper( - new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@example.com'), new Matricule('1234567'), 'Nom', 'Prenom', - CarbonImmutable::now()->subDays(2), + CarbonImmutable::now('Europe/Paris')->subDays(2), $endDate, new ShopperEstablishmentCode('ETAB01'), new ShopperSiteCode('SITE'), @@ -98,10 +106,159 @@ describe('Shopper', function (): void { expect($entity->isActive())->toBeTrue(); }); + it('is inactive when startDate is in the future', function (): void { + // GIVEN + $startDate = CarbonImmutable::now('Europe/Paris')->addDay(); + + // WHEN + $entity = new Shopper( + new ShopperId(UuidHelper::v7()), + new Email('test@example.com'), + new Matricule('1234567'), + 'Nom', + 'Prenom', + $startDate, + null, + new ShopperEstablishmentCode('ETAB01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101') + ); + + // THEN + expect($entity->isActive())->toBeFalse(); + }); + + it('is inactive when startDate is in the future even with future endDate', function (): void { + // GIVEN + $startDate = CarbonImmutable::now('Europe/Paris')->addDay(); + $endDate = CarbonImmutable::now('Europe/Paris')->addDays(10); + + // WHEN + $entity = new Shopper( + new ShopperId(UuidHelper::v7()), + new Email('test@example.com'), + new Matricule('1234567'), + 'Nom', + 'Prenom', + $startDate, + $endDate, + new ShopperEstablishmentCode('ETAB01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101') + ); + + // THEN + expect($entity->isActive())->toBeFalse(); + }); + + it('is active when startDate equals now and endDate is null', function (): void { + // GIVEN + $now = CarbonImmutable::parse('2026-11-15 00:00:00', 'Europe/Paris'); + CarbonImmutable::setTestNow($now); + + try { + // WHEN + $entity = new Shopper( + new ShopperId(UuidHelper::v7()), + new Email('test@example.com'), + new Matricule('1234567'), + 'Nom', + 'Prenom', + CarbonImmutable::parse('2026-11-15', 'UTC'), + null, + new ShopperEstablishmentCode('ETAB01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101') + ); + + // THEN + expect($entity->isActive())->toBeTrue(); + } finally { + CarbonImmutable::setTestNow(); + } + }); + + it('is inactive at the start of endDate', function (): void { + // GIVEN + $now = CarbonImmutable::parse('2026-11-15 00:00:00', 'Europe/Paris'); + CarbonImmutable::setTestNow($now); + + try { + // WHEN + $entity = new Shopper( + new ShopperId(UuidHelper::v7()), + new Email('test@example.com'), + new Matricule('1234567'), + 'Nom', + 'Prenom', + CarbonImmutable::parse('2026-11-01', 'UTC'), + CarbonImmutable::parse('2026-11-15', 'UTC'), + new ShopperEstablishmentCode('ETAB01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101') + ); + + // THEN + expect($entity->isActive())->toBeFalse(); + } finally { + CarbonImmutable::setTestNow(); + } + }); + + it('activates shopper at Europe/Paris midnight even when UTC date is still previous day', function (): void { + // GIVEN: 2026-05-07 22:30:00 UTC === 2026-05-08 00:30:00 Europe/Paris + CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-05-07 22:30:00', 'UTC')); + + try { + $entity = new Shopper( + new ShopperId(UuidHelper::v7()), + new Email('test@example.com'), + new Matricule('1234567'), + 'Nom', + 'Prenom', + CarbonImmutable::parse('2026-05-08', 'UTC'), + null, + new ShopperEstablishmentCode('ETAB01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101') + ); + + // WHEN & THEN + expect($entity->isActive())->toBeTrue(); + } finally { + CarbonImmutable::setTestNow(); + } + }); + + it('deactivates shopper at Europe/Paris midnight on endDate even when UTC date is still previous day', function (): void { + // GIVEN: 2026-05-07 22:30:00 UTC === 2026-05-08 00:30:00 Europe/Paris + CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-05-07 22:30:00', 'UTC')); + + try { + $entity = new Shopper( + new ShopperId(UuidHelper::v7()), + new Email('test@example.com'), + new Matricule('1234567'), + 'Nom', + 'Prenom', + CarbonImmutable::parse('2026-05-01', 'UTC'), + CarbonImmutable::parse('2026-05-08', 'UTC'), + new ShopperEstablishmentCode('ETAB01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101') + ); + + // WHEN & THEN + expect($entity->isActive())->toBeFalse(); + } finally { + CarbonImmutable::setTestNow(); + } + }); + 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'), '', @@ -120,7 +277,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/AttachedFileTest.php b/tests/Unit/Domain/Models/ValueObjects/AttachedFileTest.php index f9864afc..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 () { @@ -33,7 +32,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..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 () { @@ -21,35 +21,45 @@ describe('BasketProduct', function () { return new Money($amount, new Currency('EUR')); } + /** + * @param array{ + * name?: string, + * qty?: int, + * unitPriceHt?: Money, + * unitDiscount?: Money, + * taxRate?: TaxRate, + * weightGrams?: int, + * slug?: string, + * 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: new ProductId(UuidHelper::v7()), + 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), + ); } // --- Tests d'instanciation et de validation (Invariants) --- it('can instantiate', function () { // GIVEN - $id = new ProductId(Uuid::uuid7()); + $id = new ProductId(UuidHelper::v7()); $name = 'Product Name'; $qty = 2; $unitPriceHt = getMoney(100); @@ -87,7 +97,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 66efa15c..b047edab 100644 --- a/tests/Unit/Domain/Models/ValueObjects/ContactFormDataTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/ContactFormDataTest.php @@ -5,22 +5,33 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Models\ValueObjects; use Domain\Models\ValueObjects\ContactFormData; +use Domain\Models\ValueObjects\OrderReference; +use Shared\Helpers\UuidHelper; 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 () { @@ -30,7 +41,7 @@ describe('ContactFormData', function () { $email = 'john@example.com'; $subject = 'Inquiry'; $message = 'This is a message.'; - $orderRef = 'REF-123'; + $orderRef = new OrderReference(UuidHelper::v7()); $file = null; // WHEN @@ -45,7 +56,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 () { @@ -118,17 +132,3 @@ describe('ContactFormData', function () { expect($action)->toThrow(\DomainException::class); }); }); - -it('throws exception if orderRef is provided but empty', function () { - // GIVEN - $orderRef = ' '; - - // WHEN - $action = fn () => getNewContactFormData([ - 'orderRef' => $orderRef, - - ]); - - // THEN - expect($action)->toThrow(\DomainException::class); -}); 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/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); - }); -}); diff --git a/tests/Unit/Domain/Models/ValueObjects/EditablePickupExceptionForShopTest.php b/tests/Unit/Domain/Models/ValueObjects/EditablePickupExceptionForShopTest.php index d0c649d9..b80cc4c4 100644 --- a/tests/Unit/Domain/Models/ValueObjects/EditablePickupExceptionForShopTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/EditablePickupExceptionForShopTest.php @@ -4,18 +4,30 @@ 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; 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'); + 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 $exception = new PickupExceptionOnDate( - new PickupExceptionId(Uuid::uuid7()), + new PickupExceptionId(UuidHelper::v7()), CarbonImmutable::now(), 'Label', true, 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/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/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/IcsContentTest.php b/tests/Unit/Domain/Models/ValueObjects/IcsContentTest.php new file mode 100644 index 00000000..5a3cb955 --- /dev/null +++ b/tests/Unit/Domain/Models/ValueObjects/IcsContentTest.php @@ -0,0 +1,39 @@ +value)->toBe($raw) + ->and((string) $ics)->toBe($raw); + }); + + it('rejects empty ICS content', function (): void { + // WHEN / THEN + expect(fn (): IcsContent => new IcsContent(' ')) + ->toThrow(\InvalidArgumentException::class); + }); + + it('rejects ICS content missing BEGIN:VCALENDAR header', function (): void { + // WHEN / THEN + expect(fn (): IcsContent => new IcsContent("BEGIN:VEVENT\r\nEND:VCALENDAR")) + ->toThrow(\InvalidArgumentException::class); + }); + + it('rejects ICS content missing END:VCALENDAR footer', function (): void { + // WHEN / THEN + expect(fn (): IcsContent => new IcsContent("BEGIN:VCALENDAR\r\nBEGIN:VEVENT")) + ->toThrow(\InvalidArgumentException::class); + }); +}); 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..76a3c663 100644 --- a/tests/Unit/Domain/Models/ValueObjects/NutritionalValuesTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/NutritionalValuesTest.php @@ -8,6 +8,20 @@ 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); @@ -22,7 +36,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 +92,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/OrderLineProductTest.php b/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php index 97800f57..a414ee18 100644 --- a/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/OrderLineProductTest.php @@ -12,13 +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( @@ -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,13 +48,24 @@ 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 { // 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(UuidHelper::v7()), + '', + 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'); }); @@ -61,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(UuidHelper::v7()), + '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'); }); @@ -69,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(UuidHelper::v7()), + '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'); }); @@ -77,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(UuidHelper::v7()), + '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'); }); @@ -85,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(UuidHelper::v7()), + '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'); }); @@ -93,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(UuidHelper::v7()), + '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'); }); diff --git a/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php b/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php index cb601c10..e18c659b 100644 --- a/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/OrderLineTest.php @@ -13,26 +13,24 @@ 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(array $overrides = []): OrderLineProduct + function getNewOrderLineProduct(): 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: new IncoId(1), + originalId: new ProductId(UuidHelper::v7()), + 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, + ); } it('can instantiate correctly', function (): void { diff --git a/tests/Unit/Domain/Models/ValueObjects/OrderReferenceTest.php b/tests/Unit/Domain/Models/ValueObjects/OrderReferenceTest.php index 9f98ac5f..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,62 +16,58 @@ describe('OrderReference', function () { it('can instantiate with a valid UUID v7', function () { // GIVEN - $uuidV7 = Uuid::uuid7(); + $uuidV7 = UuidHelper::v7(); // WHEN $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); }); it('can instantiate from a valid base-58 UUID v7 string', function () { // GIVEN - $uuidV7 = Uuid::uuid7(); + $uuidV7 = UuidHelper::v7(); $base58 = UuidHelper::toBase58($uuidV7); // WHEN $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(); }); it('can instantiate from a valid UUID v7 string via fromString', function () { // GIVEN - $uuidV7 = Uuid::uuid7(); + $uuidV7 = UuidHelper::v7(); $uuidString = $uuidV7->toString(); // WHEN $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(); }); it('can instantiate from a valid base-58 string via fromString', function () { // GIVEN - $uuidV7 = Uuid::uuid7(); + $uuidV7 = UuidHelper::v7(); $base58 = UuidHelper::toBase58($uuidV7); // WHEN $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(); }); it('throws exception if provided UUID is not v7', function () { // GIVEN - $uuidV4 = Uuid::uuid4(); + $uuidV4 = UuidHelper::v4(); // WHEN $action = fn () => getNewOrderReference($uuidV4); @@ -94,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/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/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/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/ProductPricingTest.php b/tests/Unit/Domain/Models/ValueObjects/ProductPricingTest.php index 1b593abe..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 () { @@ -40,7 +50,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/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/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 678f9a27..bcbb9894 100644 --- a/tests/Unit/Domain/Models/ValueObjects/ShopPickupOverrideTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/ShopPickupOverrideTest.php @@ -4,18 +4,30 @@ 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; 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'); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); 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, @@ -42,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, @@ -67,15 +79,15 @@ describe('ShopPickupOverride', function (): void { it('correctly handles replacement and deadlines', function (): void { // GIVEN $exception = new PickupExceptionOnDate( - new PickupExceptionId(Uuid::uuid7()), - CarbonImmutable::create(2025, 5, 1), + new PickupExceptionId(UuidHelper::v7()), + 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, @@ -83,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 ); @@ -96,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/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/Policies/CustomerOrderLimitPolicyTest.php b/tests/Unit/Domain/Policies/CustomerOrderLimitPolicyTest.php index 94b6dd8e..515ddf89 100644 --- a/tests/Unit/Domain/Policies/CustomerOrderLimitPolicyTest.php +++ b/tests/Unit/Domain/Policies/CustomerOrderLimitPolicyTest.php @@ -11,33 +11,33 @@ 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); + $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); + $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 () { // GIVEN - $policy = new CustomerOrderLimitPolicy(20000); + $policy = new CustomerOrderLimitPolicy(20000, 20000, new Currency('EUR')); $basketTotal = new Money(20001, new Currency('EUR')); // WHEN @@ -47,35 +47,35 @@ 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); + $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); + $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 () { // GIVEN - $policy = new CustomerOrderLimitPolicy(20000, 30000); + $policy = new CustomerOrderLimitPolicy(20000, 30000, new Currency('EUR')); $basketTotal = new Money(10000, new Currency('EUR')); $weeklyTotal = new Money(20001, new Currency('EUR')); diff --git a/tests/Unit/Domain/Services/BasketServiceTest.php b/tests/Unit/Domain/Services/BasketServiceTest.php index dbaa524a..79859e5a 100644 --- a/tests/Unit/Domain/Services/BasketServiceTest.php +++ b/tests/Unit/Domain/Services/BasketServiceTest.php @@ -7,6 +7,8 @@ namespace Tests\Unit\Domain\Services; use Domain\Enums\ProductBrand; use Domain\Enums\TaxRate; use Domain\Enums\Units\OrderUnit; +use Domain\Events\BasketHasBeenModified; +use Domain\Events\BasketRemoved; use Domain\Models\Entities\Basket; use Domain\Models\ValueObjects\BasketProduct; use Domain\Models\ValueObjects\DiscountRate; @@ -20,44 +22,44 @@ 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 { - $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' => '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(UuidHelper::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 { - - it('adds a new product to the basket and saves it', 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; @@ -66,7 +68,12 @@ describe('BasketService', function (): void { $productRepository = Mockery::mock(ProductRepository::class); $productRepository->shouldReceive('getBasketProduct')->once()->with($productId, $qty)->andReturn($basketProduct); - $service = new BasketService($basketRepository, $productRepository, $sessionService); + $eventDispatcher = Mockery::mock(DomainEventDispatcher::class); + $eventDispatcher->shouldReceive('dispatch') + ->once() + ->with(Mockery::on(fn (BasketHasBeenModified $event): bool => $event->basketId->equals($basket->id))); + + $service = new BasketService($basketRepository, $productRepository, $sessionService, $eventDispatcher); // WHEN $service->add($productId, $qty); @@ -75,15 +82,15 @@ describe('BasketService', function (): void { expect($basket->has($productId))->toBeTrue(); }); - it('removes a quantity from the basket', 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(); @@ -93,7 +100,12 @@ describe('BasketService', function (): void { $productRepository = Mockery::mock(ProductRepository::class); - $service = new BasketService($basketRepository, $productRepository, $sessionService); + $eventDispatcher = Mockery::mock(DomainEventDispatcher::class); + $eventDispatcher->shouldReceive('dispatch') + ->once() + ->with(Mockery::on(fn (BasketHasBeenModified $event): bool => $event->basketId->equals($basket->id))); + + $service = new BasketService($basketRepository, $productRepository, $sessionService, $eventDispatcher); // WHEN $service->remove($productId, 2); @@ -105,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); @@ -119,7 +131,12 @@ describe('BasketService', function (): void { $productRepository = Mockery::mock(ProductRepository::class); - $service = new BasketService($basketRepository, $productRepository, $sessionService); + $eventDispatcher = Mockery::mock(DomainEventDispatcher::class); + $eventDispatcher->shouldReceive('dispatch') + ->once() + ->with(Mockery::on(fn (BasketHasBeenModified $event): bool => $event->basketId->equals($basket->id))); + + $service = new BasketService($basketRepository, $productRepository, $sessionService, $eventDispatcher); // WHEN $service->remove($productId, 3); @@ -128,15 +145,15 @@ describe('BasketService', function (): void { expect($basket->has($productId))->toBeFalse(); }); - it('removes an entire line directly via removeLine', 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); @@ -144,7 +161,12 @@ describe('BasketService', function (): void { $productRepository = Mockery::mock(ProductRepository::class); - $service = new BasketService($basketRepository, $productRepository, $sessionService); + $eventDispatcher = Mockery::mock(DomainEventDispatcher::class); + $eventDispatcher->shouldReceive('dispatch') + ->once() + ->with(Mockery::on(fn (BasketHasBeenModified $event): bool => $event->basketId->equals($basket->id))); + + $service = new BasketService($basketRepository, $productRepository, $sessionService, $eventDispatcher); // WHEN $service->removeLine($productId); @@ -153,36 +175,47 @@ describe('BasketService', function (): void { expect($basket->has($productId))->toBeFalse(); }); - it('empties the basket by destroying it from repository', function (): void { + it('empties the basket by destroying it from repository and dispatches BasketRemoved', function (): void { // GIVEN - $basketRepository = Mockery::mock(BasketRepository::class); - $sessionService = Mockery::mock(SessionService::class); - $sessionService->shouldReceive('get')->andReturn(new SessionId(Uuid::uuid7()))->byDefault(); - $basketRepository->shouldReceive('find')->once()->andReturn(new Basket(new BasketId(Uuid::uuid7()))); - $basketRepository->shouldReceive('delete')->once(); + $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(UuidHelper::v7()))->byDefault(); $productRepository = Mockery::mock(ProductRepository::class); - $service = new BasketService($basketRepository, $productRepository, $sessionService); + /** @var DomainEventDispatcher&\Mockery\MockInterface $eventDispatcher */ + $eventDispatcher = Mockery::spy(DomainEventDispatcher::class); + + $service = new BasketService($basketRepository, $productRepository, $sessionService, $eventDispatcher); // WHEN $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', 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); - $service = new BasketService($basketRepository, $productRepository, $sessionService); + $eventDispatcher = Mockery::mock(DomainEventDispatcher::class); + $eventDispatcher->shouldNotReceive('dispatch'); + + $service = new BasketService($basketRepository, $productRepository, $sessionService, $eventDispatcher); // WHEN $returnedBasket = $service->getBasket(); @@ -193,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(); @@ -201,14 +234,37 @@ describe('BasketService', function (): void { $productRepository = Mockery::mock(ProductRepository::class); - $service = new BasketService($basketRepository, $productRepository, $sessionService); + $eventDispatcher = Mockery::mock(DomainEventDispatcher::class); + $eventDispatcher->shouldNotReceive('dispatch'); + + $service = new BasketService($basketRepository, $productRepository, $sessionService, $eventDispatcher); // WHEN $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); }); + + it('reports whether the basket has items', function (): void { + // GIVEN + $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); + $productRepo = Mockery::mock(ProductRepository::class); + $sessionSvc = Mockery::mock(SessionService::class); + $eventDispatcher = Mockery::mock(DomainEventDispatcher::class); + $eventDispatcher->shouldNotReceive('dispatch'); + + $sessionSvc->shouldReceive('get')->andReturn($sessionId); + $basketRepo->shouldReceive('find')->twice()->andReturn($nonEmpty, $empty); + + $service = new BasketService($basketRepo, $productRepo, $sessionSvc, $eventDispatcher); + + // WHEN / THEN + expect($service->hasItems())->toBeTrue() + ->and($service->hasItems())->toBeFalse(); + }); }); diff --git a/tests/Unit/Domain/Services/OrderServiceTest.php b/tests/Unit/Domain/Services/OrderServiceTest.php index d9e63424..58089baa 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; @@ -37,18 +38,29 @@ 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; + +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 - $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', @@ -74,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, @@ -98,7 +110,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); @@ -112,11 +124,11 @@ 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); - $repository->shouldReceive('find')->with($orderId)->andReturn(null); + $repository->shouldReceive('findForUpdate')->with($orderId)->andReturn(null); $service = new OrderService($repository); @@ -126,16 +138,93 @@ 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(UuidHelper::v7()); + $failedId = new OrderId(UuidHelper::v7()); + + $makeOrderWithStatus = static fn (OrderId $id, OrderStatus $status): Order => new Order( + id: $id, + shopId: new ShopId(UuidHelper::v7()), + reference: new OrderReference(UuidHelper::v7()), + 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(UuidHelper::v7()), + 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 () { 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), @@ -146,7 +235,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), @@ -160,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', @@ -173,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', @@ -190,7 +279,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(); @@ -234,16 +322,18 @@ 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); + assert($product->picture instanceof StorageFilePath); + expect($product->picture->value)->toBe('images/poulet.jpg'); }); 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), @@ -264,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', @@ -276,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 1efbf9db..d4b97612 100644 --- a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php +++ b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php @@ -4,13 +4,22 @@ declare(strict_types=1); namespace Tests\Unit\Domain\Services; +use Carbon\Carbon; use Carbon\CarbonImmutable; -use DateInterval; +use Carbon\WeekDay; use Domain\Builders\OrderBuilder; -use Domain\Enums\OrderTunnelStep; +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; use Domain\Exceptions\OrderTunnel\MissingOrderBuilderException; +use Domain\Exceptions\OrderTunnel\RegateExportFailedException; +use Domain\Exceptions\OrderTunnel\UnorderableProductException; use Domain\Models\Entities\Basket; use Domain\Models\Entities\Order; use Domain\Models\Entities\Shop; @@ -19,18 +28,18 @@ 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\SessionId; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Policies\CustomerOrderLimitPolicy; -use Domain\Ports\Repositories\BasketRepository; use Domain\Ports\Repositories\OrderRepository; use Domain\Ports\Repositories\PickupExceptionRepository; use Domain\Ports\Repositories\ProductRepository; @@ -38,23 +47,23 @@ use Domain\Ports\Repositories\ShopperRepository; use Domain\Ports\Repositories\ShopRepository; use Domain\Ports\Services\EmployeeStatisticsService; use Domain\Ports\Services\OrderBuilderSessionManager; -use Domain\Ports\Services\SessionService; -use Domain\Ports\Services\TransactionManager; -use Domain\Services\BasketService; +use Domain\Ports\Services\RegateService; +use Domain\Ports\Services\TunnelAttemptTrackerService; use Domain\Services\OrderService; use Domain\Services\OrderTunnelService; 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', @@ -76,45 +85,45 @@ 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); } -function createTestBuilder(bool $completed = false): OrderBuilder +/** + * @return ($completed is true ? OrderBuilderCompleted : OrderBuilderWithBasket) + */ +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()); - $timeSlot = new PickupTimeSlot(CarbonImmutable::create(2025, 1, 1), new DateInterval('PT1H')); - $builder = $builder->withPickupTimeSlot($shopId, $timeSlot); + $shopId = new ShopId(UuidHelper::v7()); + $nextFriday = CarbonImmutable::now('Europe/Paris')->next(WeekDay::Friday->value)->addWeek()->startOfDay(); + $timeSlot = new PickupTimeSlot($nextFriday, new \DateInterval('PT1H')); + + return $builder->withPickupTimeSlot($shopId, $timeSlot); } - /** @var OrderBuilder $builder */ return $builder; } function createOrderTunnelService( - ?BasketRepository $basketRepository = null, ?ProductRepository $productRepository = null, ?ShopRepository $shopRepository = null, ?ShopperRepository $shopperRepository = null, ?PickupExceptionRepository $pickupExceptionRepository = null, ?OrderBuilderSessionManager $orderBuilderSessionManager = null, ?OrderRepository $orderRepository = null, - ?TransactionManager $transactionManager = null, ?DomainEventDispatcher $eventDispatcher = null, + ?RegateService $regateService = null, + ?TunnelAttemptTrackerService $tunnelAttemptTracker = null, ): OrderTunnelService { - if ($basketRepository === null) { - $basketRepository = mock(BasketRepository::class); - $basketRepository->shouldReceive('persist')->byDefault(); - } 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', @@ -135,170 +144,129 @@ function createOrderTunnelService( ); })->byDefault(); } - $shopRepository ??= mock(ShopRepository::class); - $shopperRepository ??= mock(ShopperRepository::class); - $pickupExceptionRepository ??= mock(PickupExceptionRepository::class); - $orderBuilderSessionManager ??= mock(OrderBuilderSessionManager::class); - $orderRepository ??= mock(OrderRepository::class); + $shopRepository ??= \Mockery::mock(ShopRepository::class); + $shopperRepository ??= \Mockery::mock(ShopperRepository::class); + if ($pickupExceptionRepository === null) { + $pickupExceptionRepository = \Mockery::mock(PickupExceptionRepository::class); + $pickupExceptionRepository->shouldReceive('getExceptionsForShop')->andReturn([])->byDefault(); + } + $orderBuilderSessionManager ??= \Mockery::mock(OrderBuilderSessionManager::class); + $orderRepository ??= \Mockery::mock(OrderRepository::class); - $transactionManager ??= mock(TransactionManager::class); - $eventDispatcher ??= mock(DomainEventDispatcher::class); - - $sessionService = \Mockery::mock(SessionService::class); - $sessionService->shouldReceive('get')->andReturn(new SessionId(Uuid::uuid7()))->byDefault(); + $eventDispatcher ??= \Mockery::mock(DomainEventDispatcher::class); $employeeStatisticsService = \Mockery::mock(EmployeeStatisticsService::class); $employeeStatisticsService->shouldReceive('getWeeklyTotalForEmployee')->andReturn(Money::EUR(0))->byDefault(); - $basketService = new BasketService($basketRepository, $productRepository, $sessionService); $shopperService = new ShopperService($shopRepository, $shopperRepository); $pickupService = new PickupSchedulingService($pickupExceptionRepository); $orderService = new OrderService($orderRepository); - $orderLimitPolicy = new CustomerOrderLimitPolicy(500000, 500000); + if ($regateService === null) { + $regateService = \Mockery::mock(RegateService::class); + $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( - $basketService, $eventDispatcher, $shopperService, $orderBuilderSessionManager, $pickupService, $orderRepository, + $productRepository, $orderLimitPolicy, - $transactionManager, $shopRepository, $shopperRepository, $orderService, - $employeeStatisticsService + $employeeStatisticsService, + $regateService, + $tunnelAttemptTracker, ); } +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('validates basket is valid when it has items', function (): void { + it('allows access to BOOKING step when builder is from basket and has items', function (): void { // GIVEN - $basketRepo = mock(BasketRepository::class); - $basketRepo->shouldReceive('find')->andReturn(createTestBasket(2)); - - $service = createOrderTunnelService(basketRepository: $basketRepo); - - // WHEN - $isValid = $service->hasValidBasket(); - - // THEN - expect($isValid)->toBeTrue(); - }); - - it('invalidates basket when it is empty', function (): void { - // GIVEN - $basketRepo = mock(BasketRepository::class); - $basketRepo->shouldReceive('find')->andReturn(createTestBasket(0)); - - $service = createOrderTunnelService(basketRepository: $basketRepo); - - // WHEN - $isValid = $service->hasValidBasket(); - - // THEN - expect($isValid)->toBeFalse(); - }); - - it('allows access to REVIEW step when basket is valid', function (): void { - // GIVEN - $basketRepo = mock(BasketRepository::class); - $basketRepo->shouldReceive('find')->andReturn(createTestBasket(1)); - - $orderBuilderRepository = mock(OrderBuilderSessionManager::class); - $orderBuilderRepository->shouldReceive('get')->andReturn(null); - - $service = createOrderTunnelService( - basketRepository: $basketRepo, - orderBuilderSessionManager: $orderBuilderRepository - ); - - // WHEN - $canAccess = $service->canAccessStep(OrderTunnelStep::REVIEW); - - // THEN - expect($canAccess)->toBeTrue(); - }); - - it('denies access to REVIEW step when basket is empty', function (): void { - // GIVEN - $basketRepo = mock(BasketRepository::class); - $basketRepo->shouldReceive('find')->andReturn(createTestBasket(0)); - - $orderBuilderRepository = mock(OrderBuilderSessionManager::class); - $orderBuilderRepository->shouldReceive('get')->andReturn(null); - - $service = createOrderTunnelService( - basketRepository: $basketRepo, - orderBuilderSessionManager: $orderBuilderRepository - ); - - // WHEN - $canAccess = $service->canAccessStep(OrderTunnelStep::REVIEW); - - // THEN - expect($canAccess)->toBeFalse(); - }); - - it('allows access to BOOKING step when builder is from basket and basket is valid', function (): void { - // GIVEN - $basketRepo = mock(BasketRepository::class); - $basketRepo->shouldReceive('find')->andReturn(createTestBasket(1)); - $builder = createTestBuilder(); - $orderBuilderRepository = mock(OrderBuilderSessionManager::class); + $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn($builder); $service = createOrderTunnelService( - basketRepository: $basketRepo, orderBuilderSessionManager: $orderBuilderRepository ); // WHEN - $canAccess = $service->canAccessStep(OrderTunnelStep::BOOKING); + $canAccess = $service->canAccessBooking(); // THEN expect($canAccess)->toBeTrue(); }); + it('denies access to BOOKING step when builder has an empty basket', function (): void { + // GIVEN + $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(UuidHelper::v7())); + $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); + $orderBuilderRepository->shouldReceive('get')->andReturn($builder); + + $service = createOrderTunnelService( + orderBuilderSessionManager: $orderBuilderRepository + ); + + // WHEN + $canAccess = $service->canAccessBooking(); + + // THEN + expect($canAccess)->toBeFalse(); + }); + it('denies access to BOOKING step when builder is missing', function (): void { // GIVEN - $basketRepo = mock(BasketRepository::class); - $basketRepo->shouldReceive('find')->andReturn(createTestBasket(1)); - - $orderBuilderRepository = mock(OrderBuilderSessionManager::class); + $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn(null); $service = createOrderTunnelService( - basketRepository: $basketRepo, orderBuilderSessionManager: $orderBuilderRepository ); // WHEN - $canAccess = $service->canAccessStep(OrderTunnelStep::BOOKING); + $canAccess = $service->canAccessBooking(); // THEN expect($canAccess)->toBeFalse(); }); - it('allows access to CONFIRMATION step when builder is completed and basket is valid', function (): void { + it('allows access to CONFIRMATION step when builder is completed and has items', function (): void { // GIVEN - $basketRepo = mock(BasketRepository::class); - $basketRepo->shouldReceive('find')->andReturn(createTestBasket(1)); - $builder = createTestBuilder(completed: true); - $orderBuilderRepository = mock(OrderBuilderSessionManager::class); + $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn($builder); $service = createOrderTunnelService( - basketRepository: $basketRepo, orderBuilderSessionManager: $orderBuilderRepository ); // WHEN - $canAccess = $service->canAccessStep(OrderTunnelStep::CONFIRMATION); + $canAccess = $service->canAccessConfirmation(); // THEN expect($canAccess)->toBeTrue(); @@ -306,20 +274,37 @@ describe('OrderTunnelService', function (): void { it('denies access to CONFIRMATION step when builder is not completed', function (): void { // GIVEN - $basketRepo = mock(BasketRepository::class); - $basketRepo->shouldReceive('find')->andReturn(createTestBasket(1)); - $builder = createTestBuilder(completed: false); - $orderBuilderRepository = mock(OrderBuilderSessionManager::class); + $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn($builder); $service = createOrderTunnelService( - basketRepository: $basketRepo, orderBuilderSessionManager: $orderBuilderRepository ); // WHEN - $canAccess = $service->canAccessStep(OrderTunnelStep::CONFIRMATION); + $canAccess = $service->canAccessConfirmation(); + + // THEN + expect($canAccess)->toBeFalse(); + }); + + it('denies access to CONFIRMATION step when builder has an empty basket', function (): void { + // GIVEN + $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(UuidHelper::v7())) + ->withPickupTimeSlot($shopId, $timeSlot); + $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); + $orderBuilderRepository->shouldReceive('get')->andReturn($builder); + + $service = createOrderTunnelService( + orderBuilderSessionManager: $orderBuilderRepository + ); + + // WHEN + $canAccess = $service->canAccessConfirmation(); // THEN expect($canAccess)->toBeFalse(); @@ -327,19 +312,15 @@ describe('OrderTunnelService', function (): void { it('denies access to CONFIRMATION step when builder is missing', function (): void { // GIVEN - $basketRepo = mock(BasketRepository::class); - $basketRepo->shouldReceive('find')->andReturn(createTestBasket(1)); - - $orderBuilderRepository = mock(OrderBuilderSessionManager::class); + $orderBuilderRepository = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepository->shouldReceive('get')->andReturn(null); $service = createOrderTunnelService( - basketRepository: $basketRepo, orderBuilderSessionManager: $orderBuilderRepository ); // WHEN - $canAccess = $service->canAccessStep(OrderTunnelStep::CONFIRMATION); + $canAccess = $service->canAccessConfirmation(); // THEN expect($canAccess)->toBeFalse(); @@ -347,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'), @@ -361,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', @@ -370,10 +351,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); @@ -393,8 +374,8 @@ 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); + $shopperId = new ShopperId(UuidHelper::v7()); + $shopperRepo = \Mockery::mock(ShopperRepository::class); $shopperRepo->shouldReceive('find')->with($shopperId)->andReturn(null); $service = createOrderTunnelService(shopperRepository: $shopperRepo); @@ -407,10 +388,10 @@ 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 = mock(PickupExceptionRepository::class); + $pickupExceptionRepo = \Mockery::mock(PickupExceptionRepository::class); $pickupExceptionRepo->shouldReceive('getExceptionsForShop')->andReturn([]); $service = createOrderTunnelService(pickupExceptionRepository: $pickupExceptionRepo); @@ -419,16 +400,16 @@ describe('OrderTunnelService', function (): void { $slots = $service->getAvailableTimeSlots($shop); // THEN - expect($slots)->toBeArray(); + expect($slots)->not->toBeEmpty(); }); it('initializes order from basket', function (): void { // GIVEN $basket = createTestBasket(1); - $customerId = new ShopperId(Uuid::uuid7()); + $customerId = new ShopperId(UuidHelper::v7()); - $orderBuilderRepo = mock(OrderBuilderSessionManager::class); - $orderBuilderRepo->shouldReceive('save')->once(); + /** @var OrderBuilderSessionManager&\Mockery\MockInterface $orderBuilderRepo */ + $orderBuilderRepo = \Mockery::spy(OrderBuilderSessionManager::class); $service = createOrderTunnelService(orderBuilderSessionManager: $orderBuilderRepo); @@ -436,13 +417,13 @@ 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 { // GIVEN $builder = createTestBuilder(); - $orderBuilderRepo = mock(OrderBuilderSessionManager::class); + $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepo->shouldReceive('get')->once()->andReturn($builder); $service = createOrderTunnelService(orderBuilderSessionManager: $orderBuilderRepo); @@ -456,7 +437,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); @@ -467,10 +448,25 @@ describe('OrderTunnelService', function (): void { expect($action)->toThrow(MissingOrderBuilderException::class); }); + it('throws exception in getBuilderFromBasketOrFail when builder has an empty basket', function (): void { + // GIVEN + $builder = OrderBuilder::fromBasket(createTestBasket(0), new ShopperId(UuidHelper::v7())); + $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); + $orderBuilderRepo->shouldReceive('get')->once()->andReturn($builder); + + $service = createOrderTunnelService(orderBuilderSessionManager: $orderBuilderRepo); + + // WHEN + $action = fn () => $service->getBuilderFromBasketOrFail(); + + // THEN + expect($action)->toThrow(MissingOrderBuilderException::class); + }); + 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); @@ -485,7 +481,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); @@ -496,16 +492,35 @@ describe('OrderTunnelService', function (): void { expect($action)->toThrow(MissingOrderBuilderException::class); }); + it('throws exception in getBuilderCompletedOrFail when builder has an empty basket', function (): void { + // GIVEN + $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(UuidHelper::v7()))->withPickupTimeSlot($shopId, $timeSlot); + + $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); + $orderBuilderRepo->shouldReceive('get')->once()->andReturn($builder); + + $service = createOrderTunnelService(orderBuilderSessionManager: $orderBuilderRepo); + + // WHEN + $action = fn () => $service->getBuilderCompletedOrFail(); + + // THEN + expect($action)->toThrow(MissingOrderBuilderException::class); + }); + it('applies time slot', 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($selectedDate, new DateInterval('PT1H')); - $ts2 = new PickupTimeSlot(CarbonImmutable::create(2025, 1, 2), new DateInterval('PT1H')); + $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')); $availableSlots = [$ts1, $ts2]; - $orderBuilderRepo = mock(OrderBuilderSessionManager::class); + $orderBuilderRepo = \Mockery::mock(OrderBuilderSessionManager::class); $orderBuilderRepo->shouldReceive('save')->once(); $service = createOrderTunnelService(orderBuilderSessionManager: $orderBuilderRepo); @@ -520,9 +535,9 @@ 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'); - $selectedDate = CarbonImmutable::create(2025, 1, 1); - $ts1 = new PickupTimeSlot(CarbonImmutable::create(2025, 1, 2), new DateInterval('PT1H')); + $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]; $service = createOrderTunnelService(); @@ -536,11 +551,6 @@ describe('OrderTunnelService', function (): void { it('finalizes order', function (): void { // GIVEN - $basketRepo = mock(BasketRepository::class); - $basketRepo->shouldReceive('find')->once()->andReturn(createTestBasket(1)); - $basketRepo->shouldReceive('persist')->once(); - $basketRepo->shouldReceive('delete')->once(); - $builder = createTestBuilder(completed: true); $shopperId = $builder->getShopperId(); $shopper = new Shopper( @@ -555,36 +565,29 @@ 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(); - $transactionManager = mock(TransactionManager::class); - $transactionManager->shouldReceive('execute')->once()->andReturnUsing(function ($callback) { - return $callback(); - }); - - $eventDispatcher = mock(DomainEventDispatcher::class); + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); $eventDispatcher->shouldReceive('dispatch')->once(); - $builderRepo = mock(OrderBuilderSessionManager::class); - $builderRepo->shouldReceive('clear')->once(); + $builderRepo = \Mockery::mock(OrderBuilderSessionManager::class); + $builderRepo->shouldNotReceive('clear'); $service = createOrderTunnelService( - basketRepository: $basketRepo, shopRepository: $shopRepo, shopperRepository: $shopperRepo, orderBuilderSessionManager: $builderRepo, orderRepository: $orderRepo, - transactionManager: $transactionManager, eventDispatcher: $eventDispatcher ); @@ -592,7 +595,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'); }); @@ -613,25 +615,19 @@ 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)); - $transactionManager = mock(TransactionManager::class); - $transactionManager->shouldReceive('execute')->once()->andReturnUsing(function ($callback) { - return $callback(); - }); - $service = createOrderTunnelService( shopRepository: $shopRepo, shopperRepository: $shopperRepo, orderRepository: $orderRepo, - transactionManager: $transactionManager ); // WHEN @@ -656,42 +652,32 @@ 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(); - $transactionManager = mock(TransactionManager::class); - $transactionManager->shouldReceive('execute')->once()->andReturnUsing(function ($callback) { - return $callback(); - }); - - $eventDispatcher = mock(DomainEventDispatcher::class); + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); $eventDispatcher->shouldReceive('dispatch')->once(); - $builderRepo = mock(OrderBuilderSessionManager::class); - $builderRepo->shouldReceive('clear')->once(); + $builderRepo = \Mockery::mock(OrderBuilderSessionManager::class); + $builderRepo->shouldNotReceive('clear'); - $basketRepo = mock(BasketRepository::class); - $basketRepo->shouldReceive('find')->once()->andReturn(createTestBasket(1)); - $basketRepo->shouldReceive('persist')->once(); - $basketRepo->shouldReceive('delete')->once(); - - $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', 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, @@ -702,18 +688,16 @@ describe('OrderTunnelService', function (): void { description: null, weightVariable: false, discountRate: DiscountRate::fromRatio(0.0), - priceKgTtc: Money::EUR(240) + priceKgTtc: Money::EUR(120) ); }); $service = createOrderTunnelService( - basketRepository: $basketRepo, productRepository: $productRepo, shopRepository: $shopRepo, shopperRepository: $shopperRepo, orderBuilderSessionManager: $builderRepo, orderRepository: $orderRepo, - transactionManager: $transactionManager, eventDispatcher: $eventDispatcher ); @@ -721,6 +705,424 @@ 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 { + // GIVEN + $builder = createTestBuilder(completed: true); + $shopperRepo = \Mockery::mock(ShopperRepository::class); + $shopperRepo->shouldNotReceive('getByIdOrFail'); + + $orderRepo = \Mockery::mock(OrderRepository::class); + $orderRepo->shouldNotReceive('persist'); + + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); + $eventDispatcher->shouldNotReceive('dispatch'); + + $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', + 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); + $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); + + $shopper = new Shopper( + id: $shopperId, + email: new Email('test@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')->with(\Mockery::type(ShopperId::class))->andReturn($shopper); + + $shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris'); + $shopRepo = \Mockery::mock(ShopRepository::class); + $shopRepo->shouldReceive('find')->andReturn($shop); + + $orderRepo = \Mockery::mock(OrderRepository::class); + $orderRepo->shouldNotReceive('persist'); + + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); + $eventDispatcher->shouldNotReceive('dispatch'); + + $builderRepo = \Mockery::mock(OrderBuilderSessionManager::class); + $builderRepo->shouldNotReceive('clear'); + + $service = createOrderTunnelService( + shopRepository: $shopRepo, + shopperRepository: $shopperRepo, + orderBuilderSessionManager: $builderRepo, + orderRepository: $orderRepo, + eventDispatcher: $eventDispatcher + ); + + // WHEN + $action = fn () => $service->finalizeOrder($builder); + + // THEN + expect($action)->toThrow(ExpiredPickupTimeSlotException::class); + }); + + it('throws UnorderableProductException when finalizing order with an unorderable product in basket', function (): void { + // GIVEN + $builder = createTestBuilder(completed: true); + + $productRepo = \Mockery::mock(ProductRepository::class); + $productRepo->shouldReceive('getBasketProduct') + ->once() + ->andThrow(new UnorderableProductException()); + + $orderRepo = \Mockery::mock(OrderRepository::class); + $orderRepo->shouldNotReceive('persist'); + + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); + $eventDispatcher->shouldNotReceive('dispatch'); + + $builderRepo = \Mockery::mock(OrderBuilderSessionManager::class); + $builderRepo->shouldNotReceive('clear'); + + $service = createOrderTunnelService( + productRepository: $productRepo, + orderBuilderSessionManager: $builderRepo, + orderRepository: $orderRepo, + eventDispatcher: $eventDispatcher + ); + + // WHEN + $action = fn () => $service->finalizeOrder($builder); + + // THEN + expect($action)->toThrow(UnorderableProductException::class); + }); + + it('propagates RegateExportFailedException without dispatching AnOrderHasBeenPlaced', function (): void { + // GIVEN + $builder = createTestBuilder(completed: true); + $shopperId = $builder->getShopperId(); + $shopper = new Shopper( + id: $shopperId, + email: new Email('test@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')->with(\Mockery::type(ShopperId::class))->andReturn($shopper); + + $shopId = clone $builder->getShopId(); + $shop = new Shop($shopId, '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'); + + $builderRepo = \Mockery::mock(OrderBuilderSessionManager::class); + $builderRepo->shouldNotReceive('clear'); + + $regateService = \Mockery::mock(RegateService::class); + $regateService->shouldReceive('processOrder')->once()->andThrow(new RegateExportFailedException('SMTP failed')); + + $service = createOrderTunnelService( + shopRepository: $shopRepo, + shopperRepository: $shopperRepo, + orderBuilderSessionManager: $builderRepo, + orderRepository: $orderRepo, + eventDispatcher: $eventDispatcher, + regateService: $regateService, + ); + + // WHEN + $action = fn () => $service->finalizeOrder($builder); + + // THEN + expect($action)->toThrow(RegateExportFailedException::class, 'SMTP failed'); + }); + + it('throws InactiveShopperException when shopper is inactive during finalizeOrder', function (): void { + // GIVEN + $builder = createTestBuilder(completed: true); + $shopperId = $builder->getShopperId(); + $inactiveShopper = new Shopper( + id: $shopperId, + email: new Email('inactive@test.com'), + matricule: new Matricule('1234567'), + nom: 'Doe', + prenom: 'Jane', + startDate: CarbonImmutable::now()->subMonth(), + endDate: CarbonImmutable::now()->subDay(), + etablissement: new ShopperEstablishmentCode('ETAB01'), + site: new ShopperSiteCode('SITEA'), + service: new ShopperServiceCode('101') + ); + $shopperRepo = \Mockery::mock(ShopperRepository::class); + $shopperRepo->shouldReceive('getByIdOrFail')->with(\Mockery::type(ShopperId::class))->andReturn($inactiveShopper); + + $orderRepo = \Mockery::mock(OrderRepository::class); + $orderRepo->shouldNotReceive('persist'); + + $eventDispatcher = \Mockery::mock(DomainEventDispatcher::class); + $eventDispatcher->shouldNotReceive('dispatch'); + + $service = createOrderTunnelService( + shopperRepository: $shopperRepo, + orderRepository: $orderRepo, + eventDispatcher: $eventDispatcher, + ); + + // WHEN + $action = fn () => $service->finalizeOrder($builder); + + // 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->status)->toBe(OrderStatus::PENDING); + }); + + it('exports, confirms and fails a pending order across split steps', function (): void { + // GIVEN + $shopId = new ShopId(UuidHelper::v7()); + $shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris'); + $shopper = new Shopper( + id: new ShopperId(UuidHelper::v7()), + 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); + $orderToOk = Order::pendingFromBasket( + 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(UuidHelper::v7()), + new OrderReference(UuidHelper::v7()), + $basket, + new PickupTimeSlot(CarbonImmutable::now()->next('Friday'), new \DateInterval('PT1H')), + $shopper, + $shop + ); + + $orderRepo = \Mockery::mock(OrderRepository::class); + $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') + ->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($orderToOk->id()); + $confirmed = $service->confirmPlacedOrder($orderToOk->id()); + $service->failPendingOrder($orderToKo->id()); + + // THEN + 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(UuidHelper::v7()); + $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(UuidHelper::v7()); + $shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris'); + $shopper = new Shopper( + id: new ShopperId(UuidHelper::v7()), + 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(UuidHelper::v7()), + new OrderReference(UuidHelper::v7()), + $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); }); }); diff --git a/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php b/tests/Unit/Domain/Services/PickupSchedulingServiceTest.php index 83d014f2..db191a6b 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; @@ -10,17 +12,16 @@ use Domain\Models\Entities\Shop; use Domain\Models\ValueObjects\Entities\PickupExceptionId; use Domain\Models\ValueObjects\Entities\ShopId; use Domain\Models\ValueObjects\PickupTimeSlot; +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; +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', @@ -45,14 +46,19 @@ dataset('example_3_deadlines', [ ]); dataset('next_pickup_scenarios', [ - 'Monday 10:00' => ['2026-05-11 10:00:00', '2026-05-15 14:00:00'], - 'Friday 10:00 (Before cutoff hour)' => ['2026-05-15 10:00:00', '2026-05-15 14:00:00'], - 'Friday 15:00 (After cutoff hour)' => ['2026-05-15 15:00:00', '2026-05-22 14:00:00'], + 'Monday 10:00 (Before cutoff)' => ['2026-05-11 10:00:00', '2026-05-15 14:00:00'], + 'Monday 14:00 (At cutoff edge)' => ['2026-05-11 14:00:00', '2026-05-15 14:00:00'], + 'Monday 14:01 (After cutoff)' => ['2026-05-11 14:01:00', '2026-05-22 14:00:00'], + 'Tuesday 10:00 (After cutoff)' => ['2026-05-12 10:00:00', '2026-05-22 14:00:00'], + 'Friday 10:00 (After cutoff)' => ['2026-05-15 10:00:00', '2026-05-22 14:00:00'], + 'Friday 15:00 (After cutoff)' => ['2026-05-15 15:00:00', '2026-05-22 14:00:00'], ]); dataset('current_cutoff_scenarios', [ - 'Monday 10:00' => ['2026-05-11 10:00:00', '2026-05-11 14:00:00'], - 'Tuesday 10:00' => ['2026-05-12 10:00:00', '2026-05-11 14:00:00'], + 'Monday 10:00 (Before cutoff)' => ['2026-05-11 10:00:00', '2026-05-11 14:00:00'], + 'Monday 14:01 (After cutoff)' => ['2026-05-11 14:01:00', '2026-05-18 14:00:00'], + 'Tuesday 10:00 (Next cutoff)' => ['2026-05-12 10:00:00', '2026-05-18 14:00:00'], + 'Friday 10:00 (Next cutoff)' => ['2026-05-15 10:00:00', '2026-05-18 14:00:00'], ]); describe('Pickup Scheduling Service', function (): void { @@ -72,9 +78,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 @@ -120,9 +127,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 @@ -149,9 +157,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 @@ -185,13 +194,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 { @@ -214,9 +220,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 { @@ -231,9 +236,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 @@ -287,7 +293,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 { @@ -300,7 +306,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 { @@ -308,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, @@ -317,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, @@ -361,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(); }); @@ -391,12 +395,104 @@ 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(); }); + + it('resolves nominal, replacement, and closed pickup windows for a target pickup day', function (): void { + // GIVEN + $now = CarbonImmutable::parse('2026-05-04 08:00:00'); + $targetFriday = CarbonImmutable::parse('2026-05-08'); + $shop = createTestShop(1); + + $nominalService = createServiceWithExceptions($now); + $closedService = createServiceWithExceptions($now, [ + createExceptionPivot(date: '2026-05-08', replacementDate: null, orderDeadlineAt: null), + ]); + $replacedService = createServiceWithExceptions($now, [ + createExceptionPivot(date: '2026-05-08', replacementDate: '2026-05-07', orderDeadlineAt: '2026-05-04 16:00:00'), + ]); + + // WHEN + $nominalWindow = $nominalService->getPickupWindowFor($shop, $targetFriday); + $closedWindow = $closedService->getPickupWindowFor($shop, $targetFriday); + $replacedWindow = $replacedService->getPickupWindowFor($shop, $targetFriday); + + // THEN + expect($nominalWindow)->toBeInstanceOf(PickupWindow::class) + ->and($nominalWindow?->timeSlot->getAt()->format('Y-m-d'))->toBe('2026-05-08') + ->and($nominalWindow?->deadline->format('Y-m-d H:i'))->toBe('2026-05-04 14:00') + ->and($closedWindow)->toBeNull() + ->and($replacedWindow)->toBeInstanceOf(PickupWindow::class) + ->and($replacedWindow?->timeSlot->getAt()->format('Y-m-d'))->toBe('2026-05-07') + ->and($replacedWindow?->deadline->format('Y-m-d H:i'))->toBe('2026-05-04 16:00'); + }); + + it('uses Europe/Paris day boundaries when UTC date is still the previous day (00:30 Paris)', function (): void { + // GIVEN: Monday 2026-05-11 00:30 Europe/Paris = Sunday 2026-05-10 22:30 UTC + $repo = \Mockery::mock(PickupExceptionRepository::class); + $repo->shouldReceive('getExceptionsForShop')->andReturn([]); + + $utcNow = CarbonImmutable::parse('2026-05-10 22:30:00', 'UTC'); + $service = new class ($repo, $utcNow) extends PickupSchedulingService + { + public function __construct(PickupExceptionRepository $repo, private readonly CarbonImmutable $utcNow) + { + parent::__construct($repo); + } + + #[\Override] + protected function getNow(): CarbonImmutable + { + return $this->utcNow; + } + }; + + $shop = createTestShop(1); + $targetToday = CarbonImmutable::parse('2026-05-11 00:00:00', 'Europe/Paris'); + $untilNext = CarbonImmutable::parse('2026-05-16 00:00:00', 'Europe/Paris'); + + // WHEN + $windowForParisToday = $service->getPickupWindowFor($shop, $targetToday); + $slots = $service->getTimeSlotsFor($shop, $untilNext); + $period = $service->getPeriodFromPickUpDay(); + + // THEN: today in Paris (Monday 2026-05-11) is rejected as not in the future, Friday 15 is open + expect($windowForParisToday)->toBeNull() + ->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'); + }); + + it('allows ordering for Friday even when Monday (CUTOFF_DAY) is a public holiday', function (): void { + // GIVEN: Whit Monday 2026-05-25 is a public holiday, Friday 2026-05-29 is open + $now = CarbonImmutable::parse('2026-05-25 10:00:00'); + $until = $now->addWeeks(2); + $shop = createTestShop(1); + + $exceptions = [ + createExceptionPivot(date: '2026-05-25', replacementDate: null, orderDeadlineAt: null), + ]; + + $service = createServiceWithExceptions($now, $exceptions); + + // WHEN + $slots = $service->getTimeSlotsFor($shop, $until); + + // THEN + $dates = array_map(static fn (PickupTimeSlot $slot): string => $slot->getAt()->format('Y-m-d'), $slots); + expect($dates)->toContain('2026-05-29'); + }); }); /** @@ -432,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/RegateServiceTest.php b/tests/Unit/Domain/Services/RegateServiceTest.php deleted file mode 100644 index 05c2e485..00000000 --- a/tests/Unit/Domain/Services/RegateServiceTest.php +++ /dev/null @@ -1,90 +0,0 @@ -shouldReceive('generate')->once()->with( - 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; - }) - )->andReturn('csv_content'); - - $dispatcher->shouldReceive('dispatch')->once()->with(Mockery::on(function (object $event) use ($orderReferenceValue): bool { - return $event instanceof RegateOrderCsvGenerated - && $event->csvContent === 'csv_content' - && str_contains($event->fileName, sprintf('BTQ-%s-', $orderReferenceValue)); - })); - - // WHEN - $service->processOrder($reference, $employeeMatricule, $pickupDay, [$line1, $line2, $line3]); - - // THEN - expect(true)->toBeTrue(); - }); -}); diff --git a/tests/Unit/Domain/Services/ShopperServiceTest.php b/tests/Unit/Domain/Services/ShopperServiceTest.php index 6d1500e5..26b5b6b0 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; @@ -18,7 +19,18 @@ 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'); + CarbonImmutable::setTestNow($now); + Carbon::setTestNow($now); +}); + +afterEach(function (): void { + CarbonImmutable::setTestNow(); + Carbon::setTestNow(); +}); describe('ShopperService', function (): void { @@ -28,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'), @@ -57,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', @@ -70,7 +82,7 @@ describe('ShopperService', function (): void { ); $shop = new Shop( - new ShopId(Uuid::uuid7()), + new ShopId(UuidHelper::v7()), 'Shop', 'Addr', '00000', @@ -92,7 +104,7 @@ describe('ShopperService', function (): void { $service = new ShopperService($shopRepo, $shopperRepo); $shopper = new Shopper( - isset($id) ? $id : new ShopperId(Uuid::uuid7()), + new ShopperId(UuidHelper::v7()), new Email('test@test.com'), new Matricule('1234567'), 'Nom', @@ -104,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); @@ -122,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', @@ -134,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); @@ -153,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', @@ -165,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); @@ -184,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 @@ -200,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'), @@ -215,7 +227,7 @@ describe('ShopperService', function (): void { ); $shop = new Shop( - new ShopId(Uuid::uuid7()), + new ShopId(UuidHelper::v7()), 'Shop', 'Addr', '00000', @@ -237,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 @@ -253,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/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/Repositories/SessionBasketRepositoryTest.php b/tests/Unit/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php deleted file mode 100644 index 6710ce64..00000000 --- a/tests/Unit/Infra/Adapters/Repositories/SessionBasketRepositoryTest.php +++ /dev/null @@ -1,122 +0,0 @@ -shouldReceive('has')->with('basket_key' . $basketId->value->toString())->andReturn(false); - - $serializer = \Mockery::mock(BasketSerializer::class); - - $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..b7dcebd8 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; @@ -14,18 +16,19 @@ 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 () { - describe('BasketSerializer', function () { +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)), + id: new ProductId(UuidHelper::fromString($productIdStr)), name: 'Product 1', qty: 2, unitPriceHt: new Money(1000, new Currency('EUR')), @@ -36,7 +39,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), @@ -45,18 +48,19 @@ it('serializes and deserializes basket correctly', function () { ); $basket = new Basket( - id: new BasketId(Uuid::fromString($basketIdStr)), + id: new BasketId(UuidHelper::fromString($basketIdStr)), items: [$productIdStr => $basketProduct] ); // WHEN - $array = $serializer->toArray($basket); - $array = json_decode(json_encode($array), true); + $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) + 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) @@ -72,9 +76,9 @@ it('serializes and deserializes basket correctly', function () { 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(); + $productIdStr = UuidHelper::v7()->toString(); $data = [ - 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), + 'id' => UuidHelper::v7()->toString(), 'items' => [ [ 'id' => $productIdStr, @@ -107,9 +111,9 @@ it('serializes and deserializes basket correctly', function () { it('throws exception if currency is missing during deserialization', function () { // GIVEN $serializer = new BasketSerializer(); - $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); + $productIdStr = UuidHelper::v7()->toString(); $data = [ - 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), + 'id' => UuidHelper::v7()->toString(), 'items' => [ [ 'id' => $productIdStr, @@ -140,9 +144,9 @@ it('serializes and deserializes basket correctly', function () { it('throws exception if currency is missing for unitDiscount', function () { // GIVEN $serializer = new BasketSerializer(); - $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); + $productIdStr = UuidHelper::v7()->toString(); $data = [ - 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), + 'id' => UuidHelper::v7()->toString(), 'items' => [ [ 'id' => $productIdStr, @@ -173,9 +177,9 @@ it('serializes and deserializes basket correctly', function () { it('throws exception if currency is missing for priceKgTtc', function () { // GIVEN $serializer = new BasketSerializer(); - $productIdStr = \Symfony\Component\Uid\Uuid::v7()->toRfc4122(); + $productIdStr = UuidHelper::v7()->toString(); $data = [ - 'id' => \Symfony\Component\Uid\Uuid::v7()->toRfc4122(), + 'id' => UuidHelper::v7()->toString(), 'items' => [ [ 'id' => $productIdStr, 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 () { 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/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php b/tests/Unit/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php deleted file mode 100644 index fb790147..00000000 --- a/tests/Unit/Infra/Adapters/Services/SessionOrderBuilderManagerTest.php +++ /dev/null @@ -1,85 +0,0 @@ - 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(OrderBuilder::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(OrderBuilder::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(); -}); diff --git a/tests/Unit/Services/CrmServiceTest.php b/tests/Unit/Services/CrmServiceTest.php deleted file mode 100644 index b8a1b546..00000000 --- a/tests/Unit/Services/CrmServiceTest.php +++ /dev/null @@ -1,217 +0,0 @@ -toString(); - - $libCustomer = new Customer([ - 'hashcode' => $uuid, - 'email' => 'john@example.com', - 'password' => 'Secret123!', - 'firstname' => 'John', - 'lastname' => 'Doe', - 'birth_date' => '1990-01-01', - 'phone' => '0123456789', - 'address' => '123 Main St', - 'address2' => null, - 'city' => 'Paris', - 'postcode' => '75000', - 'country' => EnumsCountry::france, - 'opt_in' => true, - 'status' => true, - 'last_connection' => null, - ]); - - $cacheKey = "crm_customer_hashcode_{$uuid}"; - - $cacheRepository->shouldReceive('remember') - ->once() - ->with($cacheKey, Mockery::any(), Mockery::on(function ($closure) use ($crmApi, $libCustomer, $uuid) { - $crmApi->shouldReceive('getCustomer')->with((string) $uuid)->once()->andReturn($libCustomer); - $result = $closure(); - - return $result instanceof CrmCustomer && $result->hashcode === (string) $uuid; - })) - ->andReturn(new CrmCustomer( - hashcode: (string) $uuid, - email: 'john@example.com', - password: 'Secret123!', - firstname: 'John', - lastname: 'Doe', - birthDate: '1990-01-01', - phone: '0123456789', - address: '123 Main St', - address2: null, - city: 'Paris', - postcode: '75000', - country: Country::france, - optIn: true, - status: true, - lastConnection: null, - )); - - $service = new CrmService($crmApi, $cacheRepository); - $hashcode = new CrmHashcode($uuidObj); - - // WHEN - $firstCall = $service->getCustomerFromHashCode($hashcode); - - // Second call should return from internal memory cache without querying CacheRepository again - $secondCall = $service->getCustomerFromHashCode($hashcode); - - // THEN - expect($firstCall)->toBeInstanceOf(CrmCustomer::class) - ->and($firstCall->hashcode)->toBe($uuid) - ->and($secondCall)->toBe($firstCall); - }); - - it('returns customer from email with sha256 cache key', function (): void { - // GIVEN - $crmApi = Mockery::mock(CrmApiV4::class); - $cacheRepository = Mockery::mock(CacheRepository::class); - - $email = 'test@example.com'; - $cacheKey = 'crm_customer_email_' . hash('sha256', $email); - - $expectedCustomer = new CrmCustomer( - hashcode: (string) Uuid::uuid4(), - email: $email, - password: 'Secret123!', - firstname: 'Jane', - lastname: 'Doe', - birthDate: '1992-05-10', - phone: '0123456789', - address: '456 Side St', - address2: null, - city: 'Lyon', - postcode: '69000', - country: Country::france, - optIn: false, - status: true, - lastConnection: null, - ); - - $cacheRepository->shouldReceive('remember') - ->once() - ->with($cacheKey, Mockery::any(), Mockery::type('Closure')) - ->andReturn($expectedCustomer); - - $service = new CrmService($crmApi, $cacheRepository); - - // WHEN - $result = $service->getCustomerFromEmail($email); - - // THEN - expect($result)->toBeInstanceOf(CrmCustomer::class) - ->and($result->email)->toBe($email); - }); - - it('returns null on modelNotFound ApiErrorException and caches result', function (): void { - // GIVEN - $crmApi = Mockery::mock(CrmApiV4::class); - $cacheRepository = Mockery::mock(CacheRepository::class); - - $uuid = Uuid::uuid4(); - $cacheKey = "crm_customer_hashcode_{$uuid}"; - - $cacheRepository->shouldReceive('remember') - ->once() - ->with($cacheKey, Mockery::any(), Mockery::on(function ($closure) use ($crmApi, $uuid) { - $exception = Mockery::mock(ApiErrorException::class); - $exception->shouldReceive('getApiError')->andReturn(ApiError::modelNotFound); - $crmApi->shouldReceive('getCustomer')->with((string) $uuid)->once()->andThrow($exception); - $res = $closure(); - - return $res === null; - })) - ->andReturnNull(); - - $service = new CrmService($crmApi, $cacheRepository); - - // WHEN - $result = $service->getCustomerFromHashCode(new CrmHashcode($uuid)); - - // THEN - expect($result)->toBeNull(); - }); - - it('invalidates cache on activate', function (): void { - // GIVEN - $crmApi = Mockery::mock(CrmApiV4::class); - $cacheRepository = Mockery::mock(CacheRepository::class); - - $uuid = (string) Uuid::uuid4(); - - $customer = new CrmCustomer( - hashcode: $uuid, - email: 'activate@example.com', - password: 'Secret123!', - firstname: 'John', - lastname: 'Doe', - birthDate: '1990-01-01', - phone: '0123456789', - address: '123 Main St', - address2: null, - city: 'Paris', - postcode: '75000', - country: Country::france, - optIn: true, - status: false, - lastConnection: null, - ); - - $expectedHashKey = "crm_customer_hashcode_{$uuid}"; - $expectedEmailKey = 'crm_customer_email_' . hash('sha256', 'activate@example.com'); - - $cacheRepository->shouldReceive('delete')->with($expectedHashKey)->once(); - $cacheRepository->shouldReceive('delete')->with($expectedEmailKey)->once(); - - $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 - $result = $service->activate($customer); - - // THEN - expect($result)->toHaveProperty('result'); - }); -}); diff --git a/tests/Unit/Services/IcsGeneratorServiceTest.php b/tests/Unit/Services/IcsGeneratorServiceTest.php deleted file mode 100644 index 9cfcf290..00000000 --- a/tests/Unit/Services/IcsGeneratorServiceTest.php +++ /dev/null @@ -1,43 +0,0 @@ -generate($event); - - // THEN - expect($ics)->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'); -}); diff --git a/tests/Unit/Services/StatsServiceTest.php b/tests/Unit/Services/StatsServiceTest.php deleted file mode 100644 index 8c5b3dcd..00000000 --- a/tests/Unit/Services/StatsServiceTest.php +++ /dev/null @@ -1,124 +0,0 @@ -shouldReceive('countActiveEmployeesWithin')->andReturn(100); - $employeeDirectory->shouldReceive('countActiveRegisteredEmployeesWithin')->andReturn(25); - - $service = new StatsService($employeeDirectory, $orderDirectory); - - $start = CarbonImmutable::now()->subDays(10); - $end = CarbonImmutable::now(); - - // WHEN - $rate = $service->getMembershipRate($start, $end); - - // THEN - expect($rate)->toBe(25.0); - }); - - it('returns 0 for membership rate when no active employees', function () { - // GIVEN - $employeeDirectory = mock(EmployeeDirectory::class); - $orderDirectory = mock(OrderDirectory::class); - - $employeeDirectory->shouldReceive('countActiveEmployeesWithin')->andReturn(0); - $employeeDirectory->shouldReceive('countActiveRegisteredEmployeesWithin')->andReturn(0); - - $service = new StatsService($employeeDirectory, $orderDirectory); - - $start = CarbonImmutable::now()->subDays(10); - $end = CarbonImmutable::now(); - - // WHEN - $rate = $service->getMembershipRate($start, $end); - - // THEN - expect($rate)->toBe(0.0); - }); - - it('calculates membership percentage correctly', function () { - // GIVEN - $employeeDirectory = mock(EmployeeDirectory::class); - $orderDirectory = mock(OrderDirectory::class); - - $employeeDirectory->shouldReceive('countActiveEmployees')->andReturn(200); - $employeeDirectory->shouldReceive('countActiveRegisteredEmployees')->andReturn(150); - - $service = new StatsService($employeeDirectory, $orderDirectory); - - // WHEN - $percentage = $service->getMembershipPercentage(); - - // THEN - expect($percentage)->toBe(75.0); - }); - - it('returns 0 for membership percentage when no active employees', function () { - // GIVEN - $employeeDirectory = mock(EmployeeDirectory::class); - $orderDirectory = mock(OrderDirectory::class); - - $employeeDirectory->shouldReceive('countActiveEmployees')->andReturn(0); - $employeeDirectory->shouldReceive('countActiveRegisteredEmployees')->andReturn(0); - - $service = new StatsService($employeeDirectory, $orderDirectory); - - // WHEN - $percentage = $service->getMembershipPercentage(); - - // THEN - expect($percentage)->toBe(0.0); - }); - - it('gets the previous period', function () { - // GIVEN - $employeeDirectory = mock(EmployeeDirectory::class); - $orderDirectory = mock(OrderDirectory::class); - - $service = new StatsService($employeeDirectory, $orderDirectory); - - $start = CarbonImmutable::now()->subDays(10); - $end = CarbonImmutable::now(); - - // WHEN - $previousPeriod = $service->getPreviousPeriod($start, $end); - - // THEN - expect($previousPeriod->getStartDate()->toDateString())->toBe($start->copy()->subDays(11)->toDateString()); - expect($previousPeriod->getIncludedEndDate()->toDateString())->toBe($start->copy()->subDays(1)->toDateString()); - }); - - it('calculates nbSalarie stat correctly', function () { - // GIVEN - $employeeDirectory = mock(EmployeeDirectory::class); - $orderDirectory = mock(OrderDirectory::class); - - $employeeDirectory->shouldReceive('countActiveEmployeesWithin')->andReturnValues([50, 100]); // previous, current - - $service = new StatsService($employeeDirectory, $orderDirectory); - - $start = CarbonImmutable::now()->subDays(10); - $end = CarbonImmutable::now(); - - // WHEN - $stats = $service->getStats([StatsCustomerType::nbSalarie], $start, $end); - - // THEN - expect($stats[StatsCustomerType::nbSalarie->value]['previous'])->toBe(50); - expect($stats[StatsCustomerType::nbSalarie->value]['current'])->toBe(100); - expect($stats[StatsCustomerType::nbSalarie->value]['diff'])->toBe(50); - }); -}); diff --git a/tests/Unit/Shared/Enums/BaseEnumTest.php b/tests/Unit/Shared/Enums/BaseEnumTest.php new file mode 100644 index 00000000..349a2c04 --- /dev/null +++ b/tests/Unit/Shared/Enums/BaseEnumTest.php @@ -0,0 +1,107 @@ +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/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'; +} 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..a72c6122 --- /dev/null +++ b/tests/Unit/Shared/Helpers/UuidHelperTest.php @@ -0,0 +1,160 @@ +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); + }); + + 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/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/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 diff --git a/tests/Unit/Shared/ValueObjects/CrmHashcodeTest.php b/tests/Unit/Shared/ValueObjects/CrmHashcodeTest.php new file mode 100644 index 00000000..62300f30 --- /dev/null +++ b/tests/Unit/Shared/ValueObjects/CrmHashcodeTest.php @@ -0,0 +1,47 @@ +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 = 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); + }); +});