Compare commits

..

82 commits

Author SHA1 Message Date
Jérémy Munsch
eda60066b1
Merge branch 'trunk' 2026-11-17 10:39:34 +01:00
Jérémy Munsch
276be44fa4
Merge branch 'develop' into trunk 2026-11-17 10:32:33 +01:00
Jérémy Munsch
d016a66601
Merge branch 'develop' into trunk 2026-11-17 10:26:20 +01:00
Jérémy Munsch
178f2e0bda
Merge branch 'develop' into trunk 2026-11-17 09:50:22 +01:00
Jérémy Munsch
9d2c5323ae
Merge branch 'trunk' 2026-11-02 16:44:33 +01:00
Jérémy Munsch
bd8e90b5e4
Merge branch 'develop' into trunk 2026-11-02 16:35:09 +01:00
Jérémy Munsch
d5ed718874
Merge branch 'develop' into trunk 2026-11-02 15:36:37 +01:00
Jérémy Munsch
946342d975
Merge branch 'develop' into trunk 2026-11-02 15:24:42 +01:00
Jérémy Munsch
e9454f9dbb
Merge branch 'develop' into trunk 2026-11-02 15:21:43 +01:00
Jérémy Munsch
eca7a9adbf
Merge branch 'develop' into trunk 2026-11-02 15:19:07 +01:00
Jérémy Munsch
327defbee0
Merge branch 'trunk' 2026-11-02 11:33:05 +01:00
Jérémy Munsch
dd4f4ce253
Merge branch 'develop' into trunk 2026-11-02 11:24:12 +01:00
Jeremy Munsch
24c151cc99
Merge branch 'trunk' 2026-10-30 11:00:55 +01:00
Jérémy Munsch
e8a6ab07de
Merge branch 'develop' into trunk 2026-10-29 21:16:37 +01:00
Jérémy Munsch
28d6200136
Merge branch 'develop' into trunk 2026-10-29 20:35:49 +01:00
Jérémy Munsch
f174aa74cf
Merge branch 'develop' into trunk 2026-10-29 17:10:19 +01:00
Jérémy Munsch
dfaa74be01
Merge branch 'develop' into trunk 2026-10-29 17:08:21 +01:00
Jérémy Munsch
62363253ce
Merge branch 'develop' into trunk 2026-10-29 17:06:40 +01:00
Jérémy Munsch
e66f3ce17d
Merge branch 'develop' into trunk 2026-10-28 15:25:32 +01:00
Jérémy Munsch
eb72abb9d2
Merge branch 'develop' into trunk 2026-10-28 15:19:02 +01:00
Jérémy Munsch
8be89194e3
Merge branch 'develop' into trunk 2026-10-28 15:13:49 +01:00
Jérémy Munsch
5ca0f4ddde
Merge branch 'develop' into trunk 2026-10-28 13:16:00 +01:00
Jérémy Munsch
8d43d71370
Merge branch 'develop' into trunk 2026-10-28 11:58:00 +01:00
Jérémy Munsch
35306547c9
Merge branch 'develop' into trunk 2026-10-28 11:53:30 +01:00
Jérémy Munsch
b166fa01e1
Merge branch 'develop' into trunk 2026-10-28 08:57:43 +01:00
Jérémy Munsch
6388c2a085
Merge branch 'develop' into trunk 2026-10-27 20:20:57 +01:00
Jérémy Munsch
46e9a873ab
Merge branch 'develop' into trunk 2026-10-27 20:18:15 +01:00
Jérémy Munsch
644b3f6c16
Merge branch 'develop' into trunk 2026-10-27 20:02:47 +01:00
Jérémy Munsch
87bd150f6b
Merge branch 'develop' into trunk 2026-10-27 18:57:57 +01:00
Jérémy Munsch
283038e5f4
Merge branch 'develop' into trunk 2026-10-27 17:33:48 +01:00
Jérémy Munsch
46a3ae4dc3
Merge branch 'develop' into trunk 2026-10-27 17:08:05 +01:00
Jérémy Munsch
99822b5a51
Merge branch 'develop' into trunk 2026-10-27 16:39:30 +01:00
Jérémy Munsch
0ca572537c
Merge branch 'develop' into trunk 2026-10-27 16:21:00 +01:00
Jérémy Munsch
c4e1bfa80a
Merge branch 'develop' into trunk 2026-10-27 16:17:53 +01:00
Jérémy Munsch
b67ea17584
Merge branch 'develop' into trunk 2026-10-27 15:23:47 +01:00
Jérémy Munsch
055ce2eb5d
Merge branch 'develop' into trunk 2026-10-27 13:55:36 +01:00
Jérémy Munsch
53f86fce63
Merge branch 'develop' into trunk 2026-10-27 13:53:47 +01:00
Jérémy Munsch
75646a5f49
build: fix build npm-security 2026-10-27 13:48:57 +01:00
Jérémy Munsch
81dc370134
build: fix build npm-security 2026-10-27 13:44:56 +01:00
Jérémy Munsch
ce28473860
Merge branch 'develop' into trunk 2026-10-27 13:03:33 +01:00
Jérémy Munsch
534e14f2e8
Merge branch 'develop' into trunk 2026-10-27 12:48:07 +01:00
Jérémy Munsch
38de1011ee
Merge branch 'develop' into trunk 2026-10-27 12:40:26 +01:00
Jérémy Munsch
f29ef10a43
Merge branch 'develop' into trunk 2026-10-27 11:43:50 +01:00
K Muller
53e5f47bcf Merge branch 'trunk' 2026-10-08 10:28:46 +02:00
K Muller
c9b64d4fe5 Merge branch 'develop' into trunk 2026-10-08 10:28:26 +02:00
Noah Lancien
7125bf8ead Merge branch 'trunk' 2026-05-11 14:25:51 +02:00
Noah Lancien
e5f3ea4d04 Merge branch 'develop' into trunk 2026-05-11 11:39:47 +02:00
Noix
772cd92f85 Merge branch 'vb-fix-timeslots' into 'master'
fix: Fix timeslot db request

See merge request ldc-web/projets/boutique-cnc-sable!85
2026-05-04 10:24:45 +00:00
Vincent BRIDIER
f8537635bc fix: Fix timeslot db request 2026-05-04 12:19:44 +02:00
Noah Lancien
a3c7193e05 Merge branch 'trunk' 2026-04-21 14:50:57 +02:00
Noah Lancien
2740798612 Merge branch 'develop' into trunk 2026-04-21 14:50:50 +02:00
Noah Lancien
f07fae78a2 Merge branch 'trunk' 2026-04-21 14:37:19 +02:00
Noah Lancien
eb91d4d17f Merge branch 'develop' into trunk 2026-04-21 14:23:14 +02:00
Noah Lancien
5cad93d548 Merge branch 'trunk' 2026-04-16 16:02:05 +02:00
Noah Lancien
152bc58474 Merge branch 'develop' into trunk 2026-04-16 16:01:49 +02:00
Noah Lancien
5d2d58cd7a Merge branch 'trunk' 2026-03-26 16:16:29 +01:00
Noah Lancien
6ff2257144 Merge branch 'develop' into trunk 2026-03-03 10:59:09 +01:00
Noah Lancien
f352408c40 Merge branch 'develop' into trunk 2026-03-03 09:49:18 +01:00
Noah Lancien
c7c2175625 Merge branch 'develop' into trunk 2026-02-26 14:13:08 +01:00
Noah Lancien
2c63b95f86 Merge branch 'trunk' 2026-02-12 10:57:47 +01:00
Noah Lancien
d74badf9b8 Merge branch 'develop' into trunk 2026-02-12 10:56:57 +01:00
Noah Lancien
43a33daa01 Merge branch 'trunk' 2026-02-05 17:17:49 +01:00
Noah Lancien
4f5be11730 Merge branch 'develop' into trunk 2026-02-05 17:17:33 +01:00
Noah Lancien
ed77e6aef9 Merge branch 'trunk' 2026-02-04 12:12:04 +01:00
Noah Lancien
2cf1a2761a Merge branch 'develop' into trunk 2026-02-04 12:11:46 +01:00
Noah Lancien
3c2f785441 Merge branch 'trunk' 2026-02-03 09:37:11 +01:00
Noah Lancien
7661bba6ca Merge branch 'develop' into trunk 2026-02-03 09:36:54 +01:00
Noah Lancien
8db9c7dc4c Merge branch 'trunk' 2026-02-03 09:25:45 +01:00
Noah Lancien
9a8d7b400a Merge branch 'develop' into trunk 2026-02-03 09:25:27 +01:00
Noah Lancien
60497326fe Merge branch 'trunk' 2026-02-03 09:22:13 +01:00
Noah Lancien
2c0961dcc3 Merge branch 'develop' into trunk 2026-02-03 09:21:26 +01:00
Noah Lancien
1f32078053 Merge branch 'trunk' 2025-11-12 17:22:19 +01:00
Noah Lancien
38771721ea Merge branch 'develop' into trunk 2025-11-12 17:21:59 +01:00
Noah Lancien
7ccd63db5f Merge branch 'trunk' 2025-07-08 16:59:29 +02:00
Noah Lancien
5758a1d40c Merge branch 'develop' into trunk 2025-07-08 16:44:51 +02:00
Vincent BRIDIER
28448a34a7
Merge branch 'trunk' 2025-05-12 15:35:00 +02:00
Karl Muller
f984799a02 Merge branch 'develop' into trunk 2025-04-28 14:46:33 +00:00
Karl Muller
a94589fb13 Merge branch 'develop' into trunk 2025-04-02 08:34:54 +00:00
Noah Lancien
24cfb976f6 Merge branch 'develop' into trunk 2025-02-24 15:31:41 +01:00
Noah Lancien
931a79444b Merge branch 'develop' into trunk 2025-02-14 16:20:47 +01:00
Noah Lancien
c287334426 Merge branch 'develop' into trunk 2025-02-13 15:07:20 +01:00
Noah Lancien
7547491e46 Merge branch 'develop' into trunk 2025-02-13 15:02:00 +01:00
1021 changed files with 22449 additions and 38204 deletions

View file

@ -1,4 +1,3 @@
# APP
APP_NAME=Laravel APP_NAME=Laravel
APP_ENV=local APP_ENV=local
APP_KEY= APP_KEY=
@ -6,11 +5,9 @@ APP_DEBUG=true
APP_URL=http://localhost APP_URL=http://localhost
APP_CURRENCY=EUR APP_CURRENCY=EUR
# LOG
LOG_CHANNEL=stack LOG_CHANNEL=stack
LOG_LEVEL=debug LOG_LEVEL=debug
# DB
DB_CONNECTION=mysql DB_CONNECTION=mysql
DB_HOST=127.0.0.1 DB_HOST=127.0.0.1
DB_PORT=3306 DB_PORT=3306
@ -18,42 +15,14 @@ DB_DATABASE=laravel
DB_USERNAME=root DB_USERNAME=root
DB_PASSWORD= DB_PASSWORD=
# BROADCAST, CACHE, QUEUE
BROADCAST_DRIVER=log BROADCAST_DRIVER=log
CACHE_STORE=file CACHE_STORE=file
QUEUE_CONNECTION=sync QUEUE_CONNECTION=sync
# SESSION
SESSION_DRIVER=file SESSION_DRIVER=file
SESSION_LIFETIME=120 SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_SECURE_COOKIE=false
SESSION_PATH=/
SESSION_DOMAIN=
SESSION_CONNECTION=
# REDIS FILESYSTEM_DISK=local
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_MAILER=log
MAIL_SCHEME=null MAIL_SCHEME=null
MAIL_HOST=127.0.0.1 MAIL_HOST=127.0.0.1
@ -71,10 +40,10 @@ CRM_ENDPOINT=
CRM_TOKEN= CRM_TOKEN=
CRM_PASSWORD= CRM_PASSWORD=
# SENTRY # Sentry
SENTRY_LARAVEL_DSN= SENTRY_LARAVEL_DSN=
# MATOMO # Matomo
MATOMO_SITE_ID= MATOMO_SITE_ID=
# UWIL ADMIN SECURE # UWIL ADMIN SECURE
@ -83,13 +52,13 @@ UWIL_ADMIN_SECURE_CIDR_LIST=""
# - LIST SEPARATED WITH ',' (Optional) # - LIST SEPARATED WITH ',' (Optional)
UWIL_ADMIN_SECURE_CIDR_PROJECT_ALLOWED_LIST="" UWIL_ADMIN_SECURE_CIDR_PROJECT_ALLOWED_LIST=""
# ARCADIA API # Arcadia API
ARCADIA_API_ENDPOINT= ARCADIA_API_ENDPOINT=
ARCADIA_API_APIKEY= ARCADIA_API_APIKEY=
ARCADIA_API_SECRET= ARCADIA_API_SECRET=
ARCADIA_API_IGNORE_SELF_SIGNED_CERT=false ARCADIA_API_IGNORE_SELF_SIGNED_CERT=false
# SERIAL CASTER # Serial Caster
SERIAL_CASTER_SEED=12345 SERIAL_CASTER_SEED=12345
# LDC # LDC

View file

@ -79,11 +79,7 @@ phpstan:
variables: variables:
PHP_MEMORY_LIMIT: "512M" PHP_MEMORY_LIMIT: "512M"
COMPOSER_CACHE_DIR: ".composer-cache" COMPOSER_CACHE_DIR: ".composer-cache"
CRM_ENDPOINT: "http://fake-url.com"
CRM_TOKEN: "fake-token"
CRM_PASSWORD: "fake-password"
script: script:
- cp .env.example .env
- php -d memory_limit=512M vendor/bin/phpstan --error-format=junit > phpstan-report.xml - php -d memory_limit=512M vendor/bin/phpstan --error-format=junit > phpstan-report.xml
artifacts: artifacts:
when: on_failure when: on_failure
@ -257,29 +253,12 @@ tests_laravel:
- name: mysql:8.0 - name: mysql:8.0
alias: mysql alias: mysql
before_script: 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 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 - composer install --no-scripts --no-interaction --no-ansi --no-progress --prefer-dist
script: script:
- cp .env.example .env - cp .env.example .env
- php artisan key:generate - 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 config:clear
- php artisan test --coverage --colors=never --log-junit=coverage/junit.xml --coverage-cobertura=coverage/cobertura.xml --coverage-html=coverage/html - php artisan test --coverage --colors=never --log-junit=coverage/junit.xml --coverage-cobertura=coverage/cobertura.xml --coverage-html=coverage/html
after_script: after_script:

View file

@ -7,18 +7,12 @@ 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`. 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`). - **Jour de retrait standard** : Uniquement le **Vendredi** (`PICKUP_DAY = WeekDay::Friday`).
- **Heure de clôture (Cutoff)** : **Lundi à 14h00** (`Europe/Paris`) de la même semaine (`CUTOFF_DAY = Monday`, `CUTOFF_HOUR = 14`). - **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 (`<= 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. - *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.
- *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). - **Gestion des Exceptions** :
- **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`. - 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 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 `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`). - Une tâche planifiée `UpsertShopsPickupExceptionsUsingApiForYear` est lancée pour provisionner les jours fériés de l'année pour toutes les boutiques
- 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 ## 2. Limites de Montants
@ -37,61 +31,3 @@ Elle est géré par le service `ProductAvailabilityService`.
- Il est éligible INCO (`hasInco = true`). - Il est éligible INCO (`hasInco = true`).
- La date actuelle est supérieure ou égale à `orderable_start` (si défini). - La date actuelle est supérieure ou égale à `orderable_start` (si défini).
- La date actuelle est inférieure à `orderable_end` (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()`).

View file

@ -1,24 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Attributes;
use Webmozart\Assert\Assert;
#[\Attribute(\Attribute::TARGET_CLASS)]
final readonly class Locked
{
public function __construct(
public int $ttlSeconds = 30,
public int $waitSeconds = 10,
public ?string $key = null,
) {
Assert::greaterThan($this->ttlSeconds, 0);
Assert::greaterThanEq($this->waitSeconds, 0);
if ($this->key !== null) {
Assert::stringNotEmpty(trim($this->key));
}
}
}

View file

@ -1,10 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Attributes;
#[\Attribute(\Attribute::TARGET_CLASS)]
final readonly class WithoutTransaction
{
}

View file

@ -9,16 +9,23 @@ use App\Exceptions\Crm\CrmCustomerNotActivatedException;
use App\Exceptions\CrmServiceException; use App\Exceptions\CrmServiceException;
use App\Models\Customer; use App\Models\Customer;
use App\Services\CrmService; use App\Services\CrmService;
use Domain\Models\ValueObjects\CrmCustomer;
use Domain\Models\ValueObjects\Email;
use Illuminate\Auth\EloquentUserProvider; use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Hashing\Hasher; use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use Shared\ValueObjects\CrmHashcode;
use UnexpectedValueException;
class CrmUserProvider extends EloquentUserProvider implements UserProvider class CrmUserProvider extends EloquentUserProvider implements UserProvider
{ {
private ?CrmCustomer $crmCustomer = null;
/** /**
* @param class-string<\Illuminate\Contracts\Auth\Authenticatable&\Illuminate\Database\Eloquent\Model> $model * @param class-string<\Illuminate\Contracts\Auth\Authenticatable&\Illuminate\Database\Eloquent\Model> $model
*/ */
@ -49,12 +56,7 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
#[\Override] #[\Override]
public function retrieveByCredentials(array $credentials): ?Authenticatable 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')); $result = $this->crmService->getCustomerFromEmail(Arr::string($credentials, 'email'));
if ($result instanceof CrmServiceException) { if ($result instanceof CrmServiceException) {
@ -64,7 +66,13 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
]); ]);
} }
return $result !== null ? $model : null; $this->crmCustomer = $result;
if ($this->crmCustomer instanceof CrmCustomer && $model === null) {
$model = $this->createLocalCustomer($this->crmCustomer);
}
return $this->crmCustomer !== null ? $model : null;
} }
/** /**
@ -80,11 +88,11 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
public function validateCredentials(Authenticatable $model, array $credentials): bool public function validateCredentials(Authenticatable $model, array $credentials): bool
{ {
if ($model::class !== $this->usedModel) { 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))) { 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 */ /** @var \Illuminate\Contracts\Auth\Authenticatable&\Illuminate\Contracts\Auth\MustVerifyEmail $model */
$requestEmail = Arr::string($credentials, 'email'); $requestEmail = Arr::string($credentials, 'email');
@ -98,11 +106,7 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
return true; return true;
} catch (CrmCustomerNotActivatedException) { } catch (CrmCustomerNotActivatedException) {
try { $model->sendEmailVerificationNotification();
$model->sendEmailVerificationNotification();
} catch (\Throwable $e) {
report($e);
}
return true; return true;
} catch (CrmAuthenticationFailedException) { } catch (CrmAuthenticationFailedException) {
@ -121,4 +125,26 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
{ {
// No hashing. // 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;
}
} }

View file

@ -1,62 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Date;
/**
* Stores calendar-only SQL DATE columns as Y-m-d without shifting timezones to UTC.
*
* @implements CastsAttributes<\Illuminate\Support\Carbon, \DateTimeInterface | string | null>
*/
class CalendarDateCast implements CastsAttributes
{
public bool $withoutObjectCaching = true;
/** @param array<string, mixed> $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<string, mixed> $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.');
}
}

View file

@ -6,7 +6,7 @@ namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Shared\Helpers\UuidHelper; use Ramsey\Uuid\Uuid;
use Shared\ValueObjects\CrmHashcode; use Shared\ValueObjects\CrmHashcode;
/** @implements CastsAttributes<CrmHashcode, CrmHashcode|string> */ /** @implements CastsAttributes<CrmHashcode, CrmHashcode|string> */
@ -19,7 +19,7 @@ class CrmHashcodeCast implements CastsAttributes
throw new \UnexpectedValueException('CrmHashcode must be a string.'); throw new \UnexpectedValueException('CrmHashcode must be a string.');
} }
$uuid = UuidHelper::fromString($value); $uuid = Uuid::fromString($value);
return new CrmHashcode($uuid); return new CrmHashcode($uuid);
} }
@ -32,7 +32,7 @@ class CrmHashcodeCast implements CastsAttributes
} }
if (is_string($value)) { if (is_string($value)) {
$value = new CrmHashcode(UuidHelper::fromString($value)); $value = new CrmHashcode(Uuid::fromString($value));
} }
if (! ($value instanceof CrmHashcode)) { if (! ($value instanceof CrmHashcode)) {

View file

@ -1,45 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
/** @implements CastsAttributes<StorageFilePath|null, StorageFilePath|string|null> */
class FilePathCast implements CastsAttributes
{
/** @param array<string, mixed> $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<string, mixed> $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.');
}
}

View file

@ -14,8 +14,8 @@ use Domain\Models\ValueObjects\ProductWeight;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Shared\Helpers\UuidHelper; use Ramsey\Uuid\Uuid;
use Uwil\Storage\Lib\ValueObjects\StorageFilePath; use Symfony\Component\Uid\Uuid as SymfonyUuid;
/** /**
* @implements CastsAttributes<OrderLineProduct,OrderLineProduct> * @implements CastsAttributes<OrderLineProduct,OrderLineProduct>
@ -44,7 +44,9 @@ class OrderLineProductCast implements CastsAttributes
return new OrderLineProduct( return new OrderLineProduct(
incoId: new IncoId(Arr::integer($data, 'inco_id')), incoId: new IncoId(Arr::integer($data, 'inco_id')),
originalId: new ProductId(UuidHelper::parse(Arr::string($data, 'original_id'))), originalId: new ProductId(Uuid::fromString(
SymfonyUuid::fromString(Arr::string($data, 'original_id'))->toRfc4122()
)),
name: Arr::string($data, 'name'), name: Arr::string($data, 'name'),
weight: new ProductWeight( weight: new ProductWeight(
value: Arr::integer($data, 'weight'), value: Arr::integer($data, 'weight'),
@ -56,7 +58,7 @@ class OrderLineProductCast implements CastsAttributes
discountedPrice: new MoneyCast()->get($model, 'discounted_price', Arr::get($data, 'discounted_price'), []), 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'), []), priceKgTtc: new MoneyCast()->get($model, 'price_kg_ttc', Arr::get($data, 'price_kg_ttc'), []),
taxRate: TaxRate::fromPercent($taxRate), taxRate: TaxRate::fromPercent($taxRate),
picture: is_string($picture = Arr::get($data, 'picture')) ? new StorageFilePath($picture) : null, picture: is_string($picture = Arr::get($data, 'picture')) ? $picture : null,
); );
} }
@ -97,7 +99,7 @@ class OrderLineProductCast implements CastsAttributes
[] []
), ),
'tax_rate' => $value->taxRate->percent(), 'tax_rate' => $value->taxRate->percent(),
'picture' => $value->picture?->value, 'picture' => $value->picture,
], \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES); ], \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES);
} }
} }

View file

@ -1,59 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Date;
/**
* Enforces UTC normalization when writing and reading datetime/timestamp attributes.
*
* @implements CastsAttributes<\Illuminate\Support\Carbon, \DateTimeInterface | string | int | null>
*/
class UtcDatetimeCast implements CastsAttributes
{
public bool $withoutObjectCaching = true;
/** @param array<string, mixed> $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<string, mixed> $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.');
}
}

View file

@ -7,7 +7,6 @@ namespace App\Console\Commands;
use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Validator;
@ -25,7 +24,7 @@ class MailTest extends Command
'email' => ['required', 'email:rfc,strict'], 'email' => ['required', 'email:rfc,strict'],
])->validate(); ])->validate();
Mail::raw('This is a test mail', function (Message $message): void { Mail::raw('This is a test mail', function ($message): void {
$message->to($this->argument('email')); $message->to($this->argument('email'));
$message->subject('Test mail'); $message->subject('Test mail');
}); });

View file

@ -15,27 +15,22 @@ class UpsertPublicHolydaysOnShopsPickupExceptions extends Command
{ {
/** /**
* Execute the console command. * Execute the console command.
*
* @return void
*/ */
public function handle(): int public function handle()
{ {
$year = $this->argument('year'); $year = $this->argument('year');
if ($year !== null && is_numeric($year) === false) { if (is_numeric($year) === false) {
$this->error('The year must be a number'); $this->error('The year must be a number');
return self::FAILURE; return;
} }
$this->info('Fetching hollidays upsert shops exceptions using Api'); $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'); $this->info('Done');
return self::SUCCESS;
} }
} }

View file

@ -4,17 +4,15 @@ declare(strict_types=1);
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Contracts\Executor; use App\Models\User;
use App\Cqs\Actions\Users\CreateUser;
use App\Cqs\Actions\Users\CreateUserInput;
use Domain\Enums\UserRole; use Domain\Enums\UserRole;
use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password; use Illuminate\Validation\Rules\Password;
use Webmozart\Assert\Assert;
#[Description('creates an admin user upon password entry')] #[Description('creates an admin user upon password entry')]
#[Signature('uwil:user:create')] #[Signature('uwil:user:create')]
@ -23,7 +21,7 @@ class UserCreate extends Command
/** /**
* Execute the console command. * Execute the console command.
*/ */
public function handle(Executor $executor, CreateUser $action): int public function handle(): int
{ {
$firstname = $this->askString('What is the firstname?', 'Equipe'); $firstname = $this->askString('What is the firstname?', 'Equipe');
$lastname = $this->askString('What is the lastname?', 'Web'); $lastname = $this->askString('What is the lastname?', 'Web');
@ -31,13 +29,14 @@ class UserCreate extends Command
$pwd = $this->askPassword('What is the password?'); $pwd = $this->askPassword('What is the password?');
$role = $this->askRole(); $role = $this->askRole();
$executor->execute($action, new CreateUserInput( $user = new User();
firstname: $firstname, $user->firstname = $firstname;
lastname: $lastname, $user->lastname = $lastname;
email: $email, $user->email = $email;
password: $pwd, $user->password = Hash::make($pwd);
role: $role, $user->email_verified_at = now();
)); $user->role = $role;
$user->save();
$this->info('User created.'); $this->info('User created.');
@ -120,9 +119,6 @@ class UserCreate extends Command
multiple: false multiple: false
) )
); );
Assert::string($response[0]);
$role = UserRole::tryFrom( $role = UserRole::tryFrom(
intval(mb_strcut((string) $response[0], 0, 1)) intval(mb_strcut((string) $response[0], 0, 1))
); );

View file

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Contracts\Directories;
use App\Contracts\Directory;
use App\Models\Customer;
use Domain\Models\ValueObjects\Email;
use Ramsey\Uuid\UuidInterface;
/** @extends Directory<\Ramsey\Uuid\UuidInterface, \App\Models\Customer> */
interface CustomerDirectory extends Directory
{
public function find(UuidInterface $id): ?Customer;
public function getCustomerByEmail(Email $email): ?Customer;
}

View file

@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Contracts\Directories;
use App\Contracts\Directory;
use App\Models\Employee;
use Carbon\CarbonInterface;
/** @extends Directory<int, \App\Models\Employee> */
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;
}

View file

@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace App\Contracts\Directories;
use App\Contracts\Directory;
use App\Models\Customer;
use App\Models\Order;
use Carbon\CarbonInterface;
use Domain\Enums\OrderStatus;
use Illuminate\Contracts\Pagination\LengthAwarePaginator as PaginationLengthAwarePaginator;
use Illuminate\Support\Collection;
use Ramsey\Uuid\UuidInterface;
use Shared\Pagination\Pagination;
/** @extends Directory<\Ramsey\Uuid\UuidInterface, \App\Models\Order> */
interface OrderDirectory extends Directory
{
public function find(UuidInterface $id): ?Order;
/** @return \Illuminate\Pagination\LengthAwarePaginator<int,Order> */
public function getPaginatedOrdersOf(
Customer $customer,
Pagination $pagination,
bool $orderByDate = false
): PaginationLengthAwarePaginator;
public function findOf(Customer $customer, UuidInterface $id): ?Order;
/** @return Collection<int,Order>*/
public function getValidatedOrders(CarbonInterface $start, CarbonInterface $end): Collection;
/** @return Collection<int,Order> */
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;
}

View file

@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Contracts;
/**
* @template TEntity
* @template TId
*
* @method TEntity|null find(TId $id)
*/
interface Directory
{
}

View file

@ -1,16 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Contracts;
/**
* @template TInput of \App\Contracts\ActionInput
*/
interface HandlesFailure
{
/**
* @param TInput $input
*/
public function onFailure(ActionInput $input, \Throwable $exception): void;
}

View file

@ -1,18 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Contracts;
/**
* @template TInput of \App\Contracts\ActionInput
* @template TResult
*/
interface HandlesLockTimeout
{
/**
* @param TInput $input
* @return TResult
*/
public function onLockTimeout(ActionInput $input): mixed;
}

View file

@ -1,18 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Contracts;
/**
* @template TInput of \App\Contracts\ActionInput
* @template TResult
*/
interface HandlesSuccess
{
/**
* @param TInput $input
* @param TResult $result
*/
public function onSuccess(ActionInput $input, mixed $result): void;
}

View file

@ -1,16 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Contracts;
/**
* @template TInput of \App\Contracts\ActionInput
*/
interface ProvidesLockKey
{
/**
* @param TInput $input
*/
public function lockKey(ActionInput $input): string;
}

View file

@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace App\Contracts\Repositories;
use App\Contracts\Repository;
use App\Models\Employee;
use Domain\Models\ValueObjects\Code;
use Domain\Models\ValueObjects\Matricule;
use Illuminate\Support\Collection;
use Ramsey\Uuid\UuidInterface;
/**
* @extends Repository<Employee, UuidInterface>
*/
interface EmployeeRepository extends Repository
{
public function find(UuidInterface $id): ?Employee;
public function persist(Employee $employee): void;
public function delete(Employee $employee): void;
/** @return array<array-key, Employee> */
public function getAll(): array;
public function findByMatriculeAndCode(Matricule $matricule, Code $code): ?Employee;
public function findByMatricule(Matricule $matricule): ?Employee;
/**
* @param array<array-key, Matricule>|Collection<array-key, Matricule> $matricules
* @return array<int, Employee>
*/
public function getWhereMatriculeIn(array | Collection $matricules): array;
/**
* @param array<array-key, Matricule>|Collection<array-key, Matricule> $matricules
* @return array<string, Employee>
*/
public function getWithCustomerWhereMatriculeIn(array | Collection $matricules): array;
/**
* @param array<array-key, Matricule>|Collection<array-key, Matricule> $excludedMatricules
* @return array<int, Employee>
*/
public function getWithCustomerWhereMatriculeNotIn(array | Collection $excludedMatricules): array;
public function getMostRecentSyncDate(): ?\DateTimeInterface;
}

View file

@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Contracts\Repositories;
use App\Contracts\Repository;
use App\Models\Order;
use Carbon\CarbonInterface;
use Domain\Models\ValueObjects\Matricule;
use Ramsey\Uuid\UuidInterface;
/**
* @extends Repository<Order, UuidInterface>
*/
interface OrderRepository extends Repository
{
public function find(UuidInterface $id): ?Order;
public function persist(Order $order): void;
public function delete(Order $order): void;
/** @return array<array-key, Order> */
public function getAll(): array;
/** @return array<array-key, Order> */
public function getValidatedOrdersForPickupDay(CarbonInterface $pickupDay): array;
public function hasValidatedOrderForPickupDay(Matricule $matricule, CarbonInterface $pickupDay): bool;
/** @return array<array-key, Order> */
public function getOrdersWithLinesAndShopForPickupDay(CarbonInterface $pickupDay): array;
}

View file

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Contracts\Repositories;
use App\Contracts\Repository;
use App\Models\User;
/**
* @extends Repository<User, int>
*/
interface UserRepository extends Repository
{
public function find(int $id): ?User;
public function persist(User $user): void;
public function delete(User $user): void;
}

View file

@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Contracts;
/**
* @template TModel of \Illuminate\Database\Eloquent\Model
* @template TId of \Ramsey\Uuid\UuidInterface|int
*
* @method TModel|null find(TId $id)
* @method void persist(TModel $model)
* @method void delete(TModel $model)
*/
interface Repository
{
}

View file

@ -1,31 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Auth;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Contracts\ActionInputEmpty;
use App\Models\PasswordReset;
use Illuminate\Support\Facades\Date;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<\App\Contracts\ActionInputEmpty, void>
*/
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();
}
}

View file

@ -1,56 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Auth;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use Domain\Services\ShopperService;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Infrastructure\Adapters\Services\AppCustomerAuthService;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\Auth\ResetCustomerPasswordInput,
* \App\Cqs\Actions\Auth\ResetCustomerPasswordOutput
* >
*/
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)
);
}
}

View file

@ -1,20 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Auth;
use App\Contracts\ActionInput;
use App\Models\Customer;
use Webmozart\Assert\Assert;
final readonly class ResetCustomerPasswordInput implements ActionInput
{
public function __construct(
public Customer $customer,
#[\SensitiveParameter]
public string $password,
) {
Assert::stringNotEmpty($this->password);
}
}

View file

@ -1,40 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Auth;
use App\Enums\ResetCustomerPasswordStatus;
final readonly class ResetCustomerPasswordOutput
{
private function __construct(
public ResetCustomerPasswordStatus $status,
public bool $emailVerified = false,
public ?string $errorMessage = null,
) {
}
public static function success(bool $emailVerified): self
{
return new self(
status: ResetCustomerPasswordStatus::SUCCESS,
emailVerified: $emailVerified,
);
}
public static function notEmployed(): self
{
return new self(
status: ResetCustomerPasswordStatus::NOT_EMPLOYED,
);
}
public static function invalidPassword(string $errorMessage): self
{
return new self(
status: ResetCustomerPasswordStatus::INVALID_PASSWORD,
errorMessage: $errorMessage,
);
}
}

View file

@ -10,6 +10,7 @@ use App\Interfaces\ModelWithOrder;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use SortDirection;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
@ -28,7 +29,7 @@ final class ChangeModelOrder implements Action
Assert::isInstanceOf($input, ChangeModelOrderInput::class); Assert::isInstanceOf($input, ChangeModelOrderInput::class);
$model = $input->model; $model = $input->model;
$goUp = $input->direction === \SortDirection::Ascending; $goUp = $input->direction === SortDirection::Ascending;
$currentOrder = $model->getOrder(); $currentOrder = $model->getOrder();
$usesSoftDeletes = in_array(SoftDeletes::class, class_uses_recursive($model), true) $usesSoftDeletes = in_array(SoftDeletes::class, class_uses_recursive($model), true)
@ -43,7 +44,7 @@ final class ChangeModelOrder implements Action
/** @var (Model&ModelWithOrder)|null $adjacentModel */ /** @var (Model&ModelWithOrder)|null $adjacentModel */
$adjacentModel = $baseQuery $adjacentModel = $baseQuery
->where('order', $goUp ? '<' : '>', $currentOrder) ->where('order', $goUp ? '<' : '>', $currentOrder)
->orderBy('order', $goUp ? \SortDirection::Descending : \SortDirection::Ascending) ->orderBy('order', $goUp ? SortDirection::Descending : SortDirection::Ascending)
->first(); ->first();
if ($adjacentModel === null) { if ($adjacentModel === null) {

View file

@ -7,12 +7,16 @@ namespace App\Cqs\Actions\Common;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Interfaces\ModelWithOrder; use App\Interfaces\ModelWithOrder;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use SortDirection;
use Webmozart\Assert\Assert;
final readonly class ChangeModelOrderInput implements ActionInput final readonly class ChangeModelOrderInput implements ActionInput
{ {
public function __construct( public function __construct(
public Model & ModelWithOrder $model, public Model & ModelWithOrder $model,
public \SortDirection $direction, public SortDirection $direction,
) { ) {
Assert::isInstanceOf($this->model, Model::class);
Assert::isInstanceOf($this->model, ModelWithOrder::class);
} }
} }

View file

@ -15,6 +15,8 @@ final readonly class ChangeModelOrderPositionInput implements ActionInput
public Model & ModelWithOrder $model, public Model & ModelWithOrder $model,
public int $targetOrder, public int $targetOrder,
) { ) {
Assert::isInstanceOf($this->model, Model::class);
Assert::isInstanceOf($this->model, ModelWithOrder::class);
Assert::greaterThanEq($this->targetOrder, 1); Assert::greaterThanEq($this->targetOrder, 1);
} }
} }

View file

@ -45,7 +45,7 @@ final class ExecuteMassAction implements Action
break; break;
default: default:
throw new \UnexpectedValueException('Unsupported mass action type: ' . gettype($input->action->value)); throw new \UnexpectedValueException('Unsupported mass action type: ' . $input->action->value);
} }
} }
@ -88,7 +88,7 @@ final class ExecuteMassAction implements Action
break; break;
default: default:
throw new \UnexpectedValueException('Unsupported mass action type: ' . gettype($input->action->value)); throw new \UnexpectedValueException('Unsupported mass action type: ' . $input->action->value);
} }
$foundModel->saveOrFail(); $foundModel->saveOrFail();

View file

@ -7,11 +7,14 @@ namespace App\Cqs\Actions\Common;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Interfaces\ModelWithStar; use App\Interfaces\ModelWithStar;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Webmozart\Assert\Assert;
final readonly class ToggleModelStarInput implements ActionInput final readonly class ToggleModelStarInput implements ActionInput
{ {
public function __construct( public function __construct(
public Model & ModelWithStar $model, public Model & ModelWithStar $model,
) { ) {
Assert::isInstanceOf($this->model, Model::class);
Assert::isInstanceOf($this->model, ModelWithStar::class);
} }
} }

View file

@ -7,11 +7,14 @@ namespace App\Cqs\Actions\Common;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Interfaces\ModelWithStatus; use App\Interfaces\ModelWithStatus;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Webmozart\Assert\Assert;
final readonly class ToggleModelStatusInput implements ActionInput final readonly class ToggleModelStatusInput implements ActionInput
{ {
public function __construct( public function __construct(
public Model & ModelWithStatus $model, public Model & ModelWithStatus $model,
) { ) {
Assert::isInstanceOf($this->model, Model::class);
Assert::isInstanceOf($this->model, ModelWithStatus::class);
} }
} }

View file

@ -1,86 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Contact;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesSuccess;
use App\Lib\PrivateS3Disk;
use App\Traits\TracksPendingStoragePaths;
use Domain\Models\ValueObjects\AttachedFile;
use Domain\Models\ValueObjects\ContactFormData;
use Illuminate\Http\UploadedFile;
use Uwil\Storage\Contracts\StorageService;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\Contact\SubmitContactFormInput,
* \Domain\Models\ValueObjects\ContactFormData
* >
* @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);
}
}
}
}

View file

@ -1,29 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Contact;
use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\OrderReference;
use Illuminate\Http\UploadedFile;
use Webmozart\Assert\Assert;
final readonly class SubmitContactFormInput implements ActionInput
{
public function __construct(
public string $lastName,
public string $firstName,
public string $email,
public string $subject,
public string $message,
public ?OrderReference $orderRef = null,
public ?UploadedFile $file = null,
) {
Assert::stringNotEmpty(trim($this->lastName));
Assert::stringNotEmpty(trim($this->firstName));
Assert::stringNotEmpty(trim($this->email));
Assert::stringNotEmpty(trim($this->subject));
Assert::stringNotEmpty(trim($this->message));
}
}

View file

@ -4,78 +4,34 @@ declare(strict_types=1);
namespace App\Cqs\Actions\Customers; namespace App\Cqs\Actions\Customers;
use App\Attributes\Locked;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure; use App\Contracts\Repositories\EmployeeRepository;
use App\Contracts\HandlesLockTimeout;
use App\Contracts\HandlesSuccess;
use App\Contracts\ProvidesLockKey;
use App\Enums\RegisterCustomerStatus;
use App\Exceptions\Crm\CrmCustomerExistsException; use App\Exceptions\Crm\CrmCustomerExistsException;
use App\Exceptions\CrmServiceException; use App\Exceptions\CrmServiceException;
use App\Models\Customer; use App\Models\Customer;
use App\Models\Employee;
use App\Services\CrmService; use App\Services\CrmService;
use Domain\Enums\Country; use Domain\Enums\Country;
use Domain\Models\ValueObjects\CrmCustomer; use Domain\Models\ValueObjects\CrmCustomer;
use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use Infrastructure\Adapters\Services\AppCustomerAuthService; use Infrastructure\Adapters\Services\AppCustomerAuthService;
use Shared\Helpers\UuidHelper; use Ramsey\Uuid\Uuid;
use Shared\ValueObjects\CrmHashcode; use Shared\ValueObjects\CrmHashcode;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action< * @implements \App\Contracts\Action<\App\Cqs\Actions\Customers\RegisterCustomerInput, \App\Models\Customer>
* \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>
*/ */
#[Locked(ttlSeconds: 30, waitSeconds: 10)] final class RegisterCustomer implements Action
final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeout, HandlesSuccess, ProvidesLockKey
{ {
/** @var array<int, array{hashcode: \Shared\ValueObjects\CrmHashcode, email: \Domain\Models\ValueObjects\Email}> */
private array $createdCrmCustomers = [];
public function __construct( public function __construct(
private readonly AppCustomerAuthService $authService, private readonly AppCustomerAuthService $authService,
private readonly CrmService $crmService, 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 * @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
* *
@ -84,39 +40,27 @@ final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeo
* @throws ModelNotFoundException * @throws ModelNotFoundException
*/ */
#[\Override] #[\Override]
public function __invoke(ActionInput $input): RegisterCustomerOutput public function __invoke(ActionInput $input): Customer
{ {
Assert::isInstanceOf($input, RegisterCustomerInput::class); 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 // * Persist and associate Customer + Employee
$customer = new Customer([ $customer = new Customer([
'email' => $input->email, 'email' => $input->email,
]); ]);
// * Temp hashcode to satisfy constraint // * Temp hashcode to satisfy constraint
$customer->hashcode = new CrmHashcode(UuidHelper::v4()); $customer->hashcode = new CrmHashcode(Uuid::uuid4());
$customer->saveOrFail(); $customer->saveOrFail();
$employee = $this->employeeRepository->findByMatriculeAndCode(
$input->matricule,
$input->code
);
if (! $employee) {
throw new ModelNotFoundException('Employee not found');
}
$employee->customer()->associate($customer); $employee->customer()->associate($customer);
$employee->saveOrFail(); $employee->saveOrFail();
@ -140,6 +84,21 @@ final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeo
try { try {
$result = $this->crmService->persist($crmCustomer); $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) { } catch (CrmCustomerExistsException) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'error' => trans('An account is already associated with this email address'), 'error' => trans('An account is already associated with this email address'),
@ -150,70 +109,5 @@ final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeo
'error' => trans('An error has occurred. Please try again later'), '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);
}
} }
} }

View file

@ -1,47 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Customers;
use App\Enums\RegisterCustomerStatus;
use App\Models\Customer;
final readonly class RegisterCustomerOutput
{
private function __construct(
public RegisterCustomerStatus $status,
public ?Customer $customer = null,
public ?string $errorMessage = null,
) {
}
public static function success(Customer $customer): self
{
return new self(
status: RegisterCustomerStatus::SUCCESS,
customer: $customer,
);
}
public static function employeeAlreadyRegistered(): self
{
return new self(
status: RegisterCustomerStatus::EMPLOYEE_ALREADY_REGISTERED,
);
}
public static function employeeInactive(): self
{
return new self(
status: RegisterCustomerStatus::EMPLOYEE_INACTIVE,
);
}
public static function lockTimeout(): self
{
return new self(
status: RegisterCustomerStatus::LOCK_TIMEOUT,
);
}
}

View file

@ -1,35 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Customers;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Models\Customer;
use Illuminate\Support\Facades\Date;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\Customers\UpdateCustomerLastLoginInput,
* \App\Models\Customer
* >
*/
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;
}
}

View file

@ -1,16 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Customers;
use App\Contracts\ActionInput;
use App\Models\Customer;
final readonly class UpdateCustomerLastLoginInput implements ActionInput
{
public function __construct(
public Customer $customer,
) {
}
}

View file

@ -4,30 +4,31 @@ declare(strict_types=1);
namespace App\Cqs\Actions\Employee; namespace App\Cqs\Actions\Employee;
use App\Attributes\WithoutTransaction;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Contracts\ActionInputEmpty; use App\Contracts\ActionInputEmpty;
use App\Contracts\Repositories\EmployeeRepository;
use App\Services\EmployeeSyncService; use App\Services\EmployeeSyncService;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Contracts\ActionInputEmpty, void> * @implements \App\Contracts\Action<\App\Contracts\ActionInputEmpty, void>
*/ */
#[WithoutTransaction]
final class SynchronizeEmployeesWithArcadiaApi implements Action final class SynchronizeEmployeesWithArcadiaApi implements Action
{ {
public function __construct( public function __construct(
private readonly EmployeeRepository $employeeRepository,
private readonly EmployeeSyncService $syncService private readonly EmployeeSyncService $syncService
) { ) {
} }
/** @param \App\Contracts\ActionInputEmpty $input */ /** @param \App\Contracts\ActionInputEmpty $input */
#[\Override]
public function __invoke(ActionInput $input): void public function __invoke(ActionInput $input): void
{ {
Assert::isAOf($input, ActionInputEmpty::class); Assert::isAOf($input, ActionInputEmpty::class);
$this->syncService->synchronize(); $wasLastSyncedAt = $this->employeeRepository->getMostRecentSyncDate();
$this->syncService->synchronize($wasLastSyncedAt);
} }
} }

View file

@ -6,14 +6,12 @@ namespace App\Cqs\Actions\Orders;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\PickupTimeSlot;
use Domain\Services\OrderTunnelService; use Domain\Services\OrderTunnelService;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action< * @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\ApplyPickTimeSlotInput, ?\Domain\Models\ValueObjects\PickupTimeSlot>
* \App\Cqs\Actions\Orders\ApplyPickTimeSlotInput,
* \App\Cqs\Actions\Orders\ApplyPickTimeSlotOutput
* >
*/ */
final class ApplyPickTimeSlot implements Action final class ApplyPickTimeSlot implements Action
{ {
@ -26,7 +24,7 @@ final class ApplyPickTimeSlot implements Action
* @param \App\Cqs\Actions\Orders\ApplyPickTimeSlotInput $input * @param \App\Cqs\Actions\Orders\ApplyPickTimeSlotInput $input
*/ */
#[\Override] #[\Override]
public function __invoke(ActionInput $input): ApplyPickTimeSlotOutput public function __invoke(ActionInput $input): ?PickupTimeSlot
{ {
Assert::isInstanceOf($input, ApplyPickTimeSlotInput::class); Assert::isInstanceOf($input, ApplyPickTimeSlotInput::class);
@ -34,15 +32,11 @@ final class ApplyPickTimeSlot implements Action
$shop = $this->orderTunnelService->getShopForCustomer($input->shopperId); $shop = $this->orderTunnelService->getShopForCustomer($input->shopperId);
$timeSlots = $this->orderTunnelService->getAvailableTimeSlots($shop); $timeSlots = $this->orderTunnelService->getAvailableTimeSlots($shop);
$timeSlot = $this->orderTunnelService->applyTimeSlot( return $this->orderTunnelService->applyTimeSlot(
$builder, $builder,
$shop, $shop,
$input->timeslot, $input->timeslot,
$timeSlots $timeSlots
); );
return $timeSlot !== null
? ApplyPickTimeSlotOutput::matched($timeSlot)
: ApplyPickTimeSlotOutput::unavailable();
} }
} }

View file

@ -1,32 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Enums\ApplyPickTimeSlotStatus;
use Domain\Models\ValueObjects\PickupTimeSlot;
final readonly class ApplyPickTimeSlotOutput
{
public function __construct(
public ApplyPickTimeSlotStatus $status,
public ?PickupTimeSlot $timeSlot = null,
) {
}
public static function matched(PickupTimeSlot $timeSlot): self
{
return new self(
status: ApplyPickTimeSlotStatus::MATCHED,
timeSlot: $timeSlot,
);
}
public static function unavailable(): self
{
return new self(
status: ApplyPickTimeSlotStatus::UNAVAILABLE,
);
}
}

View file

@ -6,16 +6,16 @@ namespace App\Cqs\Actions\Orders;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use Domain\Services\OrderService; use Domain\Services\OrderService as DomainOrderService;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\CancelOrderInput, \App\Cqs\Actions\Orders\CancelOrderOutput> * @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\CancelOrderInput, void>
*/ */
final class CancelOrder implements Action final class CancelOrder implements Action
{ {
public function __construct( public function __construct(
private readonly OrderService $orderService, private readonly DomainOrderService $domainOrderService,
) { ) {
} }
@ -23,16 +23,10 @@ final class CancelOrder implements Action
* @param \App\Cqs\Actions\Orders\CancelOrderInput $input * @param \App\Cqs\Actions\Orders\CancelOrderInput $input
*/ */
#[\Override] #[\Override]
public function __invoke(ActionInput $input): CancelOrderOutput public function __invoke(ActionInput $input): void
{ {
Assert::isInstanceOf($input, CancelOrderInput::class); Assert::isInstanceOf($input, CancelOrderInput::class);
try { $this->domainOrderService->cancelOrder($input->order->getId());
$this->orderService->cancelOrder($input->order->getId());
} catch (\DomainException) {
return CancelOrderOutput::NOT_FOUND;
}
return CancelOrderOutput::CANCELLED;
} }
} }

View file

@ -1,11 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
enum CancelOrderOutput
{
case CANCELLED;
case NOT_FOUND;
}

View file

@ -1,34 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Models\Order;
use Domain\Enums\OrderStatus;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\ClaimTodayOrderReminderInput, bool>
*/
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;
}
}

View file

@ -1,18 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\ActionInput;
use Carbon\CarbonImmutable;
use Domain\Models\ValueObjects\Entities\OrderId;
final readonly class ClaimTodayOrderReminderInput implements ActionInput
{
public function __construct(
public OrderId $orderId,
public CarbonImmutable $remindedAt,
) {
}
}

View file

@ -1,43 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use Domain\Services\OrderTunnelService;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\Orders\ConfirmPlacedOrderInput,
* \App\Cqs\Actions\Orders\ConfirmPlacedOrderOutput
* >
*/
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;
}
}

View file

@ -1,16 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\Entities\OrderId;
final readonly class ConfirmPlacedOrderInput implements ActionInput
{
public function __construct(
public OrderId $orderId,
) {
}
}

View file

@ -1,11 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
enum ConfirmPlacedOrderOutput
{
case CONFIRMED;
case FAILED;
}

View file

@ -1,77 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Attributes\Locked;
use App\Attributes\WithoutTransaction;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Contracts\HandlesLockTimeout;
use App\Contracts\ProvidesLockKey;
use Domain\Exceptions\OrderTunnel\RegateExportFailedException;
use Domain\Services\OrderTunnelService;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\Orders\ExportOrderToRegateInput,
* \App\Cqs\Actions\Orders\ExportOrderToRegateOutput
* >
* @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;
}
}

View file

@ -1,16 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\Entities\OrderId;
final readonly class ExportOrderToRegateInput implements ActionInput
{
public function __construct(
public OrderId $orderId,
) {
}
}

View file

@ -1,12 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
enum ExportOrderToRegateOutput
{
case SENT;
case FAILED;
case LOCK_TIMEOUT;
}

View file

@ -1,43 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use Domain\Services\OrderTunnelService;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\Orders\FailPendingOrderInput,
* \App\Cqs\Actions\Orders\FailPendingOrderOutput
* >
*/
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;
}
}

View file

@ -1,16 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\Entities\OrderId;
final readonly class FailPendingOrderInput implements ActionInput
{
public function __construct(
public OrderId $orderId,
) {
}
}

View file

@ -1,12 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
enum FailPendingOrderOutput
{
case FAILED;
case NOT_FOUND;
case INVALID_STATUS;
}

View file

@ -1,53 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use Domain\Ports\Repositories\OrderRepository;
use Domain\Services\OrderService;
use Illuminate\Support\Facades\Date;
use Psr\Log\LoggerInterface;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\FailStalePendingOrdersInput, int>
*/
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;
}
}

View file

@ -1,17 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\ActionInput;
use Webmozart\Assert\Assert;
final readonly class FailStalePendingOrdersInput implements ActionInput
{
public function __construct(
public int $ttlMinutes = 10,
) {
Assert::greaterThan($this->ttlMinutes, 0);
}
}

View file

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Services\OrderTunnelService;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\FinalizeOrderInput, \Domain\Models\ValueObjects\OrderReference>
*/
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;
}
}

View file

@ -7,7 +7,7 @@ namespace App\Cqs\Actions\Orders;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Models\ValueObjects\Entities\ShopperId;
final readonly class PlacePendingOrderInput implements ActionInput final readonly class FinalizeOrderInput implements ActionInput
{ {
public function __construct( public function __construct(
public ?ShopperId $shopperId = null, public ?ShopperId $shopperId = null,

View file

@ -1,100 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Attributes\Locked;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Contracts\HandlesLockTimeout;
use App\Contracts\ProvidesLockKey;
use Domain\Exceptions\OrderTunnel\BasketPriceChangedException;
use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException;
use Domain\Exceptions\OrderTunnel\InactiveShopperException;
use Domain\Exceptions\OrderTunnel\OrderLimitExceededException;
use Domain\Exceptions\OrderTunnel\UnorderableProductException;
use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException;
use Domain\Ports\Repositories\BasketRepository;
use Domain\Services\OrderTunnelService;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\Orders\PlacePendingOrderInput,
* \App\Cqs\Actions\Orders\PlacePendingOrderOutput
* >
* @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);
}
}

View file

@ -1,84 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Enums\PlacePendingOrderStatus;
use Domain\Models\ValueObjects\Entities\OrderId;
use Domain\Models\ValueObjects\OrderReference;
final readonly class PlacePendingOrderOutput
{
private function __construct(
public PlacePendingOrderStatus $status,
public ?OrderId $orderId = null,
public ?OrderReference $orderReference = null,
public ?string $errorMessage = null,
) {
}
public static function pendingCreated(OrderId $orderId, OrderReference $orderReference): self
{
return new self(
status: PlacePendingOrderStatus::PENDING_CREATED,
orderId: $orderId,
orderReference: $orderReference,
);
}
public static function expiredTimeSlot(string $errorMessage): self
{
return new self(
status: PlacePendingOrderStatus::EXPIRED_TIME_SLOT,
errorMessage: $errorMessage,
);
}
public static function inactiveShopper(string $errorMessage): self
{
return new self(
status: PlacePendingOrderStatus::INACTIVE_SHOPPER,
errorMessage: $errorMessage,
);
}
public static function unorderableProduct(string $errorMessage): self
{
return new self(
status: PlacePendingOrderStatus::UNORDERABLE_PRODUCT,
errorMessage: $errorMessage,
);
}
public static function basketPriceChanged(string $errorMessage): self
{
return new self(
status: PlacePendingOrderStatus::BASKET_PRICE_CHANGED,
errorMessage: $errorMessage,
);
}
public static function orderLimitExceeded(string $errorMessage): self
{
return new self(
status: PlacePendingOrderStatus::ORDER_LIMIT_EXCEEDED,
errorMessage: $errorMessage,
);
}
public static function weeklyLimitExceeded(string $errorMessage): self
{
return new self(
status: PlacePendingOrderStatus::WEEKLY_LIMIT_EXCEEDED,
errorMessage: $errorMessage,
);
}
public static function lockTimeout(): self
{
return new self(
status: PlacePendingOrderStatus::LOCK_TIMEOUT,
);
}
}

View file

@ -1,32 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Models\Order;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\ReleaseTodayOrderReminderInput, bool>
*/
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;
}
}

View file

@ -1,18 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\ActionInput;
use Carbon\CarbonImmutable;
use Domain\Models\ValueObjects\Entities\OrderId;
final readonly class ReleaseTodayOrderReminderInput implements ActionInput
{
public function __construct(
public OrderId $orderId,
public CarbonImmutable $remindedAt,
) {
}
}

View file

@ -1,62 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\PickupExceptions;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Dto\PublicHolidayDto;
use App\Models\PickupException;
use App\Models\Shop;
use Domain\Enums\RepeatFrequency;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\PickupExceptions\UpsertShopsPickupExceptionsForYearInput,
* void
* >
*/
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));
}
}

View file

@ -1,23 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\PickupExceptions;
use App\Contracts\ActionInput;
use App\Dto\PublicHolidayDto;
use Webmozart\Assert\Assert;
final readonly class UpsertShopsPickupExceptionsForYearInput implements ActionInput
{
/**
* @param list<PublicHolidayDto> $holidays
*/
public function __construct(
public int $year,
public array $holidays,
) {
Assert::greaterThanEq($this->year, 2026);
Assert::allIsInstanceOf($this->holidays, PublicHolidayDto::class);
}
}

View file

@ -11,10 +11,7 @@ use App\Services\ArcadiaIncoService;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action< * @implements \App\Contracts\Action<\App\Cqs\Actions\ProductIncos\AssociateProductIncoInput, \App\Models\ProductInco>
* \App\Cqs\Actions\ProductIncos\AssociateProductIncoInput,
* \App\Cqs\Actions\ProductIncos\AssociateProductIncoOutput
* >
*/ */
final class AssociateProductInco implements Action final class AssociateProductInco implements Action
{ {
@ -27,34 +24,36 @@ final class AssociateProductInco implements Action
* @param \App\Cqs\Actions\ProductIncos\AssociateProductIncoInput $input * @param \App\Cqs\Actions\ProductIncos\AssociateProductIncoInput $input
*/ */
#[\Override] #[\Override]
public function __invoke(ActionInput $input): AssociateProductIncoOutput public function __invoke(ActionInput $input): ProductInco
{ {
Assert::isInstanceOf($input, AssociateProductIncoInput::class); Assert::isInstanceOf($input, AssociateProductIncoInput::class);
try { $incoData = $this->arcadiaIncoService->fetchInco($input->no_art);
$incoData = $this->arcadiaIncoService->fetchInco($input->no_art);
} catch (\RuntimeException $e) {
return AssociateProductIncoOutput::apiError($e->getMessage());
}
if ($incoData === null) { if ($incoData === null) {
return AssociateProductIncoOutput::notFoundOnArcadia($input->no_art); throw new \RuntimeException(sprintf('INCO sheet #%d was not found on Arcadia API.', $input->no_art));
} }
$productId = $input->productId->value->toString();
// * Remove existing product_inco for this product if present // * Remove existing product_inco for this product if present
$existing = ProductInco::query()->where('product_id', $productId)->first(); $existing = ProductInco::query()->where('product_id', $input->product->id)->first();
if ($existing !== null) { if ($existing !== null) {
$existing->delete(); $existing->delete();
} }
$inco = new ProductInco(); $inco = new ProductInco();
$inco->product_id = $productId; $inco->product_id = (string) $input->product->id;
$inco->no_art = $incoData->noArt; $inco->no_art = $incoData->noArt;
$inco->hydrateFromArcadiaDto($incoData); $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(); $inco->saveOrFail();
return AssociateProductIncoOutput::success($inco); return $inco;
} }
} }

View file

@ -5,13 +5,13 @@ declare(strict_types=1);
namespace App\Cqs\Actions\ProductIncos; namespace App\Cqs\Actions\ProductIncos;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\Entities\ProductId; use App\Models\Product;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
final readonly class AssociateProductIncoInput implements ActionInput final readonly class AssociateProductIncoInput implements ActionInput
{ {
public function __construct( public function __construct(
public ProductId $productId, public Product $product,
public int $no_art, public int $no_art,
) { ) {
Assert::greaterThanEq($this->no_art, 1, 'The INCO article number must be greater than or equal to 1.'); Assert::greaterThanEq($this->no_art, 1, 'The INCO article number must be greater than or equal to 1.');

View file

@ -1,42 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\ProductIncos;
use App\Enums\ProductIncoSyncStatus;
use App\Models\ProductInco;
final readonly class AssociateProductIncoOutput
{
public function __construct(
public ProductIncoSyncStatus $status,
public ?ProductInco $inco = null,
public ?string $errorMessage = null,
) {
}
public static function success(ProductInco $inco): self
{
return new self(
status: ProductIncoSyncStatus::SUCCESS,
inco: $inco,
);
}
public static function notFoundOnArcadia(int $noArt): self
{
return new self(
status: ProductIncoSyncStatus::NOT_FOUND_ON_ARCADIA,
errorMessage: sprintf('INCO sheet #%d was not found on Arcadia API.', $noArt),
);
}
public static function apiError(string $errorMessage): self
{
return new self(
status: ProductIncoSyncStatus::API_ERROR,
errorMessage: $errorMessage,
);
}
}

View file

@ -11,10 +11,7 @@ use App\Services\ArcadiaIncoService;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action< * @implements \App\Contracts\Action<\App\Cqs\Actions\ProductIncos\SyncProductIncoInput, \App\Models\ProductInco>
* \App\Cqs\Actions\ProductIncos\SyncProductIncoInput,
* \App\Cqs\Actions\ProductIncos\SyncProductIncoOutput
* >
*/ */
final class SyncProductInco implements Action final class SyncProductInco implements Action
{ {
@ -27,31 +24,31 @@ final class SyncProductInco implements Action
* @param \App\Cqs\Actions\ProductIncos\SyncProductIncoInput $input * @param \App\Cqs\Actions\ProductIncos\SyncProductIncoInput $input
*/ */
#[\Override] #[\Override]
public function __invoke(ActionInput $input): SyncProductIncoOutput public function __invoke(ActionInput $input): ProductInco
{ {
Assert::isInstanceOf($input, SyncProductIncoInput::class); Assert::isInstanceOf($input, SyncProductIncoInput::class);
$inco = ProductInco::query() $inco = $input->product->inco;
->where('product_id', $input->productId->value->toString())
->first();
if ($inco === null) { if ($inco === null) {
return SyncProductIncoOutput::notAssociated(); throw new \RuntimeException('Product does not have an associated INCO sheet to sync.');
}
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) { if ($incoData === null) {
return SyncProductIncoOutput::notFoundOnArcadia($inco->no_art); throw new \RuntimeException(sprintf('INCO sheet #%d was not found on Arcadia API.', $inco->no_art));
} }
$inco->hydrateFromArcadiaDto($incoData); $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(); $inco->saveOrFail();
return SyncProductIncoOutput::success($inco); return $inco;
} }
} }

View file

@ -5,12 +5,12 @@ declare(strict_types=1);
namespace App\Cqs\Actions\ProductIncos; namespace App\Cqs\Actions\ProductIncos;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\Entities\ProductId; use App\Models\Product;
final readonly class SyncProductIncoInput implements ActionInput final readonly class SyncProductIncoInput implements ActionInput
{ {
public function __construct( public function __construct(
public ProductId $productId, public Product $product,
) { ) {
} }
} }

View file

@ -1,50 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\ProductIncos;
use App\Enums\ProductIncoSyncStatus;
use App\Models\ProductInco;
final readonly class SyncProductIncoOutput
{
public function __construct(
public ProductIncoSyncStatus $status,
public ?ProductInco $inco = null,
public ?string $errorMessage = null,
) {
}
public static function success(ProductInco $inco): self
{
return new self(
status: ProductIncoSyncStatus::SUCCESS,
inco: $inco,
);
}
public static function notAssociated(): self
{
return new self(
status: ProductIncoSyncStatus::NOT_ASSOCIATED,
errorMessage: 'Product does not have an associated INCO sheet to sync.',
);
}
public static function notFoundOnArcadia(int $noArt): self
{
return new self(
status: ProductIncoSyncStatus::NOT_FOUND_ON_ARCADIA,
errorMessage: sprintf('INCO sheet #%d was not found on Arcadia API.', $noArt),
);
}
public static function apiError(string $errorMessage): self
{
return new self(
status: ProductIncoSyncStatus::API_ERROR,
errorMessage: $errorMessage,
);
}
}

View file

@ -4,20 +4,17 @@ declare(strict_types=1);
namespace App\Cqs\Actions\ProductIncos; namespace App\Cqs\Actions\ProductIncos;
use App\Attributes\WithoutTransaction;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Contracts\ActionInputEmpty; use App\Contracts\ActionInputEmpty;
use App\Models\ProductInco; use App\Models\ProductInco;
use App\Services\ArcadiaIncoService; use App\Services\ArcadiaIncoService;
use Illuminate\Support\Facades\DB;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Contracts\ActionInputEmpty, int> * @implements \App\Contracts\Action<\App\Contracts\ActionInputEmpty, int>
*/ */
#[WithoutTransaction]
final class SynchronizeProductIncosWithArcadiaApi implements Action final class SynchronizeProductIncosWithArcadiaApi implements Action
{ {
public function __construct( public function __construct(
@ -41,20 +38,7 @@ final class SynchronizeProductIncosWithArcadiaApi implements Action
$incos = ProductInco::query()->get(); $incos = ProductInco::query()->get();
foreach ($incos as $inco) { foreach ($incos as $inco) {
try { $incoData = $this->arcadiaIncoService->fetchInco($inco->no_art);
$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) { if ($incoData === null) {
$this->logger->warning("Could not sync ProductInco #{$inco->id} (no_art: {$inco->no_art}): not found on Arcadia."); $this->logger->warning("Could not sync ProductInco #{$inco->id} (no_art: {$inco->no_art}): not found on Arcadia.");
@ -62,10 +46,16 @@ final class SynchronizeProductIncosWithArcadiaApi implements Action
continue; continue;
} }
DB::transaction(static function () use ($inco, $incoData): void { $inco->ingredients = $incoData->ingredients;
$inco->hydrateFromArcadiaDto($incoData); $inco->preparation = $incoData->preparation;
$inco->saveOrFail(); $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();
$updatedCount++; $updatedCount++;
} }

View file

@ -6,36 +6,17 @@ namespace App\Cqs\Actions\Products;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesSuccess;
use App\Lib\PublicS3Disk;
use App\Models\Product; use App\Models\Product;
use App\Models\Tag; use App\Models\Tag;
use App\Services\ImageOptimizerService;
use App\Traits\TracksPendingStoragePaths;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Uwil\Storage\Contracts\StorageService;
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Products\CreateProductInput, \App\Models\Product> * @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, HandlesFailure, HandlesSuccess final class CreateProduct implements Action
{ {
use TracksPendingStoragePaths;
public function __construct(
protected readonly StorageService $storageService,
protected readonly PublicS3Disk $s3Disk,
protected readonly ImageOptimizerService $imageOptimizerService,
) {
}
/** /**
* @param \App\Cqs\Actions\Products\CreateProductInput $input * @param \App\Cqs\Actions\Products\CreateProductInput $input
*/ */
@ -63,18 +44,14 @@ final class CreateProduct implements Action, HandlesFailure, HandlesSuccess
$product->star = $input->star; $product->star = $input->star;
$product->status = $input->status; $product->status = $input->status;
if ($input->picture instanceof UploadedFile) { if ($input->picture !== null) {
$picturePath = $this->storeFile($input->picture); $product->setAttribute('picture', $input->picture);
$product->picture = $picturePath;
$this->trackUploadedPath($input, $picturePath);
} }
$product->picture_alt = (string) $input->pictureAlt; $product->picture_alt = (string) $input->pictureAlt;
$product->picture_title = (string) $input->pictureTitle; $product->picture_title = (string) $input->pictureTitle;
if ($input->pictureLarge instanceof UploadedFile) { if ($input->pictureLarge !== null) {
$pictureLargePath = $this->storeFile($input->pictureLarge); $product->setAttribute('picture_large', $input->pictureLarge);
$product->picture_large = $pictureLargePath;
$this->trackUploadedPath($input, $pictureLargePath);
} }
$product->picture_large_alt = (string) $input->pictureLargeAlt; $product->picture_large_alt = (string) $input->pictureLargeAlt;
$product->picture_large_title = (string) $input->pictureLargeTitle; $product->picture_large_title = (string) $input->pictureLargeTitle;
@ -129,27 +106,4 @@ final class CreateProduct implements Action, HandlesFailure, HandlesSuccess
$product->products()->sync($syncData); $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);
}
} }

View file

@ -11,7 +11,6 @@ use Domain\Enums\SellUnit;
use Domain\Enums\TaxRate; use Domain\Enums\TaxRate;
use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\InvoicingUnit;
use Domain\Enums\Units\OrderUnit; use Domain\Enums\Units\OrderUnit;
use Illuminate\Http\UploadedFile;
use Money\Money; use Money\Money;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
@ -39,10 +38,10 @@ final readonly class CreateProductInput implements ActionInput
public ?CarbonInterface $orderableEnd = null, public ?CarbonInterface $orderableEnd = null,
public bool $star = false, public bool $star = false,
public bool $status = false, public bool $status = false,
public ?UploadedFile $picture = null, public mixed $picture = null,
public ?string $pictureAlt = null, public ?string $pictureAlt = null,
public ?string $pictureTitle = null, public ?string $pictureTitle = null,
public ?UploadedFile $pictureLarge = null, public mixed $pictureLarge = null,
public ?string $pictureLargeAlt = null, public ?string $pictureLargeAlt = null,
public ?string $pictureLargeTitle = null, public ?string $pictureLargeTitle = null,
public array $tags = [], public array $tags = [],

View file

@ -6,7 +6,6 @@ namespace App\Cqs\Actions\Products;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Models\Product;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
@ -22,15 +21,6 @@ final class DeleteProduct implements Action
{ {
Assert::isInstanceOf($input, DeleteProductInput::class); Assert::isInstanceOf($input, DeleteProductInput::class);
$product = Product::query() return (bool) $input->product->deleteOrFail();
->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();
} }
} }

View file

@ -5,12 +5,12 @@ declare(strict_types=1);
namespace App\Cqs\Actions\Products; namespace App\Cqs\Actions\Products;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\Entities\ProductId; use App\Models\Product;
final readonly class DeleteProductInput implements ActionInput final readonly class DeleteProductInput implements ActionInput
{ {
public function __construct( public function __construct(
public ProductId $productId, public Product $product,
) { ) {
} }
} }

View file

@ -6,31 +6,17 @@ namespace App\Cqs\Actions\Products;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesSuccess;
use App\Models\Product; use App\Models\Product;
use App\Models\Tag; use App\Models\Tag;
use App\Services\PublicImageStorageService;
use App\Traits\TracksPendingStoragePaths;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Products\UpdateProductInput, \App\Models\Product> * @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, HandlesFailure, HandlesSuccess final class UpdateProduct implements Action
{ {
use TracksPendingStoragePaths;
public function __construct(
private readonly PublicImageStorageService $publicImageStorageService,
) {
}
/** /**
* @param \App\Cqs\Actions\Products\UpdateProductInput $input * @param \App\Cqs\Actions\Products\UpdateProductInput $input
*/ */
@ -39,13 +25,7 @@ final class UpdateProduct implements Action, HandlesFailure, HandlesSuccess
{ {
Assert::isInstanceOf($input, UpdateProductInput::class); Assert::isInstanceOf($input, UpdateProductInput::class);
$product = Product::query() $product = $input->product;
->where('id', $input->productId->value->toString())
->firstOrFail();
$previousPicture = $product->picture;
$previousPictureLarge = $product->picture_large;
$newPicture = null;
$newPictureLarge = null;
$product->name = $input->name; $product->name = $input->name;
$product->short_description = $input->shortDescription; $product->short_description = $input->shortDescription;
$product->description = $input->description; $product->description = $input->description;
@ -64,18 +44,14 @@ final class UpdateProduct implements Action, HandlesFailure, HandlesSuccess
$product->star = $input->star; $product->star = $input->star;
$product->status = $input->status; $product->status = $input->status;
if ($input->picture instanceof UploadedFile) { if ($input->picture !== null) {
$newPicture = $this->publicImageStorageService->store($input->picture); $product->setAttribute('picture', $input->picture);
$product->setAttribute('picture', $newPicture);
$this->trackUploadedPath($input, $newPicture);
} }
$product->picture_alt = (string) $input->pictureAlt; $product->picture_alt = (string) $input->pictureAlt;
$product->picture_title = (string) $input->pictureTitle; $product->picture_title = (string) $input->pictureTitle;
if ($input->pictureLarge instanceof UploadedFile) { if ($input->pictureLarge !== null) {
$newPictureLarge = $this->publicImageStorageService->store($input->pictureLarge); $product->setAttribute('picture_large', $input->pictureLarge);
$product->setAttribute('picture_large', $newPictureLarge);
$this->trackUploadedPath($input, $newPictureLarge);
} }
$product->picture_large_alt = (string) $input->pictureLargeAlt; $product->picture_large_alt = (string) $input->pictureLargeAlt;
$product->picture_large_title = (string) $input->pictureLargeTitle; $product->picture_large_title = (string) $input->pictureLargeTitle;
@ -85,28 +61,9 @@ final class UpdateProduct implements Action, HandlesFailure, HandlesSuccess
$this->syncTags($input->tags, $product); $this->syncTags($input->tags, $product);
$this->syncAssociatedProducts($input->associatedProductsIds, $product); $this->syncAssociatedProducts($input->associatedProductsIds, $product);
$this->trackReplacedPath($input, $previousPicture, $newPicture);
$this->trackReplacedPath($input, $previousPictureLarge, $newPictureLarge);
return $product; 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<array{id?: int|string, label: string}> $tags * @param array<array{id?: int|string, label: string}> $tags
*/ */

View file

@ -5,16 +5,14 @@ declare(strict_types=1);
namespace App\Cqs\Actions\Products; namespace App\Cqs\Actions\Products;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Models\Product;
use Carbon\CarbonInterface; use Carbon\CarbonInterface;
use Domain\Enums\ProductBrand; use Domain\Enums\ProductBrand;
use Domain\Enums\SellUnit; use Domain\Enums\SellUnit;
use Domain\Enums\TaxRate; use Domain\Enums\TaxRate;
use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\InvoicingUnit;
use Domain\Enums\Units\OrderUnit; use Domain\Enums\Units\OrderUnit;
use Domain\Models\ValueObjects\Entities\ProductId;
use Illuminate\Http\UploadedFile;
use Money\Money; use Money\Money;
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
final readonly class UpdateProductInput implements ActionInput final readonly class UpdateProductInput implements ActionInput
@ -24,7 +22,7 @@ final readonly class UpdateProductInput implements ActionInput
* @param list<string> $associatedProductsIds * @param list<string> $associatedProductsIds
*/ */
public function __construct( public function __construct(
public ProductId $productId, public Product $product,
public string $name, public string $name,
public string $shortDescription, public string $shortDescription,
public string $description, public string $description,
@ -42,10 +40,10 @@ final readonly class UpdateProductInput implements ActionInput
public ?CarbonInterface $orderableEnd = null, public ?CarbonInterface $orderableEnd = null,
public bool $star = false, public bool $star = false,
public bool $status = false, public bool $status = false,
public UploadedFile | StorageFilePath | null $picture = null, public mixed $picture = null,
public ?string $pictureAlt = null, public ?string $pictureAlt = null,
public ?string $pictureTitle = null, public ?string $pictureTitle = null,
public UploadedFile | StorageFilePath | null $pictureLarge = null, public mixed $pictureLarge = null,
public ?string $pictureLargeAlt = null, public ?string $pictureLargeAlt = null,
public ?string $pictureLargeTitle = null, public ?string $pictureLargeTitle = null,
public array $tags = [], public array $tags = [],

View file

@ -6,33 +6,14 @@ namespace App\Cqs\Actions\Ranges;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesSuccess;
use App\Lib\PublicS3Disk;
use App\Models\Range; 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; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Ranges\CreateRangeInput, \App\Models\Range> * @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, HandlesFailure, HandlesSuccess final class CreateRange implements Action
{ {
use TracksPendingStoragePaths;
public function __construct(
protected readonly StorageService $storageService,
protected readonly PublicS3Disk $s3Disk,
protected readonly ImageOptimizerService $imageOptimizerService,
) {
}
/** /**
* @param \App\Cqs\Actions\Ranges\CreateRangeInput $input * @param \App\Cqs\Actions\Ranges\CreateRangeInput $input
*/ */
@ -49,10 +30,8 @@ final class CreateRange implements Action, HandlesFailure, HandlesSuccess
'status' => $input->status, 'status' => $input->status,
]; ];
if ($input->picture instanceof UploadedFile) { if ($input->picture !== null) {
$storedPath = $this->storeFile($input->picture); $attributes['picture'] = $input->picture;
$attributes['picture'] = $storedPath;
$this->trackUploadedPath($input, $storedPath);
} }
$range = new Range(); $range = new Range();
@ -61,27 +40,4 @@ final class CreateRange implements Action, HandlesFailure, HandlesSuccess
return $range; 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);
}
} }

View file

@ -14,7 +14,7 @@ final readonly class CreateRangeInput implements ActionInput
public function __construct( public function __construct(
public string $name, public string $name,
public ?string $description, public ?string $description,
public ?UploadedFile $picture, public UploadedFile | string | null $picture,
public PictureMetadata $pictureMetadata, public PictureMetadata $pictureMetadata,
public bool $status, public bool $status,
) { ) {

View file

@ -6,28 +6,13 @@ namespace App\Cqs\Actions\Ranges;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; 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; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Ranges\DeleteRangeInput, bool> * @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, HandlesFailure, HandlesSuccess final class DeleteRange implements Action
{ {
use TracksPendingStoragePaths;
public function __construct(
protected readonly StorageService $storageService,
protected readonly PublicS3Disk $s3Disk,
) {
}
/** /**
* @param \App\Cqs\Actions\Ranges\DeleteRangeInput $input * @param \App\Cqs\Actions\Ranges\DeleteRangeInput $input
*/ */
@ -36,29 +21,6 @@ final class DeleteRange implements Action, HandlesFailure, HandlesSuccess
{ {
Assert::isInstanceOf($input, DeleteRangeInput::class); Assert::isInstanceOf($input, DeleteRangeInput::class);
$picture = $input->range->picture; return (bool) $input->range->deleteOrFail();
$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);
} }
} }

View file

@ -6,28 +6,14 @@ namespace App\Cqs\Actions\Ranges;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesSuccess;
use App\Models\Range; use App\Models\Range;
use App\Services\PublicImageStorageService;
use App\Traits\TracksPendingStoragePaths;
use Illuminate\Http\UploadedFile;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Ranges\UpdateRangeInput, \App\Models\Range> * @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, HandlesFailure, HandlesSuccess final class UpdateRange implements Action
{ {
use TracksPendingStoragePaths;
public function __construct(
private readonly PublicImageStorageService $publicImageStorageService,
) {
}
/** /**
* @param \App\Cqs\Actions\Ranges\UpdateRangeInput $input * @param \App\Cqs\Actions\Ranges\UpdateRangeInput $input
*/ */
@ -36,9 +22,6 @@ final class UpdateRange implements Action, HandlesFailure, HandlesSuccess
{ {
Assert::isInstanceOf($input, UpdateRangeInput::class); Assert::isInstanceOf($input, UpdateRangeInput::class);
$previousPicture = $input->range->picture;
$newPicture = null;
$attributes = [ $attributes = [
'name' => $input->name, 'name' => $input->name,
'description' => $input->description, 'description' => $input->description,
@ -47,34 +30,14 @@ final class UpdateRange implements Action, HandlesFailure, HandlesSuccess
'status' => $input->status, 'status' => $input->status,
]; ];
if ($input->picture instanceof UploadedFile) { if ($input->picture !== null) {
$newPicture = $this->publicImageStorageService->store($input->picture); $attributes['picture'] = $input->picture;
$attributes['picture'] = $newPicture;
$this->trackUploadedPath($input, $newPicture);
} }
$range = $input->range; $range = $input->range;
$range->fill($attributes); $range->fill($attributes);
$range->saveOrFail(); $range->saveOrFail();
$this->trackReplacedPath($input, $previousPicture, $newPicture);
return $range; 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);
}
}
} }

View file

@ -8,7 +8,6 @@ use App\Contracts\ActionInput;
use App\Models\Range; use App\Models\Range;
use Domain\Models\ValueObjects\PictureMetadata; use Domain\Models\ValueObjects\PictureMetadata;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
final readonly class UpdateRangeInput implements ActionInput final readonly class UpdateRangeInput implements ActionInput
@ -17,7 +16,7 @@ final readonly class UpdateRangeInput implements ActionInput
public Range $range, public Range $range,
public string $name, public string $name,
public ?string $description, public ?string $description,
public UploadedFile | StorageFilePath | null $picture, public UploadedFile | string | null $picture,
public PictureMetadata $pictureMetadata, public PictureMetadata $pictureMetadata,
public bool $status, public bool $status,
) { ) {

View file

@ -6,9 +6,7 @@ namespace App\Cqs\Actions\Shops;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Models\PickupException;
use App\Models\Shop; use App\Models\Shop;
use Illuminate\Support\Facades\Date;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
@ -39,15 +37,6 @@ final class CreateShop implements Action
$shop->default = $input->default; $shop->default = $input->default;
$shop->saveOrFail(); $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; return $shop;
} }
} }

View file

@ -6,34 +6,15 @@ namespace App\Cqs\Actions\Slides;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesSuccess;
use App\Lib\PublicS3Disk;
use App\Models\Slide; use App\Models\Slide;
use App\Services\ImageOptimizerService;
use App\Traits\TracksPendingStoragePaths;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Uwil\Storage\Contracts\StorageService;
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Slides\CreateSlideInput, \App\Models\Slide> * @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, HandlesFailure, HandlesSuccess final class CreateSlide implements Action
{ {
use TracksPendingStoragePaths;
public function __construct(
protected readonly StorageService $storageService,
protected readonly PublicS3Disk $s3Disk,
protected readonly ImageOptimizerService $imageOptimizerService,
) {
}
/** /**
* @param \App\Cqs\Actions\Slides\CreateSlideInput $input * @param \App\Cqs\Actions\Slides\CreateSlideInput $input
*/ */
@ -55,10 +36,8 @@ final class CreateSlide implements Action, HandlesFailure, HandlesSuccess
'date_end' => $input->period->end !== null ? Carbon::instance($input->period->end) : null, 'date_end' => $input->period->end !== null ? Carbon::instance($input->period->end) : null,
]; ];
if ($input->picture instanceof UploadedFile) { if ($input->picture !== null) {
$storedPath = $this->storeFile($input->picture); $attributes['picture'] = $input->picture;
$attributes['picture'] = $storedPath;
$this->trackUploadedPath($input, $storedPath);
} }
$slide = new Slide(); $slide = new Slide();
@ -67,27 +46,4 @@ final class CreateSlide implements Action, HandlesFailure, HandlesSuccess
return $slide; 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);
}
} }

View file

@ -14,7 +14,7 @@ final readonly class CreateSlideInput implements ActionInput
public function __construct( public function __construct(
public string $title, public string $title,
public ?string $text = null, public ?string $text = null,
public ?UploadedFile $picture = null, public UploadedFile | string | null $picture = null,
public ?string $pictureAlt = null, public ?string $pictureAlt = null,
public ?string $pictureTitle = null, public ?string $pictureTitle = null,
public ?string $link = null, public ?string $link = null,

View file

@ -6,28 +6,13 @@ namespace App\Cqs\Actions\Slides;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; 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; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Slides\DeleteSlideInput, bool> * @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, HandlesFailure, HandlesSuccess final class DeleteSlide implements Action
{ {
use TracksPendingStoragePaths;
public function __construct(
private readonly StorageService $storageService,
private readonly PublicS3Disk $s3Disk,
) {
}
/** /**
* @param \App\Cqs\Actions\Slides\DeleteSlideInput $input * @param \App\Cqs\Actions\Slides\DeleteSlideInput $input
*/ */
@ -36,29 +21,6 @@ final class DeleteSlide implements Action, HandlesFailure, HandlesSuccess
{ {
Assert::isInstanceOf($input, DeleteSlideInput::class); Assert::isInstanceOf($input, DeleteSlideInput::class);
$picture = $input->slide->picture; return (bool) $input->slide->deleteOrFail();
$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);
} }
} }

View file

@ -6,29 +6,15 @@ namespace App\Cqs\Actions\Slides;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesSuccess;
use App\Models\Slide; use App\Models\Slide;
use App\Services\PublicImageStorageService;
use App\Traits\TracksPendingStoragePaths;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Slides\UpdateSlideInput, \App\Models\Slide> * @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, HandlesFailure, HandlesSuccess final class UpdateSlide implements Action
{ {
use TracksPendingStoragePaths;
public function __construct(
private readonly PublicImageStorageService $publicImageStorageService,
) {
}
/** /**
* @param \App\Cqs\Actions\Slides\UpdateSlideInput $input * @param \App\Cqs\Actions\Slides\UpdateSlideInput $input
*/ */
@ -37,9 +23,6 @@ final class UpdateSlide implements Action, HandlesFailure, HandlesSuccess
{ {
Assert::isInstanceOf($input, UpdateSlideInput::class); Assert::isInstanceOf($input, UpdateSlideInput::class);
$previousPicture = $input->slide->picture;
$newPicture = null;
$attributes = [ $attributes = [
'title' => $input->title, 'title' => $input->title,
'text' => $input->text, 'text' => $input->text,
@ -53,34 +36,14 @@ final class UpdateSlide implements Action, HandlesFailure, HandlesSuccess
'date_end' => $input->period->end !== null ? Carbon::instance($input->period->end) : null, 'date_end' => $input->period->end !== null ? Carbon::instance($input->period->end) : null,
]; ];
if ($input->picture instanceof UploadedFile) { if ($input->picture !== null) {
$newPicture = $this->publicImageStorageService->store($input->picture); $attributes['picture'] = $input->picture;
$attributes['picture'] = $newPicture;
$this->trackUploadedPath($input, $newPicture);
} }
$slide = $input->slide; $slide = $input->slide;
$slide->fill($attributes); $slide->fill($attributes);
$slide->saveOrFail(); $slide->saveOrFail();
$this->trackReplacedPath($input, $previousPicture, $newPicture);
return $slide; 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);
}
}
} }

View file

@ -8,7 +8,6 @@ use App\Contracts\ActionInput;
use App\Models\Slide; use App\Models\Slide;
use Domain\Models\ValueObjects\DatePeriod; use Domain\Models\ValueObjects\DatePeriod;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
final readonly class UpdateSlideInput implements ActionInput final readonly class UpdateSlideInput implements ActionInput
@ -17,7 +16,7 @@ final readonly class UpdateSlideInput implements ActionInput
public Slide $slide, public Slide $slide,
public string $title, public string $title,
public ?string $text = null, public ?string $text = null,
public UploadedFile | StorageFilePath | null $picture = null, public UploadedFile | string | null $picture = null,
public ?string $pictureAlt = null, public ?string $pictureAlt = null,
public ?string $pictureTitle = null, public ?string $pictureTitle = null,
public ?string $link = null, public ?string $link = null,

View file

@ -1,68 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Slides;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Contracts\ActionInputEmpty;
use App\Models\Slide;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Date;
use Psr\Log\LoggerInterface;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<\App\Contracts\ActionInputEmpty, void>
*/
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,
]);
}
}
}

View file

@ -1,37 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Users;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Users\CreateUserInput, \App\Models\User>
*/
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;
}
}

View file

@ -1,28 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Users;
use App\Contracts\ActionInput;
use Domain\Enums\UserRole;
use Webmozart\Assert\Assert;
final readonly class CreateUserInput implements ActionInput
{
public function __construct(
public string $firstname,
public string $lastname,
public string $email,
public string $password,
public UserRole $role,
) {
Assert::stringNotEmpty(trim($this->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);
}
}

View file

@ -7,15 +7,12 @@ namespace App\Cqs\Queries\Basket;
use App\Contracts\Query; use App\Contracts\Query;
use App\Contracts\QueryInput; use App\Contracts\QueryInput;
use App\Contracts\QueryInputEmpty; use App\Contracts\QueryInputEmpty;
use App\Dto\BasketDto; use Domain\Models\Entities\Basket;
use App\Dto\BasketProductDto;
use App\Models\Product;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Services\BasketService; use Domain\Services\BasketService;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Query<\App\Contracts\QueryInputEmpty, \App\Dto\BasketDto> * @implements \App\Contracts\Query<\App\Contracts\QueryInputEmpty, \Domain\Models\Entities\Basket>
*/ */
final readonly class GetBasketQuery implements Query final readonly class GetBasketQuery implements Query
{ {
@ -24,41 +21,13 @@ final readonly class GetBasketQuery implements Query
) { ) {
} }
#[\Override] public function __invoke(QueryInput $input): Basket
public function __invoke(QueryInput $input): BasketDto
{ {
Assert::isAOf( Assert::isAOf(
$input, $input,
QueryInputEmpty::class, QueryInputEmpty::class,
); );
$basket = $this->basketService->getBasket(); return $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);
} }
} }

View file

@ -47,7 +47,6 @@ final readonly class GetDiscountFormDataQuery implements Query
$discountDto = DiscountDto::fromModel($input->discount); $discountDto = DiscountDto::fromModel($input->discount);
} else { } else {
/** @var \Illuminate\Support\Collection<int,\App\Dto\DiscountProductDto> */
$selectedProds = collect(); $selectedProds = collect();
$existingProds = Product::query() $existingProds = Product::query()
->select(['id', 'name', 'picture']) ->select(['id', 'name', 'picture'])

View file

@ -66,8 +66,6 @@ final readonly class GetBoPaginatedOrdersQuery implements Query
if ($input->status !== null) { if ($input->status !== null) {
$query->where('status', $input->status); $query->where('status', $input->status);
} else {
$query->whereNotIn('status', [OrderStatus::PENDING, OrderStatus::FAILED]);
} }
$this->dataTable->sortQuery( $this->dataTable->sortQuery(

View file

@ -9,7 +9,6 @@ use App\Contracts\QueryInput;
use App\Dto\OrderDto; use App\Dto\OrderDto;
use App\Models\Order; use App\Models\Order;
use App\Services\DataTableService; use App\Services\DataTableService;
use Domain\Enums\OrderStatus;
use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Date;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
@ -36,9 +35,7 @@ final readonly class GetBoTodayOrdersQuery implements Query
{ {
Assert::isInstanceOf($input, GetBoTodayOrdersQueryInput::class); Assert::isInstanceOf($input, GetBoTodayOrdersQueryInput::class);
$query = Order::query() $query = Order::query()->with(['shop']);
->with(['shop'])
->whereNotIn('status', [OrderStatus::PENDING, OrderStatus::FAILED]);
$query->whereCreatedAtBetween(Date::now(), Date::now()); $query->whereCreatedAtBetween(Date::now(), Date::now());

View file

@ -8,9 +8,9 @@ use App\Contracts\Query;
use App\Contracts\QueryInput; use App\Contracts\QueryInput;
use App\Dto\OrderDto; use App\Dto\OrderDto;
use App\Models\Order; use App\Models\Order;
use Domain\Enums\OrderStatus;
use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\LengthAwarePaginator as ConcreteLengthAwarePaginator; use Illuminate\Pagination\LengthAwarePaginator as ConcreteLengthAwarePaginator;
use SortDirection;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
@ -44,8 +44,7 @@ final readonly class GetFoCustomerPaginatedOrdersQuery implements Query
$paginator = Order::query() $paginator = Order::query()
->where('employee_matricule', $employeeMatricule->value) ->where('employee_matricule', $employeeMatricule->value)
->whereNotIn('status', [OrderStatus::PENDING, OrderStatus::FAILED]) ->orderBy('id', SortDirection::Descending)
->orderBy('id', \SortDirection::Descending)
->paginate( ->paginate(
perPage: $input->pagination->pageSize()->value(), perPage: $input->pagination->pageSize()->value(),
page: $input->pagination->pageNumber()->value(), page: $input->pagination->pageNumber()->value(),

Some files were not shown because too many files have changed in this diff Show more