Compare commits
184 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
800138930d | ||
|
|
1894e45907 | ||
|
|
aba49edaee | ||
|
|
0a52798a3e | ||
|
|
7ae12f71fe | ||
|
|
d9edcd7f6b | ||
|
|
75784ae719 | ||
|
|
ad2c8f631b | ||
|
|
617d1f70e9 | ||
|
|
d2a7afc020 | ||
|
|
101d0ff018 | ||
|
|
1085a2d4db | ||
|
|
ec7aaa5cfe | ||
|
|
17cca9c43d | ||
|
|
c734ee41e4 | ||
|
|
470c2d1b9d | ||
|
|
7a701328f9 | ||
|
|
758605be09 | ||
|
|
3b24436263 | ||
|
|
c58a2c8b23 | ||
|
|
53f49fea9c | ||
|
|
24acaf56e9 | ||
|
|
dc6b00fbc1 | ||
|
|
757f9aebaa | ||
|
|
85aceedd1f | ||
|
|
392dcdc6c3 | ||
|
|
1f3d25d61a | ||
|
|
45fc35b1f7 | ||
|
|
0fb5a25a4a | ||
|
|
8ffe04c388 | ||
|
|
cdc04d0104 | ||
|
|
3aaec0a6db | ||
|
|
241ad87a2e | ||
|
|
aee7d4b8e7 | ||
|
|
b4384c00a7 | ||
|
|
14fd20c303 | ||
|
|
08c9028f91 | ||
|
|
1b44f9d178 | ||
|
|
2db00301f4 | ||
|
|
a4f2343eb2 | ||
|
|
c9d53f43c0 | ||
|
|
c2490e0339 | ||
|
|
c083d74032 | ||
|
|
7ad5acebd3 | ||
|
|
6f81d94648 | ||
|
|
1f642b185e | ||
|
|
1c304b78b2 | ||
|
|
4f2b7ba0c0 | ||
|
|
99a923a7df | ||
|
|
8a6b1442e6 | ||
|
|
49c17d61f0 | ||
|
|
5b88fb098a | ||
|
|
cdb30e2f70 | ||
|
|
a87e5a0c94 | ||
|
|
588a93cbcf | ||
|
|
8b9eb59b50 | ||
|
|
348119ec7c | ||
|
|
3f4856efa2 | ||
|
|
7b27f532ee | ||
|
|
29b9a87d78 | ||
|
|
ec6e220138 | ||
|
|
7698821501 | ||
|
|
a2fd843398 | ||
|
|
4c8280d932 | ||
|
|
712d42ed96 | ||
|
|
80d3478dbe | ||
|
|
875d6dd01d | ||
|
|
8a3d6a8156 | ||
|
|
50cef3b0cf | ||
|
|
ea06b37a47 | ||
|
|
cbb1ed812b | ||
|
|
d45022d8a4 | ||
|
|
f658dd4b64 | ||
|
|
d1f0b21ad5 | ||
|
|
3916771f69 | ||
|
|
c429697025 | ||
|
|
2d616ed3b4 | ||
|
|
0116d220d4 | ||
|
|
1e872f09d3 | ||
|
|
317ca4cd03 | ||
|
|
1ae8f65d7c | ||
|
|
3d1c798c08 | ||
|
|
3e4dfdad4e | ||
|
|
fae7690161 | ||
|
|
d46d5e7b23 | ||
|
|
f6bae64859 | ||
|
|
285f42c684 | ||
|
|
92dd038cb9 | ||
|
|
abf3839f98 | ||
|
|
6663f0f66f | ||
|
|
550f2a11c8 | ||
|
|
f0617c06ce | ||
|
|
d0a49ec77c | ||
|
|
0411e1d73b | ||
|
|
2c2a0502d6 | ||
|
|
4bbea5d285 | ||
|
|
13aec6bad8 | ||
|
|
1ad8fc45a0 | ||
|
|
13158d7301 | ||
|
|
8029bcd959 | ||
|
|
e0d2074b2b | ||
|
|
fdb7df5858 | ||
|
|
c427b60210 | ||
|
|
3d4c4f74de | ||
|
|
efbd507ac9 | ||
|
|
86e7340c48 | ||
|
|
d2179fcdc8 | ||
|
|
3ff21bdd49 | ||
|
|
3f73535ce7 | ||
|
|
afb385fe5d | ||
|
|
6a599b9855 | ||
|
|
0aa4b449b4 | ||
|
|
8892a55322 | ||
|
|
faef51091e | ||
|
|
43d63bce2e | ||
|
|
4dd7cc82fe | ||
|
|
47b0c16857 | ||
|
|
6c60e067f0 | ||
|
|
5a19f01270 | ||
|
|
0ae05e031d | ||
|
|
b62e15efc2 | ||
|
|
b10c22b931 | ||
|
|
746fe1274d | ||
|
|
d430fa01d2 | ||
|
|
5278c3e3f9 | ||
|
|
2884a76a76 | ||
|
|
66e406499d | ||
|
|
c4d9c84408 | ||
|
|
6ff09f1369 | ||
|
|
ece1b7238d | ||
|
|
fa3aec6d92 | ||
|
|
6f8c7a138b | ||
|
|
d8f326668d | ||
|
|
28a2504841 | ||
|
|
e3611be210 | ||
|
|
5197e796c0 | ||
|
|
570c1e54d5 | ||
|
|
5491c4fc30 | ||
|
|
359f762f87 | ||
|
|
7f1bc1c563 | ||
|
|
574c2a1abe | ||
|
|
5f6ccaa35d | ||
|
|
93dc942152 | ||
|
|
7d5fc6401e | ||
|
|
4be9252c24 | ||
|
|
48e9c9d38e | ||
|
|
bb23dae81e | ||
|
|
ee6a6607dc | ||
|
|
2f76a874d9 | ||
|
|
4fe2d48f68 | ||
|
|
8986570e1d | ||
|
|
bf1c0d7d4e | ||
|
|
a0f84c5da7 | ||
|
|
d1d0585b34 | ||
|
|
10b97e3a00 | ||
|
|
bd314a4575 | ||
|
|
341a66a2d1 | ||
|
|
8c484ae053 | ||
|
|
3426ea22a9 | ||
|
|
ff780a7a46 | ||
|
|
3c34f4af28 | ||
|
|
4771ef9a72 | ||
|
|
455bcd4988 | ||
|
|
6dfef2c7a1 | ||
|
|
79ae763e88 | ||
|
|
4c3fa373da | ||
|
|
9c537d83b2 | ||
|
|
93e4b202da | ||
|
|
97f6085622 | ||
|
|
758fec824d | ||
|
|
3af75ac974 | ||
|
|
5d715094d1 | ||
|
|
9808ef9769 | ||
|
|
cfba7f4756 | ||
|
|
0684215511 | ||
|
|
e4db1a476d | ||
|
|
4a9af4a90a | ||
|
|
f7a20c9d5d | ||
|
|
ba077f88b4 | ||
|
|
30bfabfaf1 | ||
|
|
1fc311ee7e | ||
|
|
6bd1273f78 | ||
|
|
0ee0d7cce7 | ||
|
|
8b8ee17246 |
1021 changed files with 38159 additions and 22404 deletions
41
.env.example
41
.env.example
|
|
@ -1,3 +1,4 @@
|
|||
# APP
|
||||
APP_NAME=Laravel
|
||||
APP_ENV=local
|
||||
APP_KEY=
|
||||
|
|
@ -5,9 +6,11 @@ APP_DEBUG=true
|
|||
APP_URL=http://localhost
|
||||
APP_CURRENCY=EUR
|
||||
|
||||
# LOG
|
||||
LOG_CHANNEL=stack
|
||||
LOG_LEVEL=debug
|
||||
|
||||
# DB
|
||||
DB_CONNECTION=mysql
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
|
|
@ -15,14 +18,42 @@ DB_DATABASE=laravel
|
|||
DB_USERNAME=root
|
||||
DB_PASSWORD=
|
||||
|
||||
# BROADCAST, CACHE, QUEUE
|
||||
BROADCAST_DRIVER=log
|
||||
CACHE_STORE=file
|
||||
QUEUE_CONNECTION=sync
|
||||
|
||||
# SESSION
|
||||
SESSION_DRIVER=file
|
||||
SESSION_LIFETIME=120
|
||||
SESSION_ENCRYPT=false
|
||||
SESSION_SECURE_COOKIE=false
|
||||
SESSION_PATH=/
|
||||
SESSION_DOMAIN=
|
||||
SESSION_CONNECTION=
|
||||
|
||||
FILESYSTEM_DISK=local
|
||||
# REDIS
|
||||
REDIS_CLIENT=phpredis
|
||||
REDIS_SCHEME=tcp
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_USERNAME=null
|
||||
REDIS_PASSWORD=null
|
||||
REDIS_PORT=6379
|
||||
REDIS_PREFIX=cocotte
|
||||
|
||||
# S3
|
||||
AWS_ACCESS_KEY_ID=minioadmin
|
||||
AWS_SECRET_ACCESS_KEY=minioadmin
|
||||
AWS_DEFAULT_REGION=us-east-1
|
||||
AWS_BUCKET=ovoteam
|
||||
AWS_ENDPOINT=http://127.0.0.1:9000
|
||||
AWS_URL=http://127.0.0.1:9000/ovoteam
|
||||
AWS_USE_PATH_STYLE_ENDPOINT=true
|
||||
|
||||
# FILESYSTEM
|
||||
FILESYSTEM_DISK=s3-public
|
||||
|
||||
# MAIL
|
||||
MAIL_MAILER=log
|
||||
MAIL_SCHEME=null
|
||||
MAIL_HOST=127.0.0.1
|
||||
|
|
@ -40,10 +71,10 @@ CRM_ENDPOINT=
|
|||
CRM_TOKEN=
|
||||
CRM_PASSWORD=
|
||||
|
||||
# Sentry
|
||||
# SENTRY
|
||||
SENTRY_LARAVEL_DSN=
|
||||
|
||||
# Matomo
|
||||
# MATOMO
|
||||
MATOMO_SITE_ID=
|
||||
|
||||
# UWIL ADMIN SECURE
|
||||
|
|
@ -52,13 +83,13 @@ UWIL_ADMIN_SECURE_CIDR_LIST=""
|
|||
# - LIST SEPARATED WITH ',' (Optional)
|
||||
UWIL_ADMIN_SECURE_CIDR_PROJECT_ALLOWED_LIST=""
|
||||
|
||||
# Arcadia API
|
||||
# ARCADIA API
|
||||
ARCADIA_API_ENDPOINT=
|
||||
ARCADIA_API_APIKEY=
|
||||
ARCADIA_API_SECRET=
|
||||
ARCADIA_API_IGNORE_SELF_SIGNED_CERT=false
|
||||
|
||||
# Serial Caster
|
||||
# SERIAL CASTER
|
||||
SERIAL_CASTER_SEED=12345
|
||||
|
||||
# LDC
|
||||
|
|
|
|||
|
|
@ -79,7 +79,11 @@ phpstan:
|
|||
variables:
|
||||
PHP_MEMORY_LIMIT: "512M"
|
||||
COMPOSER_CACHE_DIR: ".composer-cache"
|
||||
CRM_ENDPOINT: "http://fake-url.com"
|
||||
CRM_TOKEN: "fake-token"
|
||||
CRM_PASSWORD: "fake-password"
|
||||
script:
|
||||
- cp .env.example .env
|
||||
- php -d memory_limit=512M vendor/bin/phpstan --error-format=junit > phpstan-report.xml
|
||||
artifacts:
|
||||
when: on_failure
|
||||
|
|
@ -253,12 +257,29 @@ tests_laravel:
|
|||
- name: mysql:8.0
|
||||
alias: mysql
|
||||
before_script:
|
||||
- apk add --no-cache mariadb-client mariadb-connector-c icu-data-full
|
||||
- printf "[client]\nssl=0\n" > ~/.my.cnf
|
||||
- composer config gitlab-token.lab.s-web.fr $CI_DEPLOY_USER $CI_DEPLOY_PASSWORD
|
||||
- composer install --no-scripts --no-interaction --no-ansi --no-progress --prefer-dist
|
||||
script:
|
||||
- cp .env.example .env
|
||||
- php artisan key:generate
|
||||
- php -r "while(true){try{new PDO('mysql:host=mysql;dbname=testing_db','root','password');break;}catch(Exception){sleep(1);}}"
|
||||
- |
|
||||
php -r '
|
||||
while (true) {
|
||||
try {
|
||||
$pdo = new PDO("mysql:host=mysql;dbname=testing_db", "root", "password");
|
||||
$account = (string) $pdo->query("SELECT CURRENT_USER()")->fetchColumn();
|
||||
[$user, $host] = explode("@", $account, 2);
|
||||
$pdo->exec("ALTER USER " . $pdo->quote($user) . "@" . $pdo->quote($host) . " IDENTIFIED WITH mysql_native_password BY " . $pdo->quote("password"));
|
||||
$pdo->exec("FLUSH PRIVILEGES");
|
||||
break;
|
||||
} catch (Exception) {
|
||||
sleep(1);
|
||||
}
|
||||
}
|
||||
'
|
||||
- mysql --user=root --password=password --host=mysql --port=3306 --database=testing_db -e "SELECT 1"
|
||||
- php artisan config:clear
|
||||
- php artisan test --coverage --colors=never --log-junit=coverage/junit.xml --coverage-cobertura=coverage/cobertura.xml --coverage-html=coverage/html
|
||||
after_script:
|
||||
|
|
|
|||
|
|
@ -7,12 +7,18 @@ Les règles reposent sur le code de la partie **Domaine**.
|
|||
La sélection du retrait se fait désormais sur une journée complète et non plus par tranches horaires via `PickupSchedulingService`.
|
||||
|
||||
- **Jour de retrait standard** : Uniquement le **Vendredi** (`PICKUP_DAY = WeekDay::Friday`).
|
||||
- **Heure de clôture (Cutoff)** : **Lundi à 14h00** de la même semaine (`CUTOFF_DAY = Monday`, `CUTOFF_HOUR = 14`).
|
||||
- *Comportement* : Une commande validée avant Lundi 14h00 est préparée pour le vendredi en cours. Passé ce délai, le premier jour disponible bascule automatiquement sur le vendredi de la semaine suivante.
|
||||
- **Gestion des Exceptions** :
|
||||
- **Heure de clôture (Cutoff)** : **Lundi à 14h00** (`Europe/Paris`) de la même semaine (`CUTOFF_DAY = Monday`, `CUTOFF_HOUR = 14`).
|
||||
- *Comportement* : Une commande validée avant Lundi 14h00 (`<= 14:00:00 Europe/Paris`) est préparée pour le vendredi en cours. Passé ce délai, `nextPickup()` et `currentCutoff()` basculent automatiquement sur le vendredi et le lundi de la semaine suivante.
|
||||
- *Lundis fériés* : Si un lundi (`CUTOFF_DAY`) est un jour férié, la prise de commande et le cutoff restent inchangés (seuls les jours de retrait sont affectés par les jours fériés).
|
||||
- **Fuseaux horaires & Persistance BDD (MySQL)** :
|
||||
- Toute la logique métier du cutoff et des jours de retrait opère en **`Europe/Paris`**.
|
||||
- En base de données (`config('app.timezone') = 'UTC'`), toutes les colonnes `datetime`/`timestamp` sont converties et stockées en **UTC** via `App\Casts\UtcDatetimeCast` (et converties côté requêtes BO depuis `client_timezone` via `ConvertsClientDatesToUtc`), puis affichées au fuseau local via `Date::forHumans()` / `Date::toLocalInput()`.
|
||||
- Les colonnes SQL `DATE` calendaires sans heure (`pickup_exceptions.date`, `replacement_date`, `pickup_day`, `employees.start_date`/`end_date`, `stats.date`) utilisent `App\Casts\CalendarDateCast` afin d'être stockées en `Y-m-d` sans décalage horaire ni perte d'un jour, et affichées via `Date::forHumansDate()`.
|
||||
- **Gestion des Exceptions & Jours fériés** :
|
||||
- Les fermetures et jours fériés sont gérés via des `ShopPickupException`.
|
||||
- Une exception peut **fermer le retrait**, ou proposer un **jour de remplacement**. Ce jour de remplacement peut posséder sa propre limite de validation (`orderDeadlineAt`).
|
||||
- Une tâche planifiée `UpsertShopsPickupExceptionsUsingApiForYear` est lancée pour provisionner les jours fériés de l'année pour toutes les boutiques
|
||||
- Une tâche planifiée `EnsurePublicHolidaysSyncedJob` synchronise les jours fériés de la zone **Métropole** (`calendrier.api.gouv.fr/jours-feries/metropole/:year.json`, hors Alsace-Moselle) pour toutes les boutiques existantes (`UpsertShopsPickupExceptionsForYear`).
|
||||
- Lors de la création d'une nouvelle boutique (`CreateShop`), les jours fériés déjà synchronisés (`auto_updated = true`, année courante et suivantes) lui sont automatiquement rattachés.
|
||||
|
||||
## 2. Limites de Montants
|
||||
|
||||
|
|
@ -31,3 +37,61 @@ Elle est géré par le service `ProductAvailabilityService`.
|
|||
- Il est éligible INCO (`hasInco = true`).
|
||||
- La date actuelle est supérieure ou égale à `orderable_start` (si défini).
|
||||
- La date actuelle est inférieure à `orderable_end` (si défini).
|
||||
|
||||
## 4. Statut Actif du Salarié
|
||||
|
||||
Elle est vérifiée côté Domaine par `Shopper::isActive()` et côté Eloquent par `Employee::isActive` / `Employee::scopeActive()`.
|
||||
|
||||
- **Fuseau calendaire (`Europe/Paris`)** :
|
||||
- En base de données, `start_date` et `end_date` sont des colonnes SQL `DATE` (sans heure ni fuseau, chargées via `CalendarDateCast`).
|
||||
- L'activation et la désactivation sont évaluées par rapport à la date calendaire du jour en **`Europe/Paris`** (`00:00:00 Europe/Paris`), afin d'éviter le décalage nocturne de 1 h à 2 h lié à UTC.
|
||||
|
||||
- **Date de début (`start_date`)** :
|
||||
|
||||
- Le salarié est actif lorsque `start_date` est inférieure ou égale au jour courant en `Europe/Paris` (ou si `start_date` est `null` en base de données).
|
||||
- Un salarié dont la `start_date` est dans le futur est considéré comme **inactif** jusqu'à la date d'effet (`00:00:00 Europe/Paris` du jour de début).
|
||||
|
||||
- **Date de fin (`end_date`)** :
|
||||
|
||||
- Le salarié est actif uniquement si `end_date` est `null` ou strictement supérieure au jour courant en `Europe/Paris` (`end_date > aujourd'hui Europe/Paris`).
|
||||
- **Comportement assumé** : le salarié devient donc inactif dès `00:00:00 Europe/Paris` de son dernier jour renseigné (`end_date`).
|
||||
|
||||
## 5. Cycle de Vie, Tunnel de Commande & Annulation (Back-Office)
|
||||
|
||||
### Statuts des commandes (`Domain\Enums\OrderStatus`)
|
||||
- **`WAITING` (`'waiting'`)** : reliquat historique des commandes créées avant la refonte (paniers non transformés). Conservé en lecture dans les statistiques historiques.
|
||||
- **`PENDING` (`'pending'`)** : commande technique créée lors de `PlacePendingOrder` avant l'export Régate. Elle est comptabilisée dans le plafond hebdomadaire de 200 € (`EloquentEmployeeStatisticsService`), masquée en Front-Office (`GetFoCustomerPaginatedOrdersQuery`, `Frontend\OrderPolicy::viewOwn`) et masquée par défaut en Back-Office (affichable à la demande via le filtre statut).
|
||||
- **`VALIDATED` (`'validated'`)** : commande confirmée après succès de l'export Régate (`ConfirmPlacedOrder`).
|
||||
- **`FAILED` (`'failed'`)** : statut technique en cas d'échec de l'export Régate (`FailPendingOrder`) ou d'expiration d'une commande `PENDING` bloquée au-delà de 10 minutes (`FailStalePendingOrders` / `FailStalePendingOrdersJob`, planifié toutes les 5 minutes). Masqué en Front-Office, affichable à la demande en Back-Office, exclu du plafond hebdomadaire et des statistiques.
|
||||
- **`CANCELED` (`'canceled'`)** : annulation métier (Back-Office ou Régate).
|
||||
|
||||
### Concurrence du tunnel & suivi des paniers non transformés
|
||||
- Lors de la soumission finale (`TunnelController::confirmationSubmit()`), un verrou distribué non bloquant (`order:checkout:shopper:{id}`, `waitSeconds: 0`, TTL `60s`) protège la séquence synchrone `PlacePendingOrder` (elle-même protégée par `#[Locked]` sur `order:finalize:shopper:{id}`) → `ExportOrderToRegate` → `ConfirmPlacedOrder` / `FailPendingOrder`.
|
||||
- Les entrées dans le tunnel (étape 1, `OrderTunnelService::initializeFromBasket`) créent ou réutilisent une tentative en session dans `order_tunnel_attempts` (`TunnelAttemptTrackerService::recordEntry`), marquée convertie lors de la validation (`markConverted`) ou réinitialisée en session si le panier est vidé (`BasketRemoved` → `ResetTunnelAttemptOnBasketRemoved`). `StatsService::getNbWaitingCmd()` (et `getCanceledRate()`) additionnent les commandes historiques `WAITING` et les tentatives `order_tunnel_attempts` non converties (`converted_at IS NULL`).
|
||||
|
||||
### Annulation de Commande (Back-Office)
|
||||
Elle est autorisée côté HTTP par `App\Policies\Backend\OrderPolicy::cancel()` et exécutée côté Domaine par `Domain\Services\OrderService::cancelOrder()`.
|
||||
|
||||
- **Statuts autorisés & date de retrait (`pickup_day`)** : `Backend\OrderPolicy::cancel()` interdit d'annuler une commande déjà `CANCELED`, `PENDING` ou `FAILED`, mais autorise intentionnellement un administrateur à annuler toute commande métier (`WAITING` ou `VALIDATED`), y compris lorsque `pickup_day` est déjà dépassé (rattrapage/correction administrative).
|
||||
- **Comportement assumé** : l'annulation d'une commande depuis le Back-Office met uniquement à jour son statut en base de données (`cancel()` puis `persist()`) sans émettre d'événement de domaine ni envoyer d'e-mail ou de notification à Régate ou au client.
|
||||
|
||||
## 6. Code d'Accès Salarié & Inscription
|
||||
|
||||
La génération des codes d'accès salariés est gérée par `App\Services\CodeGenerationService` et leur validation à l'inscription par `App\Http\Requests\Fo\Auth\RegisterRequest`.
|
||||
|
||||
- **Génération déterministe du code** :
|
||||
- Chaque code d'accès (`Code`, longueur `7`) est dérivé de façon déterministe à partir du `matricule` du salarié via `SerialCasterBuilder` (`Code::ALLOWED_CHARACTERS`, `Code::LENGTH`). Il ne s'agit pas d'un secret aléatoire, mais d'un code d'appariement court lié au matricule.
|
||||
- **Validation à l'inscription (`RegisterRequest`)** :
|
||||
- L'existence d'un `matricule` non encore associé à un compte client (`employees.customer_id IS NULL`) est validée explicitement (`Rule::exists('employees', 'matricule')->whereNull('customer_id')`), séparément de la règle sur `code` (`Rule::exists('employees', 'code')->where('matricule', ...)->whereNull('customer_id')`).
|
||||
- Les messages d'erreur distincts entre « matricule inconnu / déjà utilisé » et « code incorrect » sont assumés pour faciliter le support utilisateur, les routes d'authentification étant protégées par un rate limiter (`throttle`).
|
||||
|
||||
## 7. Connexion d'un Compte Non Activé (CRM & `laravel/ui`)
|
||||
|
||||
Elle est gérée par `App\Auth\CrmUserProvider::validateCredentials()` et `App\Http\Controllers\Fo\Auth\LoginController::authenticated()`.
|
||||
|
||||
- **Validation CRM (`CrmService::login()`)** :
|
||||
- L'API CRM (`Api\V4\CustomerController::authenticate()`) vérifie **d'abord** le mot de passe (`ApiError::authFailed`) avant de vérifier si le compte est activé (`ApiError::customerNotActivated` → `CrmCustomerNotActivatedException`).
|
||||
- **Alignement sur `laravel/ui` (`VerificationController`)** :
|
||||
- Conformément au fonctionnement standard de `laravel/ui`, `VerificationController` requiert une session authentifiée (`auth:frontend`) pour accéder aux routes `email/verify`, `email/verify/{id}/{hash}` et `email/resend`.
|
||||
- Lorsqu'un client saisit le **bon mot de passe** sur un compte non encore activé, `CrmUserProvider::validateCredentials()` intercepte `CrmCustomerNotActivatedException`, renvoie l'e-mail de vérification et retourne `true` afin d'ouvrir la session et de laisser le middleware `verified` (`EnsureCustomerEmailIsVerified`) rediriger vers `fo.auth.verification.notice`.
|
||||
- En revanche, `LoginController::authenticated()` ne flashe le message `"You are logged in!"` que si l'e-mail du client est déjà vérifié (`AppCustomerAuthService::hasVerifiedEmail()`).
|
||||
|
|
|
|||
24
app/Attributes/Locked.php
Normal file
24
app/Attributes/Locked.php
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
<?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));
|
||||
}
|
||||
}
|
||||
}
|
||||
10
app/Attributes/WithoutTransaction.php
Normal file
10
app/Attributes/WithoutTransaction.php
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Attributes;
|
||||
|
||||
#[\Attribute(\Attribute::TARGET_CLASS)]
|
||||
final readonly class WithoutTransaction
|
||||
{
|
||||
}
|
||||
|
|
@ -9,23 +9,16 @@ use App\Exceptions\Crm\CrmCustomerNotActivatedException;
|
|||
use App\Exceptions\CrmServiceException;
|
||||
use App\Models\Customer;
|
||||
use App\Services\CrmService;
|
||||
use Domain\Models\ValueObjects\CrmCustomer;
|
||||
use Domain\Models\ValueObjects\Email;
|
||||
use Illuminate\Auth\EloquentUserProvider;
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||
use Illuminate\Contracts\Auth\UserProvider;
|
||||
use Illuminate\Contracts\Hashing\Hasher;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Shared\ValueObjects\CrmHashcode;
|
||||
use UnexpectedValueException;
|
||||
|
||||
class CrmUserProvider extends EloquentUserProvider implements UserProvider
|
||||
{
|
||||
private ?CrmCustomer $crmCustomer = null;
|
||||
|
||||
/**
|
||||
* @param class-string<\Illuminate\Contracts\Auth\Authenticatable&\Illuminate\Database\Eloquent\Model> $model
|
||||
*/
|
||||
|
|
@ -56,7 +49,12 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
|
|||
#[\Override]
|
||||
public function retrieveByCredentials(array $credentials): ?Authenticatable
|
||||
{
|
||||
$model = parent::retrieveByCredentials($credentials);
|
||||
$model = parent::retrieveByCredentials($credentials);
|
||||
|
||||
if ($model === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$result = $this->crmService->getCustomerFromEmail(Arr::string($credentials, 'email'));
|
||||
|
||||
if ($result instanceof CrmServiceException) {
|
||||
|
|
@ -66,13 +64,7 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
|
|||
]);
|
||||
}
|
||||
|
||||
$this->crmCustomer = $result;
|
||||
|
||||
if ($this->crmCustomer instanceof CrmCustomer && $model === null) {
|
||||
$model = $this->createLocalCustomer($this->crmCustomer);
|
||||
}
|
||||
|
||||
return $this->crmCustomer !== null ? $model : null;
|
||||
return $result !== null ? $model : null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -88,11 +80,11 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
|
|||
public function validateCredentials(Authenticatable $model, array $credentials): bool
|
||||
{
|
||||
if ($model::class !== $this->usedModel) {
|
||||
throw new UnexpectedValueException("Cannot authenticate any thing else than '{$this->usedModel}'");
|
||||
throw new \UnexpectedValueException("Cannot authenticate any thing else than '{$this->usedModel}'");
|
||||
}
|
||||
|
||||
if (! in_array(MustVerifyEmail::class, \class_implements($model))) {
|
||||
throw new UnexpectedValueException("Model '{$this->usedModel}' should implement 'MustVerifyEmail'");
|
||||
throw new \UnexpectedValueException("Model '{$this->usedModel}' should implement 'MustVerifyEmail'");
|
||||
}
|
||||
/** @var \Illuminate\Contracts\Auth\Authenticatable&\Illuminate\Contracts\Auth\MustVerifyEmail $model */
|
||||
$requestEmail = Arr::string($credentials, 'email');
|
||||
|
|
@ -106,7 +98,11 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
|
|||
|
||||
return true;
|
||||
} catch (CrmCustomerNotActivatedException) {
|
||||
$model->sendEmailVerificationNotification();
|
||||
try {
|
||||
$model->sendEmailVerificationNotification();
|
||||
} catch (\Throwable $e) {
|
||||
report($e);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (CrmAuthenticationFailedException) {
|
||||
|
|
@ -125,26 +121,4 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
|
|||
{
|
||||
// No hashing.
|
||||
}
|
||||
|
||||
private function createLocalCustomer(CrmCustomer $crmCustomer): Model & Authenticatable
|
||||
{
|
||||
$email = $crmCustomer->email ?
|
||||
new Email($crmCustomer->email) :
|
||||
throw new UnexpectedValueException('Email is required ti create a customer');
|
||||
|
||||
$hashcode = $crmCustomer->hashcode ?
|
||||
$crmCustomer->hashcode :
|
||||
throw new UnexpectedValueException('Hashcode is required to create a customer');
|
||||
|
||||
/** @var \App\Models\Customer&\Illuminate\Contracts\Auth\Authenticatable $model */
|
||||
$model = $this->usedModel::query()
|
||||
->where('email', $crmCustomer->email)
|
||||
->firstOrNew();
|
||||
|
||||
$model->email = $email;
|
||||
$model->hashcode = CrmHashcode::fromString($hashcode);
|
||||
$model->saveOrFail();
|
||||
|
||||
return $model;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
62
app/Casts/CalendarDateCast.php
Normal file
62
app/Casts/CalendarDateCast.php
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
<?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.');
|
||||
}
|
||||
}
|
||||
|
|
@ -6,7 +6,7 @@ namespace App\Casts;
|
|||
|
||||
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
use Shared\Helpers\UuidHelper;
|
||||
use Shared\ValueObjects\CrmHashcode;
|
||||
|
||||
/** @implements CastsAttributes<CrmHashcode, CrmHashcode|string> */
|
||||
|
|
@ -19,7 +19,7 @@ class CrmHashcodeCast implements CastsAttributes
|
|||
throw new \UnexpectedValueException('CrmHashcode must be a string.');
|
||||
}
|
||||
|
||||
$uuid = Uuid::fromString($value);
|
||||
$uuid = UuidHelper::fromString($value);
|
||||
|
||||
return new CrmHashcode($uuid);
|
||||
}
|
||||
|
|
@ -32,7 +32,7 @@ class CrmHashcodeCast implements CastsAttributes
|
|||
}
|
||||
|
||||
if (is_string($value)) {
|
||||
$value = new CrmHashcode(Uuid::fromString($value));
|
||||
$value = new CrmHashcode(UuidHelper::fromString($value));
|
||||
}
|
||||
|
||||
if (! ($value instanceof CrmHashcode)) {
|
||||
|
|
|
|||
45
app/Casts/FilePathCast.php
Normal file
45
app/Casts/FilePathCast.php
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
<?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.');
|
||||
}
|
||||
}
|
||||
|
|
@ -14,8 +14,8 @@ use Domain\Models\ValueObjects\ProductWeight;
|
|||
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Arr;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
use Symfony\Component\Uid\Uuid as SymfonyUuid;
|
||||
use Shared\Helpers\UuidHelper;
|
||||
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
|
||||
|
||||
/**
|
||||
* @implements CastsAttributes<OrderLineProduct,OrderLineProduct>
|
||||
|
|
@ -44,9 +44,7 @@ class OrderLineProductCast implements CastsAttributes
|
|||
|
||||
return new OrderLineProduct(
|
||||
incoId: new IncoId(Arr::integer($data, 'inco_id')),
|
||||
originalId: new ProductId(Uuid::fromString(
|
||||
SymfonyUuid::fromString(Arr::string($data, 'original_id'))->toRfc4122()
|
||||
)),
|
||||
originalId: new ProductId(UuidHelper::parse(Arr::string($data, 'original_id'))),
|
||||
name: Arr::string($data, 'name'),
|
||||
weight: new ProductWeight(
|
||||
value: Arr::integer($data, 'weight'),
|
||||
|
|
@ -58,7 +56,7 @@ class OrderLineProductCast implements CastsAttributes
|
|||
discountedPrice: new MoneyCast()->get($model, 'discounted_price', Arr::get($data, 'discounted_price'), []),
|
||||
priceKgTtc: new MoneyCast()->get($model, 'price_kg_ttc', Arr::get($data, 'price_kg_ttc'), []),
|
||||
taxRate: TaxRate::fromPercent($taxRate),
|
||||
picture: is_string($picture = Arr::get($data, 'picture')) ? $picture : null,
|
||||
picture: is_string($picture = Arr::get($data, 'picture')) ? new StorageFilePath($picture) : null,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -99,7 +97,7 @@ class OrderLineProductCast implements CastsAttributes
|
|||
[]
|
||||
),
|
||||
'tax_rate' => $value->taxRate->percent(),
|
||||
'picture' => $value->picture,
|
||||
'picture' => $value->picture?->value,
|
||||
], \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
59
app/Casts/UtcDatetimeCast.php
Normal file
59
app/Casts/UtcDatetimeCast.php
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
<?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.');
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ namespace App\Console\Commands;
|
|||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Mail\Message;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
|
|
@ -24,7 +25,7 @@ class MailTest extends Command
|
|||
'email' => ['required', 'email:rfc,strict'],
|
||||
])->validate();
|
||||
|
||||
Mail::raw('This is a test mail', function ($message): void {
|
||||
Mail::raw('This is a test mail', function (Message $message): void {
|
||||
$message->to($this->argument('email'));
|
||||
$message->subject('Test mail');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -15,22 +15,27 @@ class UpsertPublicHolydaysOnShopsPickupExceptions extends Command
|
|||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle()
|
||||
public function handle(): int
|
||||
{
|
||||
$year = $this->argument('year');
|
||||
|
||||
if (is_numeric($year) === false) {
|
||||
if ($year !== null && is_numeric($year) === false) {
|
||||
$this->error('The year must be a number');
|
||||
|
||||
return;
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info('Fetching hollidays upsert shops exceptions using Api');
|
||||
dispatch(new UpsertShopsPickupExceptionsUsingApiForYear(intval($year)));
|
||||
|
||||
$job = $year !== null
|
||||
? new UpsertShopsPickupExceptionsUsingApiForYear(intval($year))
|
||||
: new UpsertShopsPickupExceptionsUsingApiForYear();
|
||||
|
||||
dispatch($job);
|
||||
|
||||
$this->info('Done');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,15 +4,17 @@ declare(strict_types=1);
|
|||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Contracts\Executor;
|
||||
use App\Cqs\Actions\Users\CreateUser;
|
||||
use App\Cqs\Actions\Users\CreateUserInput;
|
||||
use Domain\Enums\UserRole;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
#[Description('creates an admin user upon password entry')]
|
||||
#[Signature('uwil:user:create')]
|
||||
|
|
@ -21,7 +23,7 @@ class UserCreate extends Command
|
|||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
public function handle(Executor $executor, CreateUser $action): int
|
||||
{
|
||||
$firstname = $this->askString('What is the firstname?', 'Equipe');
|
||||
$lastname = $this->askString('What is the lastname?', 'Web');
|
||||
|
|
@ -29,14 +31,13 @@ class UserCreate extends Command
|
|||
$pwd = $this->askPassword('What is the password?');
|
||||
$role = $this->askRole();
|
||||
|
||||
$user = new User();
|
||||
$user->firstname = $firstname;
|
||||
$user->lastname = $lastname;
|
||||
$user->email = $email;
|
||||
$user->password = Hash::make($pwd);
|
||||
$user->email_verified_at = now();
|
||||
$user->role = $role;
|
||||
$user->save();
|
||||
$executor->execute($action, new CreateUserInput(
|
||||
firstname: $firstname,
|
||||
lastname: $lastname,
|
||||
email: $email,
|
||||
password: $pwd,
|
||||
role: $role,
|
||||
));
|
||||
|
||||
$this->info('User created.');
|
||||
|
||||
|
|
@ -119,6 +120,9 @@ class UserCreate extends Command
|
|||
multiple: false
|
||||
)
|
||||
);
|
||||
|
||||
Assert::string($response[0]);
|
||||
|
||||
$role = UserRole::tryFrom(
|
||||
intval(mb_strcut((string) $response[0], 0, 1))
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,18 +0,0 @@
|
|||
<?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;
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
<?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;
|
||||
}
|
||||
|
|
@ -1,48 +0,0 @@
|
|||
<?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;
|
||||
}
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Contracts;
|
||||
|
||||
/**
|
||||
* @template TEntity
|
||||
* @template TId
|
||||
*
|
||||
* @method TEntity|null find(TId $id)
|
||||
*/
|
||||
interface Directory
|
||||
{
|
||||
}
|
||||
16
app/Contracts/HandlesFailure.php
Normal file
16
app/Contracts/HandlesFailure.php
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<?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;
|
||||
}
|
||||
18
app/Contracts/HandlesLockTimeout.php
Normal file
18
app/Contracts/HandlesLockTimeout.php
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
<?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;
|
||||
}
|
||||
18
app/Contracts/HandlesSuccess.php
Normal file
18
app/Contracts/HandlesSuccess.php
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
<?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;
|
||||
}
|
||||
16
app/Contracts/ProvidesLockKey.php
Normal file
16
app/Contracts/ProvidesLockKey.php
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<?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;
|
||||
}
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
<?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;
|
||||
}
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
<?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;
|
||||
}
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
<?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;
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
<?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
|
||||
{
|
||||
}
|
||||
31
app/Cqs/Actions/Auth/DeleteOldResetTokens.php
Normal file
31
app/Cqs/Actions/Auth/DeleteOldResetTokens.php
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
<?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();
|
||||
}
|
||||
}
|
||||
56
app/Cqs/Actions/Auth/ResetCustomerPassword.php
Normal file
56
app/Cqs/Actions/Auth/ResetCustomerPassword.php
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
<?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)
|
||||
);
|
||||
}
|
||||
}
|
||||
20
app/Cqs/Actions/Auth/ResetCustomerPasswordInput.php
Normal file
20
app/Cqs/Actions/Auth/ResetCustomerPasswordInput.php
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<?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);
|
||||
}
|
||||
}
|
||||
40
app/Cqs/Actions/Auth/ResetCustomerPasswordOutput.php
Normal file
40
app/Cqs/Actions/Auth/ResetCustomerPasswordOutput.php
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
<?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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -10,7 +10,6 @@ use App\Interfaces\ModelWithOrder;
|
|||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use SortDirection;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
|
|
@ -29,7 +28,7 @@ final class ChangeModelOrder implements Action
|
|||
Assert::isInstanceOf($input, ChangeModelOrderInput::class);
|
||||
|
||||
$model = $input->model;
|
||||
$goUp = $input->direction === SortDirection::Ascending;
|
||||
$goUp = $input->direction === \SortDirection::Ascending;
|
||||
$currentOrder = $model->getOrder();
|
||||
|
||||
$usesSoftDeletes = in_array(SoftDeletes::class, class_uses_recursive($model), true)
|
||||
|
|
@ -44,7 +43,7 @@ final class ChangeModelOrder implements Action
|
|||
/** @var (Model&ModelWithOrder)|null $adjacentModel */
|
||||
$adjacentModel = $baseQuery
|
||||
->where('order', $goUp ? '<' : '>', $currentOrder)
|
||||
->orderBy('order', $goUp ? SortDirection::Descending : SortDirection::Ascending)
|
||||
->orderBy('order', $goUp ? \SortDirection::Descending : \SortDirection::Ascending)
|
||||
->first();
|
||||
|
||||
if ($adjacentModel === null) {
|
||||
|
|
|
|||
|
|
@ -7,16 +7,12 @@ namespace App\Cqs\Actions\Common;
|
|||
use App\Contracts\ActionInput;
|
||||
use App\Interfaces\ModelWithOrder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use SortDirection;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
final readonly class ChangeModelOrderInput implements ActionInput
|
||||
{
|
||||
public function __construct(
|
||||
public Model & ModelWithOrder $model,
|
||||
public SortDirection $direction,
|
||||
public \SortDirection $direction,
|
||||
) {
|
||||
Assert::isInstanceOf($this->model, Model::class);
|
||||
Assert::isInstanceOf($this->model, ModelWithOrder::class);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,8 +15,6 @@ final readonly class ChangeModelOrderPositionInput implements ActionInput
|
|||
public Model & ModelWithOrder $model,
|
||||
public int $targetOrder,
|
||||
) {
|
||||
Assert::isInstanceOf($this->model, Model::class);
|
||||
Assert::isInstanceOf($this->model, ModelWithOrder::class);
|
||||
Assert::greaterThanEq($this->targetOrder, 1);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ final class ExecuteMassAction implements Action
|
|||
break;
|
||||
|
||||
default:
|
||||
throw new \UnexpectedValueException('Unsupported mass action type: ' . $input->action->value);
|
||||
throw new \UnexpectedValueException('Unsupported mass action type: ' . gettype($input->action->value));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -88,7 +88,7 @@ final class ExecuteMassAction implements Action
|
|||
break;
|
||||
|
||||
default:
|
||||
throw new \UnexpectedValueException('Unsupported mass action type: ' . $input->action->value);
|
||||
throw new \UnexpectedValueException('Unsupported mass action type: ' . gettype($input->action->value));
|
||||
}
|
||||
|
||||
$foundModel->saveOrFail();
|
||||
|
|
|
|||
|
|
@ -7,14 +7,11 @@ namespace App\Cqs\Actions\Common;
|
|||
use App\Contracts\ActionInput;
|
||||
use App\Interfaces\ModelWithStar;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
final readonly class ToggleModelStarInput implements ActionInput
|
||||
{
|
||||
public function __construct(
|
||||
public Model & ModelWithStar $model,
|
||||
) {
|
||||
Assert::isInstanceOf($this->model, Model::class);
|
||||
Assert::isInstanceOf($this->model, ModelWithStar::class);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,14 +7,11 @@ namespace App\Cqs\Actions\Common;
|
|||
use App\Contracts\ActionInput;
|
||||
use App\Interfaces\ModelWithStatus;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
final readonly class ToggleModelStatusInput implements ActionInput
|
||||
{
|
||||
public function __construct(
|
||||
public Model & ModelWithStatus $model,
|
||||
) {
|
||||
Assert::isInstanceOf($this->model, Model::class);
|
||||
Assert::isInstanceOf($this->model, ModelWithStatus::class);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
86
app/Cqs/Actions/Contact/SubmitContactForm.php
Normal file
86
app/Cqs/Actions/Contact/SubmitContactForm.php
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
<?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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
29
app/Cqs/Actions/Contact/SubmitContactFormInput.php
Normal file
29
app/Cqs/Actions/Contact/SubmitContactFormInput.php
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
<?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));
|
||||
}
|
||||
}
|
||||
|
|
@ -4,34 +4,78 @@ declare(strict_types=1);
|
|||
|
||||
namespace App\Cqs\Actions\Customers;
|
||||
|
||||
use App\Attributes\Locked;
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Contracts\Repositories\EmployeeRepository;
|
||||
use App\Contracts\HandlesFailure;
|
||||
use App\Contracts\HandlesLockTimeout;
|
||||
use App\Contracts\HandlesSuccess;
|
||||
use App\Contracts\ProvidesLockKey;
|
||||
use App\Enums\RegisterCustomerStatus;
|
||||
use App\Exceptions\Crm\CrmCustomerExistsException;
|
||||
use App\Exceptions\CrmServiceException;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Employee;
|
||||
use App\Services\CrmService;
|
||||
use Domain\Enums\Country;
|
||||
use Domain\Models\ValueObjects\CrmCustomer;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Infrastructure\Adapters\Services\AppCustomerAuthService;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
use Shared\Helpers\UuidHelper;
|
||||
use Shared\ValueObjects\CrmHashcode;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\Customers\RegisterCustomerInput, \App\Models\Customer>
|
||||
* @implements \App\Contracts\Action<
|
||||
* \App\Cqs\Actions\Customers\RegisterCustomerInput,
|
||||
* \App\Cqs\Actions\Customers\RegisterCustomerOutput
|
||||
* >
|
||||
* @implements \App\Contracts\ProvidesLockKey<\App\Cqs\Actions\Customers\RegisterCustomerInput>
|
||||
* @implements \App\Contracts\HandlesLockTimeout<
|
||||
* \App\Cqs\Actions\Customers\RegisterCustomerInput,
|
||||
* \App\Cqs\Actions\Customers\RegisterCustomerOutput
|
||||
* >
|
||||
* @implements \App\Contracts\HandlesSuccess<
|
||||
* \App\Cqs\Actions\Customers\RegisterCustomerInput,
|
||||
* \App\Cqs\Actions\Customers\RegisterCustomerOutput
|
||||
* >
|
||||
* @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Customers\RegisterCustomerInput>
|
||||
*/
|
||||
final class RegisterCustomer implements Action
|
||||
#[Locked(ttlSeconds: 30, waitSeconds: 10)]
|
||||
final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeout, HandlesSuccess, ProvidesLockKey
|
||||
{
|
||||
/** @var array<int, array{hashcode: \Shared\ValueObjects\CrmHashcode, email: \Domain\Models\ValueObjects\Email}> */
|
||||
private array $createdCrmCustomers = [];
|
||||
|
||||
public function __construct(
|
||||
private readonly AppCustomerAuthService $authService,
|
||||
private readonly CrmService $crmService,
|
||||
private readonly EmployeeRepository $employeeRepository,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
|
||||
*/
|
||||
#[\Override]
|
||||
public function lockKey(ActionInput $input): string
|
||||
{
|
||||
Assert::isInstanceOf($input, RegisterCustomerInput::class);
|
||||
|
||||
return "customer:register:employee:{$input->matricule->value}";
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
|
||||
*/
|
||||
#[\Override]
|
||||
public function onLockTimeout(ActionInput $input): RegisterCustomerOutput
|
||||
{
|
||||
Assert::isInstanceOf($input, RegisterCustomerInput::class);
|
||||
|
||||
return RegisterCustomerOutput::lockTimeout();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
|
||||
*
|
||||
|
|
@ -40,27 +84,39 @@ final class RegisterCustomer implements Action
|
|||
* @throws ModelNotFoundException
|
||||
*/
|
||||
#[\Override]
|
||||
public function __invoke(ActionInput $input): Customer
|
||||
public function __invoke(ActionInput $input): RegisterCustomerOutput
|
||||
{
|
||||
Assert::isInstanceOf($input, RegisterCustomerInput::class);
|
||||
|
||||
$inputKey = spl_object_id($input);
|
||||
unset($this->createdCrmCustomers[$inputKey]);
|
||||
|
||||
$employee = Employee::query()
|
||||
->where('matricule', $input->matricule->value)
|
||||
->where('code', $input->code->value)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if (! $employee) {
|
||||
throw new ModelNotFoundException('Employee not found');
|
||||
}
|
||||
|
||||
if ($employee->customer_id !== null) {
|
||||
return RegisterCustomerOutput::employeeAlreadyRegistered();
|
||||
}
|
||||
|
||||
if (! $employee->is_active) {
|
||||
return RegisterCustomerOutput::employeeInactive();
|
||||
}
|
||||
|
||||
// * Persist and associate Customer + Employee
|
||||
$customer = new Customer([
|
||||
'email' => $input->email,
|
||||
]);
|
||||
// * Temp hashcode to satisfy constraint
|
||||
$customer->hashcode = new CrmHashcode(Uuid::uuid4());
|
||||
$customer->hashcode = new CrmHashcode(UuidHelper::v4());
|
||||
$customer->saveOrFail();
|
||||
|
||||
$employee = $this->employeeRepository->findByMatriculeAndCode(
|
||||
$input->matricule,
|
||||
$input->code
|
||||
);
|
||||
|
||||
if (! $employee) {
|
||||
throw new ModelNotFoundException('Employee not found');
|
||||
}
|
||||
|
||||
$employee->customer()->associate($customer);
|
||||
$employee->saveOrFail();
|
||||
|
||||
|
|
@ -84,21 +140,6 @@ final class RegisterCustomer implements Action
|
|||
|
||||
try {
|
||||
$result = $this->crmService->persist($crmCustomer);
|
||||
|
||||
if (! $result->hashcode) {
|
||||
throw new \UnexpectedValueException(
|
||||
'CRM did not return a hashcode for the created customer'
|
||||
);
|
||||
}
|
||||
|
||||
$customer->hashcode = CrmHashcode::fromString($result->hashcode);
|
||||
$customer->saveOrFail();
|
||||
|
||||
$customer->sendEmailVerificationNotification();
|
||||
|
||||
$this->authService->logIn($customer);
|
||||
|
||||
return $customer;
|
||||
} catch (CrmCustomerExistsException) {
|
||||
throw ValidationException::withMessages([
|
||||
'error' => trans('An account is already associated with this email address'),
|
||||
|
|
@ -109,5 +150,70 @@ final class RegisterCustomer implements Action
|
|||
'error' => trans('An error has occurred. Please try again later'),
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $result->hashcode) {
|
||||
throw new \UnexpectedValueException(
|
||||
'CRM did not return a hashcode for the created customer'
|
||||
);
|
||||
}
|
||||
|
||||
$crmHashcode = CrmHashcode::fromString($result->hashcode);
|
||||
$this->createdCrmCustomers[$inputKey] = [
|
||||
'hashcode' => $crmHashcode,
|
||||
'email' => $input->email,
|
||||
];
|
||||
|
||||
$customer->hashcode = $crmHashcode;
|
||||
$customer->saveOrFail();
|
||||
|
||||
return RegisterCustomerOutput::success($customer);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
|
||||
* @param \App\Cqs\Actions\Customers\RegisterCustomerOutput $result
|
||||
*/
|
||||
#[\Override]
|
||||
public function onSuccess(ActionInput $input, mixed $result): void
|
||||
{
|
||||
Assert::isInstanceOf($input, RegisterCustomerInput::class);
|
||||
Assert::isInstanceOf($result, RegisterCustomerOutput::class);
|
||||
|
||||
unset($this->createdCrmCustomers[spl_object_id($input)]);
|
||||
|
||||
if ($result->status !== RegisterCustomerStatus::SUCCESS || ! $result->customer instanceof Customer) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->authService->logIn($result->customer);
|
||||
|
||||
try {
|
||||
$result->customer->sendEmailVerificationNotification();
|
||||
} catch (\Throwable $e) {
|
||||
report($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
|
||||
*/
|
||||
#[\Override]
|
||||
public function onFailure(ActionInput $input, \Throwable $exception): void
|
||||
{
|
||||
Assert::isInstanceOf($input, RegisterCustomerInput::class);
|
||||
|
||||
$inputKey = spl_object_id($input);
|
||||
$createdCrm = $this->createdCrmCustomers[$inputKey] ?? null;
|
||||
unset($this->createdCrmCustomers[$inputKey]);
|
||||
|
||||
if ($createdCrm === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->crmService->deleteByHashcode($createdCrm['hashcode'], $createdCrm['email']);
|
||||
} catch (\Throwable $e) {
|
||||
report($e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
47
app/Cqs/Actions/Customers/RegisterCustomerOutput.php
Normal file
47
app/Cqs/Actions/Customers/RegisterCustomerOutput.php
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
<?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,
|
||||
);
|
||||
}
|
||||
}
|
||||
35
app/Cqs/Actions/Customers/UpdateCustomerLastLogin.php
Normal file
35
app/Cqs/Actions/Customers/UpdateCustomerLastLogin.php
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
<?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;
|
||||
}
|
||||
}
|
||||
16
app/Cqs/Actions/Customers/UpdateCustomerLastLoginInput.php
Normal file
16
app/Cqs/Actions/Customers/UpdateCustomerLastLoginInput.php
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<?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,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
|
@ -4,31 +4,30 @@ declare(strict_types=1);
|
|||
|
||||
namespace App\Cqs\Actions\Employee;
|
||||
|
||||
use App\Attributes\WithoutTransaction;
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Contracts\ActionInputEmpty;
|
||||
use App\Contracts\Repositories\EmployeeRepository;
|
||||
use App\Services\EmployeeSyncService;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Contracts\ActionInputEmpty, void>
|
||||
*/
|
||||
#[WithoutTransaction]
|
||||
final class SynchronizeEmployeesWithArcadiaApi implements Action
|
||||
{
|
||||
public function __construct(
|
||||
private readonly EmployeeRepository $employeeRepository,
|
||||
private readonly EmployeeSyncService $syncService
|
||||
) {
|
||||
}
|
||||
|
||||
/** @param \App\Contracts\ActionInputEmpty $input */
|
||||
#[\Override]
|
||||
public function __invoke(ActionInput $input): void
|
||||
{
|
||||
Assert::isAOf($input, ActionInputEmpty::class);
|
||||
|
||||
$wasLastSyncedAt = $this->employeeRepository->getMostRecentSyncDate();
|
||||
|
||||
$this->syncService->synchronize($wasLastSyncedAt);
|
||||
$this->syncService->synchronize();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,12 +6,14 @@ namespace App\Cqs\Actions\Orders;
|
|||
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use Domain\Models\ValueObjects\PickupTimeSlot;
|
||||
use Domain\Services\OrderTunnelService;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\ApplyPickTimeSlotInput, ?\Domain\Models\ValueObjects\PickupTimeSlot>
|
||||
* @implements \App\Contracts\Action<
|
||||
* \App\Cqs\Actions\Orders\ApplyPickTimeSlotInput,
|
||||
* \App\Cqs\Actions\Orders\ApplyPickTimeSlotOutput
|
||||
* >
|
||||
*/
|
||||
final class ApplyPickTimeSlot implements Action
|
||||
{
|
||||
|
|
@ -24,7 +26,7 @@ final class ApplyPickTimeSlot implements Action
|
|||
* @param \App\Cqs\Actions\Orders\ApplyPickTimeSlotInput $input
|
||||
*/
|
||||
#[\Override]
|
||||
public function __invoke(ActionInput $input): ?PickupTimeSlot
|
||||
public function __invoke(ActionInput $input): ApplyPickTimeSlotOutput
|
||||
{
|
||||
Assert::isInstanceOf($input, ApplyPickTimeSlotInput::class);
|
||||
|
||||
|
|
@ -32,11 +34,15 @@ final class ApplyPickTimeSlot implements Action
|
|||
$shop = $this->orderTunnelService->getShopForCustomer($input->shopperId);
|
||||
$timeSlots = $this->orderTunnelService->getAvailableTimeSlots($shop);
|
||||
|
||||
return $this->orderTunnelService->applyTimeSlot(
|
||||
$timeSlot = $this->orderTunnelService->applyTimeSlot(
|
||||
$builder,
|
||||
$shop,
|
||||
$input->timeslot,
|
||||
$timeSlots
|
||||
);
|
||||
|
||||
return $timeSlot !== null
|
||||
? ApplyPickTimeSlotOutput::matched($timeSlot)
|
||||
: ApplyPickTimeSlotOutput::unavailable();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
32
app/Cqs/Actions/Orders/ApplyPickTimeSlotOutput.php
Normal file
32
app/Cqs/Actions/Orders/ApplyPickTimeSlotOutput.php
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
<?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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -6,16 +6,16 @@ namespace App\Cqs\Actions\Orders;
|
|||
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use Domain\Services\OrderService as DomainOrderService;
|
||||
use Domain\Services\OrderService;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\CancelOrderInput, void>
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\CancelOrderInput, \App\Cqs\Actions\Orders\CancelOrderOutput>
|
||||
*/
|
||||
final class CancelOrder implements Action
|
||||
{
|
||||
public function __construct(
|
||||
private readonly DomainOrderService $domainOrderService,
|
||||
private readonly OrderService $orderService,
|
||||
) {
|
||||
}
|
||||
|
||||
|
|
@ -23,10 +23,16 @@ final class CancelOrder implements Action
|
|||
* @param \App\Cqs\Actions\Orders\CancelOrderInput $input
|
||||
*/
|
||||
#[\Override]
|
||||
public function __invoke(ActionInput $input): void
|
||||
public function __invoke(ActionInput $input): CancelOrderOutput
|
||||
{
|
||||
Assert::isInstanceOf($input, CancelOrderInput::class);
|
||||
|
||||
$this->domainOrderService->cancelOrder($input->order->getId());
|
||||
try {
|
||||
$this->orderService->cancelOrder($input->order->getId());
|
||||
} catch (\DomainException) {
|
||||
return CancelOrderOutput::NOT_FOUND;
|
||||
}
|
||||
|
||||
return CancelOrderOutput::CANCELLED;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
11
app/Cqs/Actions/Orders/CancelOrderOutput.php
Normal file
11
app/Cqs/Actions/Orders/CancelOrderOutput.php
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Cqs\Actions\Orders;
|
||||
|
||||
enum CancelOrderOutput
|
||||
{
|
||||
case CANCELLED;
|
||||
case NOT_FOUND;
|
||||
}
|
||||
34
app/Cqs/Actions/Orders/ClaimTodayOrderReminder.php
Normal file
34
app/Cqs/Actions/Orders/ClaimTodayOrderReminder.php
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
<?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;
|
||||
}
|
||||
}
|
||||
18
app/Cqs/Actions/Orders/ClaimTodayOrderReminderInput.php
Normal file
18
app/Cqs/Actions/Orders/ClaimTodayOrderReminderInput.php
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
<?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,
|
||||
) {
|
||||
}
|
||||
}
|
||||
43
app/Cqs/Actions/Orders/ConfirmPlacedOrder.php
Normal file
43
app/Cqs/Actions/Orders/ConfirmPlacedOrder.php
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
<?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;
|
||||
}
|
||||
}
|
||||
16
app/Cqs/Actions/Orders/ConfirmPlacedOrderInput.php
Normal file
16
app/Cqs/Actions/Orders/ConfirmPlacedOrderInput.php
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<?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,
|
||||
) {
|
||||
}
|
||||
}
|
||||
11
app/Cqs/Actions/Orders/ConfirmPlacedOrderOutput.php
Normal file
11
app/Cqs/Actions/Orders/ConfirmPlacedOrderOutput.php
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Cqs\Actions\Orders;
|
||||
|
||||
enum ConfirmPlacedOrderOutput
|
||||
{
|
||||
case CONFIRMED;
|
||||
case FAILED;
|
||||
}
|
||||
77
app/Cqs/Actions/Orders/ExportOrderToRegate.php
Normal file
77
app/Cqs/Actions/Orders/ExportOrderToRegate.php
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
<?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;
|
||||
}
|
||||
}
|
||||
16
app/Cqs/Actions/Orders/ExportOrderToRegateInput.php
Normal file
16
app/Cqs/Actions/Orders/ExportOrderToRegateInput.php
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<?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,
|
||||
) {
|
||||
}
|
||||
}
|
||||
12
app/Cqs/Actions/Orders/ExportOrderToRegateOutput.php
Normal file
12
app/Cqs/Actions/Orders/ExportOrderToRegateOutput.php
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Cqs\Actions\Orders;
|
||||
|
||||
enum ExportOrderToRegateOutput
|
||||
{
|
||||
case SENT;
|
||||
case FAILED;
|
||||
case LOCK_TIMEOUT;
|
||||
}
|
||||
43
app/Cqs/Actions/Orders/FailPendingOrder.php
Normal file
43
app/Cqs/Actions/Orders/FailPendingOrder.php
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
<?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;
|
||||
}
|
||||
}
|
||||
16
app/Cqs/Actions/Orders/FailPendingOrderInput.php
Normal file
16
app/Cqs/Actions/Orders/FailPendingOrderInput.php
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<?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,
|
||||
) {
|
||||
}
|
||||
}
|
||||
12
app/Cqs/Actions/Orders/FailPendingOrderOutput.php
Normal file
12
app/Cqs/Actions/Orders/FailPendingOrderOutput.php
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Cqs\Actions\Orders;
|
||||
|
||||
enum FailPendingOrderOutput
|
||||
{
|
||||
case FAILED;
|
||||
case NOT_FOUND;
|
||||
case INVALID_STATUS;
|
||||
}
|
||||
53
app/Cqs/Actions/Orders/FailStalePendingOrders.php
Normal file
53
app/Cqs/Actions/Orders/FailStalePendingOrders.php
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
<?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;
|
||||
}
|
||||
}
|
||||
17
app/Cqs/Actions/Orders/FailStalePendingOrdersInput.php
Normal file
17
app/Cqs/Actions/Orders/FailStalePendingOrdersInput.php
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
<?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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
<?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;
|
||||
}
|
||||
}
|
||||
100
app/Cqs/Actions/Orders/PlacePendingOrder.php
Normal file
100
app/Cqs/Actions/Orders/PlacePendingOrder.php
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
<?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);
|
||||
}
|
||||
}
|
||||
|
|
@ -7,7 +7,7 @@ namespace App\Cqs\Actions\Orders;
|
|||
use App\Contracts\ActionInput;
|
||||
use Domain\Models\ValueObjects\Entities\ShopperId;
|
||||
|
||||
final readonly class FinalizeOrderInput implements ActionInput
|
||||
final readonly class PlacePendingOrderInput implements ActionInput
|
||||
{
|
||||
public function __construct(
|
||||
public ?ShopperId $shopperId = null,
|
||||
84
app/Cqs/Actions/Orders/PlacePendingOrderOutput.php
Normal file
84
app/Cqs/Actions/Orders/PlacePendingOrderOutput.php
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
<?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,
|
||||
);
|
||||
}
|
||||
}
|
||||
32
app/Cqs/Actions/Orders/ReleaseTodayOrderReminder.php
Normal file
32
app/Cqs/Actions/Orders/ReleaseTodayOrderReminder.php
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
<?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;
|
||||
}
|
||||
}
|
||||
18
app/Cqs/Actions/Orders/ReleaseTodayOrderReminderInput.php
Normal file
18
app/Cqs/Actions/Orders/ReleaseTodayOrderReminderInput.php
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
<?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,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
<?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));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
<?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);
|
||||
}
|
||||
}
|
||||
|
|
@ -11,7 +11,10 @@ use App\Services\ArcadiaIncoService;
|
|||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\ProductIncos\AssociateProductIncoInput, \App\Models\ProductInco>
|
||||
* @implements \App\Contracts\Action<
|
||||
* \App\Cqs\Actions\ProductIncos\AssociateProductIncoInput,
|
||||
* \App\Cqs\Actions\ProductIncos\AssociateProductIncoOutput
|
||||
* >
|
||||
*/
|
||||
final class AssociateProductInco implements Action
|
||||
{
|
||||
|
|
@ -24,36 +27,34 @@ final class AssociateProductInco implements Action
|
|||
* @param \App\Cqs\Actions\ProductIncos\AssociateProductIncoInput $input
|
||||
*/
|
||||
#[\Override]
|
||||
public function __invoke(ActionInput $input): ProductInco
|
||||
public function __invoke(ActionInput $input): AssociateProductIncoOutput
|
||||
{
|
||||
Assert::isInstanceOf($input, AssociateProductIncoInput::class);
|
||||
|
||||
$incoData = $this->arcadiaIncoService->fetchInco($input->no_art);
|
||||
|
||||
if ($incoData === null) {
|
||||
throw new \RuntimeException(sprintf('INCO sheet #%d was not found on Arcadia API.', $input->no_art));
|
||||
try {
|
||||
$incoData = $this->arcadiaIncoService->fetchInco($input->no_art);
|
||||
} catch (\RuntimeException $e) {
|
||||
return AssociateProductIncoOutput::apiError($e->getMessage());
|
||||
}
|
||||
|
||||
if ($incoData === null) {
|
||||
return AssociateProductIncoOutput::notFoundOnArcadia($input->no_art);
|
||||
}
|
||||
|
||||
$productId = $input->productId->value->toString();
|
||||
|
||||
// * Remove existing product_inco for this product if present
|
||||
$existing = ProductInco::query()->where('product_id', $input->product->id)->first();
|
||||
$existing = ProductInco::query()->where('product_id', $productId)->first();
|
||||
if ($existing !== null) {
|
||||
$existing->delete();
|
||||
}
|
||||
|
||||
$inco = new ProductInco();
|
||||
$inco->product_id = (string) $input->product->id;
|
||||
$inco->no_art = $incoData->noArt;
|
||||
$inco->ingredients = $incoData->ingredients;
|
||||
$inco->preparation = $incoData->preparation;
|
||||
$inco->servings = $incoData->servings;
|
||||
$inco->allergens = $incoData->allergens;
|
||||
$inco->selling_argument = $incoData->sellingArgument;
|
||||
$inco->nutriscore = $incoData->nutriscore;
|
||||
$inco->nutriscore_args = $incoData->nutriscoreArgs;
|
||||
$inco->nutrition = $incoData->nutrition;
|
||||
|
||||
$inco = new ProductInco();
|
||||
$inco->product_id = $productId;
|
||||
$inco->no_art = $incoData->noArt;
|
||||
$inco->hydrateFromArcadiaDto($incoData);
|
||||
$inco->saveOrFail();
|
||||
|
||||
return $inco;
|
||||
return AssociateProductIncoOutput::success($inco);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,13 +5,13 @@ declare(strict_types=1);
|
|||
namespace App\Cqs\Actions\ProductIncos;
|
||||
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Models\Product;
|
||||
use Domain\Models\ValueObjects\Entities\ProductId;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
final readonly class AssociateProductIncoInput implements ActionInput
|
||||
{
|
||||
public function __construct(
|
||||
public Product $product,
|
||||
public ProductId $productId,
|
||||
public int $no_art,
|
||||
) {
|
||||
Assert::greaterThanEq($this->no_art, 1, 'The INCO article number must be greater than or equal to 1.');
|
||||
|
|
|
|||
42
app/Cqs/Actions/ProductIncos/AssociateProductIncoOutput.php
Normal file
42
app/Cqs/Actions/ProductIncos/AssociateProductIncoOutput.php
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
<?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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -11,7 +11,10 @@ use App\Services\ArcadiaIncoService;
|
|||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\ProductIncos\SyncProductIncoInput, \App\Models\ProductInco>
|
||||
* @implements \App\Contracts\Action<
|
||||
* \App\Cqs\Actions\ProductIncos\SyncProductIncoInput,
|
||||
* \App\Cqs\Actions\ProductIncos\SyncProductIncoOutput
|
||||
* >
|
||||
*/
|
||||
final class SyncProductInco implements Action
|
||||
{
|
||||
|
|
@ -24,31 +27,31 @@ final class SyncProductInco implements Action
|
|||
* @param \App\Cqs\Actions\ProductIncos\SyncProductIncoInput $input
|
||||
*/
|
||||
#[\Override]
|
||||
public function __invoke(ActionInput $input): ProductInco
|
||||
public function __invoke(ActionInput $input): SyncProductIncoOutput
|
||||
{
|
||||
Assert::isInstanceOf($input, SyncProductIncoInput::class);
|
||||
|
||||
$inco = $input->product->inco;
|
||||
$inco = ProductInco::query()
|
||||
->where('product_id', $input->productId->value->toString())
|
||||
->first();
|
||||
|
||||
if ($inco === null) {
|
||||
throw new \RuntimeException('Product does not have an associated INCO sheet to sync.');
|
||||
return SyncProductIncoOutput::notAssociated();
|
||||
}
|
||||
|
||||
try {
|
||||
$incoData = $this->arcadiaIncoService->fetchInco($inco->no_art);
|
||||
} catch (\RuntimeException $e) {
|
||||
return SyncProductIncoOutput::apiError($e->getMessage());
|
||||
}
|
||||
|
||||
$incoData = $this->arcadiaIncoService->fetchInco($inco->no_art);
|
||||
if ($incoData === null) {
|
||||
throw new \RuntimeException(sprintf('INCO sheet #%d was not found on Arcadia API.', $inco->no_art));
|
||||
return SyncProductIncoOutput::notFoundOnArcadia($inco->no_art);
|
||||
}
|
||||
|
||||
$inco->ingredients = $incoData->ingredients;
|
||||
$inco->preparation = $incoData->preparation;
|
||||
$inco->servings = $incoData->servings;
|
||||
$inco->allergens = $incoData->allergens;
|
||||
$inco->selling_argument = $incoData->sellingArgument;
|
||||
$inco->nutriscore = $incoData->nutriscore;
|
||||
$inco->nutriscore_args = $incoData->nutriscoreArgs;
|
||||
$inco->nutrition = $incoData->nutrition;
|
||||
|
||||
$inco->hydrateFromArcadiaDto($incoData);
|
||||
$inco->saveOrFail();
|
||||
|
||||
return $inco;
|
||||
return SyncProductIncoOutput::success($inco);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,12 +5,12 @@ declare(strict_types=1);
|
|||
namespace App\Cqs\Actions\ProductIncos;
|
||||
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Models\Product;
|
||||
use Domain\Models\ValueObjects\Entities\ProductId;
|
||||
|
||||
final readonly class SyncProductIncoInput implements ActionInput
|
||||
{
|
||||
public function __construct(
|
||||
public Product $product,
|
||||
public ProductId $productId,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
|
|
|||
50
app/Cqs/Actions/ProductIncos/SyncProductIncoOutput.php
Normal file
50
app/Cqs/Actions/ProductIncos/SyncProductIncoOutput.php
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
<?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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -4,17 +4,20 @@ declare(strict_types=1);
|
|||
|
||||
namespace App\Cqs\Actions\ProductIncos;
|
||||
|
||||
use App\Attributes\WithoutTransaction;
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Contracts\ActionInputEmpty;
|
||||
use App\Models\ProductInco;
|
||||
use App\Services\ArcadiaIncoService;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Contracts\ActionInputEmpty, int>
|
||||
*/
|
||||
#[WithoutTransaction]
|
||||
final class SynchronizeProductIncosWithArcadiaApi implements Action
|
||||
{
|
||||
public function __construct(
|
||||
|
|
@ -38,7 +41,20 @@ final class SynchronizeProductIncosWithArcadiaApi implements Action
|
|||
$incos = ProductInco::query()->get();
|
||||
|
||||
foreach ($incos as $inco) {
|
||||
$incoData = $this->arcadiaIncoService->fetchInco($inco->no_art);
|
||||
try {
|
||||
$incoData = $this->arcadiaIncoService->fetchInco($inco->no_art);
|
||||
} catch (\Throwable $e) {
|
||||
$this->logger->error(
|
||||
"Failed to fetch ProductInco #{$inco->id} (no_art: {$inco->no_art}): {$e->getMessage()}",
|
||||
[
|
||||
'product_inco_id' => $inco->id,
|
||||
'no_art' => $inco->no_art,
|
||||
'exception' => $e,
|
||||
]
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($incoData === null) {
|
||||
$this->logger->warning("Could not sync ProductInco #{$inco->id} (no_art: {$inco->no_art}): not found on Arcadia.");
|
||||
|
|
@ -46,16 +62,10 @@ final class SynchronizeProductIncosWithArcadiaApi implements Action
|
|||
continue;
|
||||
}
|
||||
|
||||
$inco->ingredients = $incoData->ingredients;
|
||||
$inco->preparation = $incoData->preparation;
|
||||
$inco->servings = $incoData->servings;
|
||||
$inco->allergens = $incoData->allergens;
|
||||
$inco->selling_argument = $incoData->sellingArgument;
|
||||
$inco->nutriscore = $incoData->nutriscore;
|
||||
$inco->nutriscore_args = $incoData->nutriscoreArgs;
|
||||
$inco->nutrition = $incoData->nutrition;
|
||||
|
||||
$inco->saveOrFail();
|
||||
DB::transaction(static function () use ($inco, $incoData): void {
|
||||
$inco->hydrateFromArcadiaDto($incoData);
|
||||
$inco->saveOrFail();
|
||||
});
|
||||
$updatedCount++;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -6,17 +6,36 @@ namespace App\Cqs\Actions\Products;
|
|||
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Contracts\HandlesFailure;
|
||||
use App\Contracts\HandlesSuccess;
|
||||
use App\Lib\PublicS3Disk;
|
||||
use App\Models\Product;
|
||||
use App\Models\Tag;
|
||||
use App\Services\ImageOptimizerService;
|
||||
use App\Traits\TracksPendingStoragePaths;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
use Illuminate\Support\Str;
|
||||
use Uwil\Storage\Contracts\StorageService;
|
||||
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\Products\CreateProductInput, \App\Models\Product>
|
||||
* @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Products\CreateProductInput, \App\Models\Product>
|
||||
* @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Products\CreateProductInput>
|
||||
*/
|
||||
final class CreateProduct implements Action
|
||||
final class CreateProduct implements Action, HandlesFailure, HandlesSuccess
|
||||
{
|
||||
use TracksPendingStoragePaths;
|
||||
|
||||
public function __construct(
|
||||
protected readonly StorageService $storageService,
|
||||
protected readonly PublicS3Disk $s3Disk,
|
||||
protected readonly ImageOptimizerService $imageOptimizerService,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Products\CreateProductInput $input
|
||||
*/
|
||||
|
|
@ -44,14 +63,18 @@ final class CreateProduct implements Action
|
|||
$product->star = $input->star;
|
||||
$product->status = $input->status;
|
||||
|
||||
if ($input->picture !== null) {
|
||||
$product->setAttribute('picture', $input->picture);
|
||||
if ($input->picture instanceof UploadedFile) {
|
||||
$picturePath = $this->storeFile($input->picture);
|
||||
$product->picture = $picturePath;
|
||||
$this->trackUploadedPath($input, $picturePath);
|
||||
}
|
||||
$product->picture_alt = (string) $input->pictureAlt;
|
||||
$product->picture_title = (string) $input->pictureTitle;
|
||||
|
||||
if ($input->pictureLarge !== null) {
|
||||
$product->setAttribute('picture_large', $input->pictureLarge);
|
||||
if ($input->pictureLarge instanceof UploadedFile) {
|
||||
$pictureLargePath = $this->storeFile($input->pictureLarge);
|
||||
$product->picture_large = $pictureLargePath;
|
||||
$this->trackUploadedPath($input, $pictureLargePath);
|
||||
}
|
||||
$product->picture_large_alt = (string) $input->pictureLargeAlt;
|
||||
$product->picture_large_title = (string) $input->pictureLargeTitle;
|
||||
|
|
@ -106,4 +129,27 @@ final class CreateProduct implements Action
|
|||
|
||||
$product->products()->sync($syncData);
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onSuccess(ActionInput $input, mixed $result): void
|
||||
{
|
||||
$this->clearTrackedPaths($input);
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onFailure(ActionInput $input, \Throwable $exception): void
|
||||
{
|
||||
foreach ($this->pullUploadedPaths($input) as $path) {
|
||||
if ($this->storageService->fileExistsOnDisk($path, $this->s3Disk->disk)) {
|
||||
$this->storageService->removeFromDisk($path, $this->s3Disk->disk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected function storeFile(UploadedFile $file): StorageFilePath
|
||||
{
|
||||
$optimized = $this->imageOptimizerService->optimize($file);
|
||||
|
||||
return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ use Domain\Enums\SellUnit;
|
|||
use Domain\Enums\TaxRate;
|
||||
use Domain\Enums\Units\InvoicingUnit;
|
||||
use Domain\Enums\Units\OrderUnit;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Money\Money;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
|
|
@ -38,10 +39,10 @@ final readonly class CreateProductInput implements ActionInput
|
|||
public ?CarbonInterface $orderableEnd = null,
|
||||
public bool $star = false,
|
||||
public bool $status = false,
|
||||
public mixed $picture = null,
|
||||
public ?UploadedFile $picture = null,
|
||||
public ?string $pictureAlt = null,
|
||||
public ?string $pictureTitle = null,
|
||||
public mixed $pictureLarge = null,
|
||||
public ?UploadedFile $pictureLarge = null,
|
||||
public ?string $pictureLargeAlt = null,
|
||||
public ?string $pictureLargeTitle = null,
|
||||
public array $tags = [],
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ namespace App\Cqs\Actions\Products;
|
|||
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Models\Product;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
|
|
@ -21,6 +22,15 @@ final class DeleteProduct implements Action
|
|||
{
|
||||
Assert::isInstanceOf($input, DeleteProductInput::class);
|
||||
|
||||
return (bool) $input->product->deleteOrFail();
|
||||
$product = Product::query()
|
||||
->where('id', $input->productId->value->toString())
|
||||
->first();
|
||||
|
||||
if (! $product) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// NOTE: Product uses SoftDeletes so it will not be permanently removed from the database.
|
||||
return (bool) $product->deleteOrFail();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,12 +5,12 @@ declare(strict_types=1);
|
|||
namespace App\Cqs\Actions\Products;
|
||||
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Models\Product;
|
||||
use Domain\Models\ValueObjects\Entities\ProductId;
|
||||
|
||||
final readonly class DeleteProductInput implements ActionInput
|
||||
{
|
||||
public function __construct(
|
||||
public Product $product,
|
||||
public ProductId $productId,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,17 +6,31 @@ namespace App\Cqs\Actions\Products;
|
|||
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Contracts\HandlesFailure;
|
||||
use App\Contracts\HandlesSuccess;
|
||||
use App\Models\Product;
|
||||
use App\Models\Tag;
|
||||
use App\Services\PublicImageStorageService;
|
||||
use App\Traits\TracksPendingStoragePaths;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
use Illuminate\Support\Str;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\Products\UpdateProductInput, \App\Models\Product>
|
||||
* @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Products\UpdateProductInput, \App\Models\Product>
|
||||
* @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Products\UpdateProductInput>
|
||||
*/
|
||||
final class UpdateProduct implements Action
|
||||
final class UpdateProduct implements Action, HandlesFailure, HandlesSuccess
|
||||
{
|
||||
use TracksPendingStoragePaths;
|
||||
|
||||
public function __construct(
|
||||
private readonly PublicImageStorageService $publicImageStorageService,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Products\UpdateProductInput $input
|
||||
*/
|
||||
|
|
@ -25,7 +39,13 @@ final class UpdateProduct implements Action
|
|||
{
|
||||
Assert::isInstanceOf($input, UpdateProductInput::class);
|
||||
|
||||
$product = $input->product;
|
||||
$product = Product::query()
|
||||
->where('id', $input->productId->value->toString())
|
||||
->firstOrFail();
|
||||
$previousPicture = $product->picture;
|
||||
$previousPictureLarge = $product->picture_large;
|
||||
$newPicture = null;
|
||||
$newPictureLarge = null;
|
||||
$product->name = $input->name;
|
||||
$product->short_description = $input->shortDescription;
|
||||
$product->description = $input->description;
|
||||
|
|
@ -44,14 +64,18 @@ final class UpdateProduct implements Action
|
|||
$product->star = $input->star;
|
||||
$product->status = $input->status;
|
||||
|
||||
if ($input->picture !== null) {
|
||||
$product->setAttribute('picture', $input->picture);
|
||||
if ($input->picture instanceof UploadedFile) {
|
||||
$newPicture = $this->publicImageStorageService->store($input->picture);
|
||||
$product->setAttribute('picture', $newPicture);
|
||||
$this->trackUploadedPath($input, $newPicture);
|
||||
}
|
||||
$product->picture_alt = (string) $input->pictureAlt;
|
||||
$product->picture_title = (string) $input->pictureTitle;
|
||||
|
||||
if ($input->pictureLarge !== null) {
|
||||
$product->setAttribute('picture_large', $input->pictureLarge);
|
||||
if ($input->pictureLarge instanceof UploadedFile) {
|
||||
$newPictureLarge = $this->publicImageStorageService->store($input->pictureLarge);
|
||||
$product->setAttribute('picture_large', $newPictureLarge);
|
||||
$this->trackUploadedPath($input, $newPictureLarge);
|
||||
}
|
||||
$product->picture_large_alt = (string) $input->pictureLargeAlt;
|
||||
$product->picture_large_title = (string) $input->pictureLargeTitle;
|
||||
|
|
@ -61,9 +85,28 @@ final class UpdateProduct implements Action
|
|||
$this->syncTags($input->tags, $product);
|
||||
$this->syncAssociatedProducts($input->associatedProductsIds, $product);
|
||||
|
||||
$this->trackReplacedPath($input, $previousPicture, $newPicture);
|
||||
$this->trackReplacedPath($input, $previousPictureLarge, $newPictureLarge);
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onSuccess(ActionInput $input, mixed $result): void
|
||||
{
|
||||
foreach ($this->pullObsoletePaths($input) as $path) {
|
||||
$this->publicImageStorageService->deleteIfExists($path);
|
||||
}
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onFailure(ActionInput $input, \Throwable $exception): void
|
||||
{
|
||||
foreach ($this->pullUploadedPaths($input) as $path) {
|
||||
$this->publicImageStorageService->deleteIfExists($path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array{id?: int|string, label: string}> $tags
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -5,14 +5,16 @@ declare(strict_types=1);
|
|||
namespace App\Cqs\Actions\Products;
|
||||
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Models\Product;
|
||||
use Carbon\CarbonInterface;
|
||||
use Domain\Enums\ProductBrand;
|
||||
use Domain\Enums\SellUnit;
|
||||
use Domain\Enums\TaxRate;
|
||||
use Domain\Enums\Units\InvoicingUnit;
|
||||
use Domain\Enums\Units\OrderUnit;
|
||||
use Domain\Models\ValueObjects\Entities\ProductId;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Money\Money;
|
||||
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
final readonly class UpdateProductInput implements ActionInput
|
||||
|
|
@ -22,7 +24,7 @@ final readonly class UpdateProductInput implements ActionInput
|
|||
* @param list<string> $associatedProductsIds
|
||||
*/
|
||||
public function __construct(
|
||||
public Product $product,
|
||||
public ProductId $productId,
|
||||
public string $name,
|
||||
public string $shortDescription,
|
||||
public string $description,
|
||||
|
|
@ -40,10 +42,10 @@ final readonly class UpdateProductInput implements ActionInput
|
|||
public ?CarbonInterface $orderableEnd = null,
|
||||
public bool $star = false,
|
||||
public bool $status = false,
|
||||
public mixed $picture = null,
|
||||
public UploadedFile | StorageFilePath | null $picture = null,
|
||||
public ?string $pictureAlt = null,
|
||||
public ?string $pictureTitle = null,
|
||||
public mixed $pictureLarge = null,
|
||||
public UploadedFile | StorageFilePath | null $pictureLarge = null,
|
||||
public ?string $pictureLargeAlt = null,
|
||||
public ?string $pictureLargeTitle = null,
|
||||
public array $tags = [],
|
||||
|
|
|
|||
|
|
@ -6,14 +6,33 @@ namespace App\Cqs\Actions\Ranges;
|
|||
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Contracts\HandlesFailure;
|
||||
use App\Contracts\HandlesSuccess;
|
||||
use App\Lib\PublicS3Disk;
|
||||
use App\Models\Range;
|
||||
use App\Services\ImageOptimizerService;
|
||||
use App\Traits\TracksPendingStoragePaths;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Uwil\Storage\Contracts\StorageService;
|
||||
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\Ranges\CreateRangeInput, \App\Models\Range>
|
||||
* @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Ranges\CreateRangeInput, \App\Models\Range>
|
||||
* @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Ranges\CreateRangeInput>
|
||||
*/
|
||||
final class CreateRange implements Action
|
||||
final class CreateRange implements Action, HandlesFailure, HandlesSuccess
|
||||
{
|
||||
use TracksPendingStoragePaths;
|
||||
|
||||
public function __construct(
|
||||
protected readonly StorageService $storageService,
|
||||
protected readonly PublicS3Disk $s3Disk,
|
||||
protected readonly ImageOptimizerService $imageOptimizerService,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Ranges\CreateRangeInput $input
|
||||
*/
|
||||
|
|
@ -30,8 +49,10 @@ final class CreateRange implements Action
|
|||
'status' => $input->status,
|
||||
];
|
||||
|
||||
if ($input->picture !== null) {
|
||||
$attributes['picture'] = $input->picture;
|
||||
if ($input->picture instanceof UploadedFile) {
|
||||
$storedPath = $this->storeFile($input->picture);
|
||||
$attributes['picture'] = $storedPath;
|
||||
$this->trackUploadedPath($input, $storedPath);
|
||||
}
|
||||
|
||||
$range = new Range();
|
||||
|
|
@ -40,4 +61,27 @@ final class CreateRange implements Action
|
|||
|
||||
return $range;
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onSuccess(ActionInput $input, mixed $result): void
|
||||
{
|
||||
$this->clearTrackedPaths($input);
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onFailure(ActionInput $input, \Throwable $exception): void
|
||||
{
|
||||
foreach ($this->pullUploadedPaths($input) as $path) {
|
||||
if ($this->storageService->fileExistsOnDisk($path, $this->s3Disk->disk)) {
|
||||
$this->storageService->removeFromDisk($path, $this->s3Disk->disk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected function storeFile(UploadedFile $file): StorageFilePath
|
||||
{
|
||||
$optimized = $this->imageOptimizerService->optimize($file);
|
||||
|
||||
return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ final readonly class CreateRangeInput implements ActionInput
|
|||
public function __construct(
|
||||
public string $name,
|
||||
public ?string $description,
|
||||
public UploadedFile | string | null $picture,
|
||||
public ?UploadedFile $picture,
|
||||
public PictureMetadata $pictureMetadata,
|
||||
public bool $status,
|
||||
) {
|
||||
|
|
|
|||
|
|
@ -6,13 +6,28 @@ namespace App\Cqs\Actions\Ranges;
|
|||
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Contracts\HandlesFailure;
|
||||
use App\Contracts\HandlesSuccess;
|
||||
use App\Lib\PublicS3Disk;
|
||||
use App\Traits\TracksPendingStoragePaths;
|
||||
use Uwil\Storage\Contracts\StorageService;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\Ranges\DeleteRangeInput, bool>
|
||||
* @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Ranges\DeleteRangeInput, bool>
|
||||
* @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Ranges\DeleteRangeInput>
|
||||
*/
|
||||
final class DeleteRange implements Action
|
||||
final class DeleteRange implements Action, HandlesFailure, HandlesSuccess
|
||||
{
|
||||
use TracksPendingStoragePaths;
|
||||
|
||||
public function __construct(
|
||||
protected readonly StorageService $storageService,
|
||||
protected readonly PublicS3Disk $s3Disk,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Ranges\DeleteRangeInput $input
|
||||
*/
|
||||
|
|
@ -21,6 +36,29 @@ final class DeleteRange implements Action
|
|||
{
|
||||
Assert::isInstanceOf($input, DeleteRangeInput::class);
|
||||
|
||||
return (bool) $input->range->deleteOrFail();
|
||||
$picture = $input->range->picture;
|
||||
$deletion = (bool) $input->range->deleteOrFail();
|
||||
|
||||
if ($deletion) {
|
||||
$this->trackObsoletePath($input, $picture);
|
||||
}
|
||||
|
||||
return $deletion;
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onSuccess(ActionInput $input, mixed $result): void
|
||||
{
|
||||
foreach ($this->pullObsoletePaths($input) as $path) {
|
||||
if ($this->storageService->fileExistsOnDisk($path, $this->s3Disk->disk)) {
|
||||
$this->storageService->removeFromDisk($path, $this->s3Disk->disk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onFailure(ActionInput $input, \Throwable $exception): void
|
||||
{
|
||||
$this->clearTrackedPaths($input);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,14 +6,28 @@ namespace App\Cqs\Actions\Ranges;
|
|||
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Contracts\HandlesFailure;
|
||||
use App\Contracts\HandlesSuccess;
|
||||
use App\Models\Range;
|
||||
use App\Services\PublicImageStorageService;
|
||||
use App\Traits\TracksPendingStoragePaths;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\Ranges\UpdateRangeInput, \App\Models\Range>
|
||||
* @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Ranges\UpdateRangeInput, \App\Models\Range>
|
||||
* @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Ranges\UpdateRangeInput>
|
||||
*/
|
||||
final class UpdateRange implements Action
|
||||
final class UpdateRange implements Action, HandlesFailure, HandlesSuccess
|
||||
{
|
||||
use TracksPendingStoragePaths;
|
||||
|
||||
public function __construct(
|
||||
private readonly PublicImageStorageService $publicImageStorageService,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Ranges\UpdateRangeInput $input
|
||||
*/
|
||||
|
|
@ -22,6 +36,9 @@ final class UpdateRange implements Action
|
|||
{
|
||||
Assert::isInstanceOf($input, UpdateRangeInput::class);
|
||||
|
||||
$previousPicture = $input->range->picture;
|
||||
$newPicture = null;
|
||||
|
||||
$attributes = [
|
||||
'name' => $input->name,
|
||||
'description' => $input->description,
|
||||
|
|
@ -30,14 +47,34 @@ final class UpdateRange implements Action
|
|||
'status' => $input->status,
|
||||
];
|
||||
|
||||
if ($input->picture !== null) {
|
||||
$attributes['picture'] = $input->picture;
|
||||
if ($input->picture instanceof UploadedFile) {
|
||||
$newPicture = $this->publicImageStorageService->store($input->picture);
|
||||
$attributes['picture'] = $newPicture;
|
||||
$this->trackUploadedPath($input, $newPicture);
|
||||
}
|
||||
|
||||
$range = $input->range;
|
||||
$range->fill($attributes);
|
||||
$range->saveOrFail();
|
||||
|
||||
$this->trackReplacedPath($input, $previousPicture, $newPicture);
|
||||
|
||||
return $range;
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onSuccess(ActionInput $input, mixed $result): void
|
||||
{
|
||||
foreach ($this->pullObsoletePaths($input) as $path) {
|
||||
$this->publicImageStorageService->deleteIfExists($path);
|
||||
}
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onFailure(ActionInput $input, \Throwable $exception): void
|
||||
{
|
||||
foreach ($this->pullUploadedPaths($input) as $path) {
|
||||
$this->publicImageStorageService->deleteIfExists($path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ use App\Contracts\ActionInput;
|
|||
use App\Models\Range;
|
||||
use Domain\Models\ValueObjects\PictureMetadata;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
final readonly class UpdateRangeInput implements ActionInput
|
||||
|
|
@ -16,7 +17,7 @@ final readonly class UpdateRangeInput implements ActionInput
|
|||
public Range $range,
|
||||
public string $name,
|
||||
public ?string $description,
|
||||
public UploadedFile | string | null $picture,
|
||||
public UploadedFile | StorageFilePath | null $picture,
|
||||
public PictureMetadata $pictureMetadata,
|
||||
public bool $status,
|
||||
) {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,9 @@ namespace App\Cqs\Actions\Shops;
|
|||
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Models\PickupException;
|
||||
use App\Models\Shop;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
|
|
@ -37,6 +39,15 @@ final class CreateShop implements Action
|
|||
$shop->default = $input->default;
|
||||
$shop->saveOrFail();
|
||||
|
||||
$publicHolidays = PickupException::query()
|
||||
->where('auto_updated', true)
|
||||
->where('date', '>=', Date::now('Europe/Paris')->startOfYear()->format('Y-m-d'))
|
||||
->get();
|
||||
|
||||
if ($publicHolidays->isNotEmpty()) {
|
||||
$shop->pickupExceptions()->syncWithoutDetaching($publicHolidays);
|
||||
}
|
||||
|
||||
return $shop;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,15 +6,34 @@ namespace App\Cqs\Actions\Slides;
|
|||
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Contracts\HandlesFailure;
|
||||
use App\Contracts\HandlesSuccess;
|
||||
use App\Lib\PublicS3Disk;
|
||||
use App\Models\Slide;
|
||||
use App\Services\ImageOptimizerService;
|
||||
use App\Traits\TracksPendingStoragePaths;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Uwil\Storage\Contracts\StorageService;
|
||||
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\Slides\CreateSlideInput, \App\Models\Slide>
|
||||
* @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Slides\CreateSlideInput, \App\Models\Slide>
|
||||
* @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Slides\CreateSlideInput>
|
||||
*/
|
||||
final class CreateSlide implements Action
|
||||
final class CreateSlide implements Action, HandlesFailure, HandlesSuccess
|
||||
{
|
||||
use TracksPendingStoragePaths;
|
||||
|
||||
public function __construct(
|
||||
protected readonly StorageService $storageService,
|
||||
protected readonly PublicS3Disk $s3Disk,
|
||||
protected readonly ImageOptimizerService $imageOptimizerService,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Slides\CreateSlideInput $input
|
||||
*/
|
||||
|
|
@ -36,8 +55,10 @@ final class CreateSlide implements Action
|
|||
'date_end' => $input->period->end !== null ? Carbon::instance($input->period->end) : null,
|
||||
];
|
||||
|
||||
if ($input->picture !== null) {
|
||||
$attributes['picture'] = $input->picture;
|
||||
if ($input->picture instanceof UploadedFile) {
|
||||
$storedPath = $this->storeFile($input->picture);
|
||||
$attributes['picture'] = $storedPath;
|
||||
$this->trackUploadedPath($input, $storedPath);
|
||||
}
|
||||
|
||||
$slide = new Slide();
|
||||
|
|
@ -46,4 +67,27 @@ final class CreateSlide implements Action
|
|||
|
||||
return $slide;
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onSuccess(ActionInput $input, mixed $result): void
|
||||
{
|
||||
$this->clearTrackedPaths($input);
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onFailure(ActionInput $input, \Throwable $exception): void
|
||||
{
|
||||
foreach ($this->pullUploadedPaths($input) as $path) {
|
||||
if ($this->storageService->fileExistsOnDisk($path, $this->s3Disk->disk)) {
|
||||
$this->storageService->removeFromDisk($path, $this->s3Disk->disk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected function storeFile(UploadedFile $file): StorageFilePath
|
||||
{
|
||||
$optimized = $this->imageOptimizerService->optimize($file);
|
||||
|
||||
return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ final readonly class CreateSlideInput implements ActionInput
|
|||
public function __construct(
|
||||
public string $title,
|
||||
public ?string $text = null,
|
||||
public UploadedFile | string | null $picture = null,
|
||||
public ?UploadedFile $picture = null,
|
||||
public ?string $pictureAlt = null,
|
||||
public ?string $pictureTitle = null,
|
||||
public ?string $link = null,
|
||||
|
|
|
|||
|
|
@ -6,13 +6,28 @@ namespace App\Cqs\Actions\Slides;
|
|||
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Contracts\HandlesFailure;
|
||||
use App\Contracts\HandlesSuccess;
|
||||
use App\Lib\PublicS3Disk;
|
||||
use App\Traits\TracksPendingStoragePaths;
|
||||
use Uwil\Storage\Contracts\StorageService;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\Slides\DeleteSlideInput, bool>
|
||||
* @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Slides\DeleteSlideInput, bool>
|
||||
* @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Slides\DeleteSlideInput>
|
||||
*/
|
||||
final class DeleteSlide implements Action
|
||||
final class DeleteSlide implements Action, HandlesFailure, HandlesSuccess
|
||||
{
|
||||
use TracksPendingStoragePaths;
|
||||
|
||||
public function __construct(
|
||||
private readonly StorageService $storageService,
|
||||
private readonly PublicS3Disk $s3Disk,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Slides\DeleteSlideInput $input
|
||||
*/
|
||||
|
|
@ -21,6 +36,29 @@ final class DeleteSlide implements Action
|
|||
{
|
||||
Assert::isInstanceOf($input, DeleteSlideInput::class);
|
||||
|
||||
return (bool) $input->slide->deleteOrFail();
|
||||
$picture = $input->slide->picture;
|
||||
$deletion = (bool) $input->slide->deleteOrFail();
|
||||
|
||||
if ($deletion) {
|
||||
$this->trackObsoletePath($input, $picture);
|
||||
}
|
||||
|
||||
return $deletion;
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onSuccess(ActionInput $input, mixed $result): void
|
||||
{
|
||||
foreach ($this->pullObsoletePaths($input) as $path) {
|
||||
if ($this->storageService->fileExistsOnDisk($path, $this->s3Disk->disk)) {
|
||||
$this->storageService->removeFromDisk($path, $this->s3Disk->disk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onFailure(ActionInput $input, \Throwable $exception): void
|
||||
{
|
||||
$this->clearTrackedPaths($input);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,15 +6,29 @@ namespace App\Cqs\Actions\Slides;
|
|||
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Contracts\HandlesFailure;
|
||||
use App\Contracts\HandlesSuccess;
|
||||
use App\Models\Slide;
|
||||
use App\Services\PublicImageStorageService;
|
||||
use App\Traits\TracksPendingStoragePaths;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\Slides\UpdateSlideInput, \App\Models\Slide>
|
||||
* @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Slides\UpdateSlideInput, \App\Models\Slide>
|
||||
* @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Slides\UpdateSlideInput>
|
||||
*/
|
||||
final class UpdateSlide implements Action
|
||||
final class UpdateSlide implements Action, HandlesFailure, HandlesSuccess
|
||||
{
|
||||
use TracksPendingStoragePaths;
|
||||
|
||||
public function __construct(
|
||||
private readonly PublicImageStorageService $publicImageStorageService,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Slides\UpdateSlideInput $input
|
||||
*/
|
||||
|
|
@ -23,6 +37,9 @@ final class UpdateSlide implements Action
|
|||
{
|
||||
Assert::isInstanceOf($input, UpdateSlideInput::class);
|
||||
|
||||
$previousPicture = $input->slide->picture;
|
||||
$newPicture = null;
|
||||
|
||||
$attributes = [
|
||||
'title' => $input->title,
|
||||
'text' => $input->text,
|
||||
|
|
@ -36,14 +53,34 @@ final class UpdateSlide implements Action
|
|||
'date_end' => $input->period->end !== null ? Carbon::instance($input->period->end) : null,
|
||||
];
|
||||
|
||||
if ($input->picture !== null) {
|
||||
$attributes['picture'] = $input->picture;
|
||||
if ($input->picture instanceof UploadedFile) {
|
||||
$newPicture = $this->publicImageStorageService->store($input->picture);
|
||||
$attributes['picture'] = $newPicture;
|
||||
$this->trackUploadedPath($input, $newPicture);
|
||||
}
|
||||
|
||||
$slide = $input->slide;
|
||||
$slide->fill($attributes);
|
||||
$slide->saveOrFail();
|
||||
|
||||
$this->trackReplacedPath($input, $previousPicture, $newPicture);
|
||||
|
||||
return $slide;
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onSuccess(ActionInput $input, mixed $result): void
|
||||
{
|
||||
foreach ($this->pullObsoletePaths($input) as $path) {
|
||||
$this->publicImageStorageService->deleteIfExists($path);
|
||||
}
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function onFailure(ActionInput $input, \Throwable $exception): void
|
||||
{
|
||||
foreach ($this->pullUploadedPaths($input) as $path) {
|
||||
$this->publicImageStorageService->deleteIfExists($path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ use App\Contracts\ActionInput;
|
|||
use App\Models\Slide;
|
||||
use Domain\Models\ValueObjects\DatePeriod;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
final readonly class UpdateSlideInput implements ActionInput
|
||||
|
|
@ -16,7 +17,7 @@ final readonly class UpdateSlideInput implements ActionInput
|
|||
public Slide $slide,
|
||||
public string $title,
|
||||
public ?string $text = null,
|
||||
public UploadedFile | string | null $picture = null,
|
||||
public UploadedFile | StorageFilePath | null $picture = null,
|
||||
public ?string $pictureAlt = null,
|
||||
public ?string $pictureTitle = null,
|
||||
public ?string $link = null,
|
||||
|
|
|
|||
68
app/Cqs/Actions/Slides/UpdateSlidesStatus.php
Normal file
68
app/Cqs/Actions/Slides/UpdateSlidesStatus.php
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
<?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,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
37
app/Cqs/Actions/Users/CreateUser.php
Normal file
37
app/Cqs/Actions/Users/CreateUser.php
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
<?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;
|
||||
}
|
||||
}
|
||||
28
app/Cqs/Actions/Users/CreateUserInput.php
Normal file
28
app/Cqs/Actions/Users/CreateUserInput.php
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
<?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);
|
||||
}
|
||||
}
|
||||
|
|
@ -7,12 +7,15 @@ namespace App\Cqs\Queries\Basket;
|
|||
use App\Contracts\Query;
|
||||
use App\Contracts\QueryInput;
|
||||
use App\Contracts\QueryInputEmpty;
|
||||
use Domain\Models\Entities\Basket;
|
||||
use App\Dto\BasketDto;
|
||||
use App\Dto\BasketProductDto;
|
||||
use App\Models\Product;
|
||||
use Domain\Models\ValueObjects\BasketProduct;
|
||||
use Domain\Services\BasketService;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* @implements \App\Contracts\Query<\App\Contracts\QueryInputEmpty, \Domain\Models\Entities\Basket>
|
||||
* @implements \App\Contracts\Query<\App\Contracts\QueryInputEmpty, \App\Dto\BasketDto>
|
||||
*/
|
||||
final readonly class GetBasketQuery implements Query
|
||||
{
|
||||
|
|
@ -21,13 +24,41 @@ final readonly class GetBasketQuery implements Query
|
|||
) {
|
||||
}
|
||||
|
||||
public function __invoke(QueryInput $input): Basket
|
||||
#[\Override]
|
||||
public function __invoke(QueryInput $input): BasketDto
|
||||
{
|
||||
Assert::isAOf(
|
||||
$input,
|
||||
QueryInputEmpty::class,
|
||||
);
|
||||
|
||||
return $this->basketService->getBasket();
|
||||
$basket = $this->basketService->getBasket();
|
||||
$basketItems = array_values($basket->items());
|
||||
$ids = array_map(
|
||||
static fn (BasketProduct $item): string => $item->id->value->toString(),
|
||||
$basketItems
|
||||
);
|
||||
|
||||
if ($ids === []) {
|
||||
$publishedMap = [];
|
||||
} else {
|
||||
$publishedIds = Product::query()
|
||||
->whereIn('id', $ids)
|
||||
->where('status', true)
|
||||
->pluck('id')
|
||||
->all();
|
||||
Assert::allString($publishedIds);
|
||||
$publishedMap = array_flip($publishedIds);
|
||||
}
|
||||
|
||||
$items = array_map(
|
||||
static fn (BasketProduct $item): BasketProductDto => new BasketProductDto(
|
||||
product: $item,
|
||||
isPublished: isset($publishedMap[$item->id->value->toString()]),
|
||||
),
|
||||
$basketItems
|
||||
);
|
||||
|
||||
return BasketDto::fromEntity($basket, $items);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,6 +47,7 @@ final readonly class GetDiscountFormDataQuery implements Query
|
|||
|
||||
$discountDto = DiscountDto::fromModel($input->discount);
|
||||
} else {
|
||||
/** @var \Illuminate\Support\Collection<int,\App\Dto\DiscountProductDto> */
|
||||
$selectedProds = collect();
|
||||
$existingProds = Product::query()
|
||||
->select(['id', 'name', 'picture'])
|
||||
|
|
|
|||
|
|
@ -66,6 +66,8 @@ final readonly class GetBoPaginatedOrdersQuery implements Query
|
|||
|
||||
if ($input->status !== null) {
|
||||
$query->where('status', $input->status);
|
||||
} else {
|
||||
$query->whereNotIn('status', [OrderStatus::PENDING, OrderStatus::FAILED]);
|
||||
}
|
||||
|
||||
$this->dataTable->sortQuery(
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ use App\Contracts\QueryInput;
|
|||
use App\Dto\OrderDto;
|
||||
use App\Models\Order;
|
||||
use App\Services\DataTableService;
|
||||
use Domain\Enums\OrderStatus;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
|
@ -35,7 +36,9 @@ final readonly class GetBoTodayOrdersQuery implements Query
|
|||
{
|
||||
Assert::isInstanceOf($input, GetBoTodayOrdersQueryInput::class);
|
||||
|
||||
$query = Order::query()->with(['shop']);
|
||||
$query = Order::query()
|
||||
->with(['shop'])
|
||||
->whereNotIn('status', [OrderStatus::PENDING, OrderStatus::FAILED]);
|
||||
|
||||
$query->whereCreatedAtBetween(Date::now(), Date::now());
|
||||
|
||||
|
|
|
|||
|
|
@ -8,9 +8,9 @@ use App\Contracts\Query;
|
|||
use App\Contracts\QueryInput;
|
||||
use App\Dto\OrderDto;
|
||||
use App\Models\Order;
|
||||
use Domain\Enums\OrderStatus;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Pagination\LengthAwarePaginator as ConcreteLengthAwarePaginator;
|
||||
use SortDirection;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
|
|
@ -44,7 +44,8 @@ final readonly class GetFoCustomerPaginatedOrdersQuery implements Query
|
|||
|
||||
$paginator = Order::query()
|
||||
->where('employee_matricule', $employeeMatricule->value)
|
||||
->orderBy('id', SortDirection::Descending)
|
||||
->whereNotIn('status', [OrderStatus::PENDING, OrderStatus::FAILED])
|
||||
->orderBy('id', \SortDirection::Descending)
|
||||
->paginate(
|
||||
perPage: $input->pagination->pageSize()->value(),
|
||||
page: $input->pagination->pageNumber()->value(),
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue