Compare commits

..

184 commits

Author SHA1 Message Date
Jérémy
800138930d Merge branch 'to-pvc-less' into 'develop'
Removes pvc usage

See merge request ldc-web/projets/boutique-cnc-sable!90
2026-11-17 12:47:48 +01:00
Jérémy Munsch
1894e45907
fix(stats): exclude technical PENDING and FAILED orders from active clients metric 2026-11-17 12:39:18 +01:00
Jérémy Munsch
aba49edaee
chore(config,tests): disable local disk serving route and freeze time in ShopperTest 2026-11-17 12:32:21 +01:00
Jérémy Munsch
0a52798a3e
fix(filesystems): correct default disk configuration
Ensure the default filesystem disk falls back to 'local' if not set.
Set 'serve' option to false for the local disk.
2026-11-17 12:32:18 +01:00
Jérémy Munsch
7ae12f71fe
test(arch): forbid direct Ramsey\Uuid\Uuid and Symfony\Component\Uid usage 2026-11-17 12:15:45 +01:00
Jérémy Munsch
d9edcd7f6b
test(uuid): migrate test suite to UuidHelper and add missing describe blocks 2026-11-17 12:15:39 +01:00
Jérémy Munsch
75784ae719
refactor(uuid): migrate app, domain, infra, and factories to UuidHelper 2026-11-17 12:15:34 +01:00
Jérémy Munsch
ad2c8f631b
feat(shared): encapsulate UUID generation and parsing in UuidHelper 2026-11-17 12:15:28 +01:00
Jérémy Munsch
617d1f70e9
feat(manifest): add LOG_LEVEL configuration
Added LOG_LEVEL with a default value of "warning" to the manifest for better logging control.
2026-11-17 12:13:55 +01:00
Jérémy Munsch
d2a7afc020
Merge branch 'develop' into to-pvc-less
# Conflicts:
#	app/Services/EmployeeCsvReaderService.php
#	tests/Feature/App/Console/Commands/UpsertEmployeesFormFileTest.php
#	tests/Unit/App/Services/EmployeeCsvReaderServiceTest.php
2026-11-17 10:36:59 +01:00
Jérémy Munsch
101d0ff018
feat(EmployeeCsvReaderService): refactor CSV reader creation
Updated the importEmployeesFromCsv method to use a dedicated createCsvReader method for better encoding handling and improved readability.
2026-11-17 09:46:05 +01:00
Jérémy Munsch
1085a2d4db
test(enums): add enum fixtures for testing BaseEnum functionality
- Introduced IntStatusFixture, StringStatusFixture, and MissingLabelFixture for comprehensive testing of enum behavior.
2026-11-17 09:37:58 +01:00
Jérémy Munsch
ec7aaa5cfe
ci(gitlab): install icu-data-full in tests_laravel for French locale currency formatting 2026-11-16 22:09:41 +01:00
Jérémy Munsch
17cca9c43d
ci(tests_laravel): add mariadb-connector-c and update DB user setup
Enhance the CI pipeline for Laravel tests by adding mariadb-connector-c
and improving the database user setup process for better reliability.
2026-11-16 22:02:10 +01:00
Jérémy Munsch
c734ee41e4
ci(gitlab): install mariadb-client and disable TLS verification for CI mysql:8.0 2026-11-16 21:32:19 +01:00
Jérémy Munsch
470c2d1b9d
ci(gitlab): install mysql-client in tests_laravel for RefreshDatabase schema import 2026-11-16 21:19:39 +01:00
Jérémy Munsch
7a701328f9
test(orders): verify selected HTML option, failed status filter, and all OrderStatus cases 2026-11-16 20:39:50 +01:00
Jérémy Munsch
758605be09
refactor(domain,orders): convert OrderStatus enum to lowercase string 2026-11-16 20:31:25 +01:00
Jérémy Munsch
3b24436263
feat(stats,orders): track tunnel attempts in DB to preserve waiting stats 2026-11-16 20:19:31 +01:00
Jérémy Munsch
c58a2c8b23
feat(orders): add checkout lock, FAIL/PENDING isolation, and stale pending expiration 2026-11-16 20:05:35 +01:00
Jérémy Munsch
53f49fea9c
refactor(domain,infra): isolate PENDING/FAILED order states and add lockForUpdate 2026-11-16 19:57:06 +01:00
Jérémy Munsch
24acaf56e9
test(tunnel): add end-to-end confirmation HTTP tests without mocking Executor 2026-11-16 18:34:10 +01:00
Jérémy Munsch
dc6b00fbc1
chore(deps): bound wildcard constraints for league/csv and uwil/storage-laravel 2026-11-16 18:34:09 +01:00
Jérémy Munsch
757f9aebaa
fix(casts): treat empty string as null in FilePathCast 2026-11-16 18:34:09 +01:00
Jérémy Munsch
85aceedd1f
fix(http): guard null route when redirecting guests in middleware 2026-11-16 18:34:09 +01:00
Jérémy Munsch
392dcdc6c3
fix(auth): validate forgot-password email through Email value object 2026-11-16 18:34:08 +01:00
Jérémy Munsch
1f3d25d61a
fix(ci,tests): resolve PHPStan CI failures with .env.example and Intelephense warnings 2026-11-16 18:34:08 +01:00
Jérémy Munsch
45fc35b1f7
fix(products): query published associated products in pivot order on FO product page 2026-11-16 18:34:07 +01:00
Jérémy Munsch
0fb5a25a4a
ci: update phpstan configuration to copy .env.example
This change ensures that the .env file is created from the example
before running phpstan, allowing for proper environment setup.
2026-11-16 17:12:54 +01:00
Jérémy Munsch
8ffe04c388
ci: add AWS_DEFAULT_REGION variable for phpstan 2026-11-16 17:08:29 +01:00
Jérémy Munsch
cdc04d0104
test(coverage): cover Arcadia jobs and employee service, add describe blocks (Lot 7C) 2026-11-16 17:01:12 +01:00
Jérémy Munsch
3aaec0a6db
test(coverage): cover post-commit Listeners and AppSessionService (Lot 7B) 2026-11-16 16:53:21 +01:00
Jérémy Munsch
241ad87a2e
test(coverage): cover remaining CQS Queries and FO product HTML rendering (Lot 7A) 2026-11-16 16:47:33 +01:00
Jérémy Munsch
aee7d4b8e7
chore(config): force APP_ENV to testing in phpunit.xml
Ensures the testing environment is consistently set.
2026-11-16 16:37:52 +01:00
Jérémy Munsch
b4384c00a7
chore(lint): resolve remaining PHPCS warnings across domain, infra, shared, and unit tests 2026-11-16 16:34:21 +01:00
Jérémy Munsch
14fd20c303
test(quality): resolve PHPStan level 10 errors in Feature tests and wrap long test lines 2026-11-16 16:29:17 +01:00
Jérémy Munsch
08c9028f91
test: update tests to use Assert for type checking
- Refactored tests to utilize Webmozart Assert for type assertions.
- Improved clarity and consistency in test expectations across multiple test files.
- Ensured that all relevant tests now check for expected types and values.
2026-11-16 16:26:51 +01:00
Jérémy Munsch
1b44f9d178
test(quality): resolve all PHPStan level 10 errors in Unit and Integration tests 2026-11-16 16:13:14 +01:00
Jérémy Munsch
2db00301f4
test(shared): add pure unit test suites across Helpers, Enums, Filesystem, Pagination, and ValueObjects 2026-11-16 16:01:08 +01:00
Jérémy Munsch
a4f2343eb2
test(eloquent,container): use Model::query() and direct dependency instantiation 2026-11-16 15:54:41 +01:00
Jérémy Munsch
c9d53f43c0
test(clock): add global clock reset and freeze time across 22 test files 2026-11-16 15:49:48 +01:00
Jérémy Munsch
c2490e0339
test(phpstan): remove all 55 redundant RefreshDatabase uses() 2026-11-16 15:45:21 +01:00
Jérémy Munsch
c083d74032
test(phpstan): remove all 145 redundant Pest expectations 2026-11-16 15:43:10 +01:00
Jérémy Munsch
7ad5acebd3
test(requests): overhaul FO request tests and lock Architecture rules 2026-11-16 15:31:41 +01:00
Jérémy Munsch
6f81d94648
test(requests): overhaul Basket and remaining BO request tests with controller failure checks 2026-11-16 15:23:40 +01:00
Jérémy Munsch
1f642b185e
test(requests): overhaul BO Tags/Slides/Ranges/Products request tests and failure responses 2026-11-16 15:19:01 +01:00
Jérémy Munsch
1c304b78b2
test(decouple): remove expect(true)->toBeTrue() and move ProductPolicy INCO checks to WithApp 2026-11-16 15:12:42 +01:00
Jérémy Munsch
4f2b7ba0c0
test(tests): update ArcadiaIncoServiceTest for null safety
Refactor assertions to use null-safe operator and simplify instantiation of IncoNutriscore.
2026-11-16 15:07:53 +01:00
Jérémy Munsch
99a923a7df
test(tests): replace internal Laravel Session/Mail/DB mocks with real stores and Mail::fake (lot 4B) 2026-11-16 15:04:17 +01:00
Jérémy Munsch
8a6b1442e6
test(tests): remove Reflection attribute/constructor hacks and pass-through InitializeOrderTunnel (lot 4A) 2026-11-16 15:01:17 +01:00
Jérémy Munsch
49c17d61f0
chore(tests): upgrade to Pest 5, PHPUnit 13, pest-plugin-phpstan and phpstan-webmozart-assert 2026-11-16 14:49:53 +01:00
Jérémy Munsch
5b88fb098a
test(tests): add PSR-4 namespaces to Architecture and Feature test files 2026-11-16 14:26:35 +01:00
Jérémy Munsch
cdb30e2f70
test(tests): add PSR-4 namespaces to Integration test files 2026-11-16 14:21:17 +01:00
Jérémy Munsch
a87e5a0c94
test(tests): add unit tests for Pagination value object 2026-11-16 14:19:02 +01:00
Jérémy Munsch
588a93cbcf
test(tests): add PSR-4 namespaces to Unit test files 2026-11-16 14:18:42 +01:00
Jérémy Munsch
8b9eb59b50
test(tests): replace $this->fail with caught exception assertion in LaravelCacheLockTest 2026-11-16 13:11:20 +01:00
Jérémy Munsch
348119ec7c
test(tests): normalize Integration Cqs and Feature App directories (lot 3C) 2026-11-16 13:09:00 +01:00
Jérémy Munsch
3f4856efa2
test(tests): move Laravel-bound tests out of Unit and group Unit Cqs tests (lot 3B) 2026-11-16 13:02:15 +01:00
Jérémy Munsch
7b27f532ee
test(tests): fix PHPStan level 10 errors in OrderTunnelServiceTest and PickupSchedulingServiceTest 2026-11-16 13:00:47 +01:00
Jérémy Munsch
29b9a87d78
test(tests): update mock usage in DataTableServiceTest
Refactor mock creation to use \Mockery::mock for consistency.
2026-11-16 12:54:52 +01:00
Jérémy Munsch
ec6e220138
test(tests): update Carbon usage in GetPickTimeSlotQueryTest and IcsGeneratorServiceTest
Refactor date handling to use CarbonImmutable for consistency in tests.
2026-11-16 12:54:30 +01:00
Jérémy Munsch
7698821501
test(tests): add namespace declarations to test files 2026-11-16 12:54:16 +01:00
Jérémy Munsch
a2fd843398
test(tests): add unit tests for session-based basket repository
Added tests for the SessionBasketRepository to ensure correct behavior when finding, persisting, and deleting baskets in the session.
2026-11-16 12:53:27 +01:00
Jérémy Munsch
4c8280d932
test(tests): prune constructor-only DTO tests and consolidate contracts (lot 2C) 2026-11-16 12:50:19 +01:00
Jérémy Munsch
712d42ed96
test(tests): remove generic enum, exception string, and invariant-free input tests (lot 2B) 2026-11-16 12:47:36 +01:00
Jérémy Munsch
80d3478dbe
test(tests): merge unique assertions and remove strict duplicate test files (lot 2A) 2026-11-16 12:46:06 +01:00
Jérémy Munsch
875d6dd01d
test(tests): apply step 1 hygiene, clock reset, and explicit Arcadia policy skips 2026-11-16 12:39:21 +01:00
Jérémy Munsch
8a3d6a8156
chore(phpstan): add phpstan-mockery extension for testing
This addition enhances the testing capabilities by integrating phpstan-mockery.
2026-11-16 12:36:26 +01:00
Jérémy Munsch
50cef3b0cf
chore(dependencies): add phpstan-mockery for improved testing
This addition enhances the testing capabilities by integrating the PHPStan Mockery extension.
2026-11-16 11:49:32 +01:00
Jérémy Munsch
ea06b37a47
refactor(BaseEnum): improve cache handling and type annotations
Enhanced type annotations for cache variables and improved readability of the toLabels, toValues, and getCustomDefinitions methods.
2026-11-16 11:44:31 +01:00
Jérémy Munsch
cbb1ed812b
test(UpsertEmployeesFormFile): assert result is PendingCommand 2026-11-16 11:41:51 +01:00
Jérémy Munsch
d45022d8a4
fix(SessionBasketRepository): handle corrupted session payload correctly
Ensure that corrupted session data is ignored and null is returned, improving robustness.
2026-11-16 11:40:24 +01:00
Jérémy Munsch
f658dd4b64
refactor(tests): remove unused imports in test files
Cleaned up test files by removing unnecessary imports to improve readability.
2026-11-16 11:40:10 +01:00
Jérémy Munsch
d1f0b21ad5
refactor(EntityId): move UUID validation to EntityId constructor
Refactored the EntityId class to include UUID v7 validation in the constructor, ensuring all derived classes inherit this behavior.
2026-11-16 11:39:52 +01:00
Jérémy Munsch
3916771f69
test: update tests to remove schema creation and use factories
Refactor tests to eliminate schema creation in beforeEach hooks and utilize model factories for data setup.
2026-11-16 11:22:47 +01:00
Jérémy Munsch
c429697025
chore(deps): upgrade uwil/laravel-k8s to ^4.0 and uwil/sitemap-generator to ^8.1 2026-11-16 11:08:01 +01:00
Jérémy Munsch
2d616ed3b4
fix(translations): add missing employee account message in fr.json
Ensures consistency in employee account messages for French localization.
2026-11-16 10:39:39 +01:00
Jérémy Munsch
0116d220d4
feat(sitemap): implement sitemap generation and configuration
- Added new sitemap generation configuration.
- Removed deprecated refresh-sitemap configuration.
- Updated Product model to implement Sitemapable interface.
- Upgraded sitemap-generator dependency to version 8.1.
2026-11-16 10:35:40 +01:00
Jérémy Munsch
1e872f09d3
refactor(logging): remove 'daily' channel from k8s logging configuration
Simplifies the logging setup for Kubernetes by using only 'stdout'.
2026-11-16 10:05:46 +01:00
Jérémy Munsch
317ca4cd03
fix(sync): move Arcadia API calls outside transactions, track per-site employee cursors, and release reminder claim on failure 2026-11-16 08:45:40 +01:00
Jérémy Munsch
1ae8f65d7c
fix(integrity): include trashed products in max order and purge CRM email cache on deletion 2026-11-16 03:41:39 +01:00
Jérémy Munsch
3d1c798c08
refactor(orders): split pending placement, non-transactional Regate SMTP export and final confirmation 2026-11-16 03:32:57 +01:00
Jérémy Munsch
3e4dfdad4e
feat(tunnel): detect basket price changes during order finalization 2026-11-16 03:10:25 +01:00
Jérémy Munsch
fae7690161
fix(security): escape slider description/toast text and validate product brand and alt fields 2026-11-16 02:50:39 +01:00
Jérémy Munsch
d46d5e7b23
fix(auth): prevent premature customer creation and enforce active employee registration 2026-11-16 02:35:42 +01:00
Jérémy Munsch
f6bae64859
fix(fo): exclude unpublished products from associated products on product detail page 2026-11-16 02:18:51 +01:00
Jérémy Munsch
285f42c684
fix(shopper): evaluate employee calendar dates in Europe/Paris and document BO order cancel 2026-11-16 02:10:50 +01:00
Jérémy Munsch
92dd038cb9
fix(pickup): align scheduling on Europe/Paris cutoff and attach holidays on shop creation 2026-11-16 01:58:44 +01:00
Jérémy Munsch
abf3839f98
fix(dates): enforce UTC and calendar-date casts across models, requests and BO views 2026-11-16 01:58:43 +01:00
Jérémy Munsch
6663f0f66f
fix(fo): invert is_orderable condition for opacity and coming soon badge 2026-11-16 01:30:10 +01:00
Jérémy Munsch
550f2a11c8
fix(fo): use ProductWithPricingDto for product policy checks in FO views 2026-11-16 01:16:56 +01:00
Jérémy Munsch
f0617c06ce
feat(i18n): translate StatsShopType labels and synchronize fr/en json files 2026-11-16 01:01:41 +01:00
Jérémy Munsch
d0a49ec77c
fix(validation): use translation keys in Adult rule 2026-11-16 01:01:41 +01:00
Jérémy Munsch
0411e1d73b
refactor(datatable): require column listing resolver dependency in DataTableService 2026-11-16 01:01:33 +01:00
Jérémy Munsch
2c2a0502d6
refactor(routing): execute published product route binding via Executor 2026-11-16 00:53:36 +01:00
Jérémy Munsch
4bbea5d285
fix(bo): check proper model policy in ranges and pickup exceptions index views 2026-11-16 00:53:36 +01:00
Jérémy Munsch
13aec6bad8
fix(bo): authorize update in ChangesModelOrder actions 2026-11-16 00:53:11 +01:00
Jérémy Munsch
1ad8fc45a0
chore(arch): include shared, domain, and infra in lint/arch checks 2026-11-16 00:49:51 +01:00
Jérémy Munsch
13158d7301
chore(tests): configure phpstan, phpcs, and structural test setup 2026-11-16 00:39:49 +01:00
Jérémy Munsch
8029bcd959
test(actions): add missing integration tests for Products, Basket, CRM, and Orders 2026-11-15 22:11:27 +01:00
Jérémy Munsch
e0d2074b2b
fix(orders): render RegateExportFailedException gracefully while keeping rollback and Sentry reporting 2026-11-15 21:57:14 +01:00
Jérémy Munsch
fdb7df5858
fix(auth): prevent CRM split-brain and add post-commit hooks in RegisterCustomer 2026-11-15 21:44:33 +01:00
Jérémy Munsch
c427b60210
feat(jobs): handle shop pickup exceptions, chunking, and cache deduplication in SendMissingOrderReminderJob 2026-11-15 21:39:33 +01:00
Jérémy Munsch
3d4c4f74de
feat(jobs): add chunking and idempotent reminded_at tracking to SendReminderMail 2026-11-15 21:39:32 +01:00
Jérémy Munsch
efbd507ac9
feat(jobs): implement unique job handling for reminders
Added ShouldBeUnique interface to SendMissingOrderReminderJob and SendReminderMail for unique job processing.
2026-11-15 20:39:57 +01:00
Jérémy Munsch
86e7340c48
feat(products): add success and failure handling for product actions
- Implemented HandlesSuccess and HandlesFailure interfaces in CreateProduct and UpdateProduct actions.
- Added tracking of uploaded paths and cleanup on failure.
- Enhanced image storage handling to ensure proper cleanup of orphaned files.

feat(ranges): add success and failure handling for range actions

- Implemented HandlesSuccess and HandlesFailure interfaces in CreateRange and UpdateRange actions.
- Added tracking of uploaded paths and cleanup on failure.
- Enhanced image storage handling to ensure proper cleanup of orphaned files.

feat(slides): add success and failure handling for slide actions

- Implemented HandlesSuccess and HandlesFailure interfaces in CreateSlide and UpdateSlide actions.
- Added tracking of uploaded paths and cleanup on failure.
- Enhanced image storage handling to ensure proper cleanup of orphaned files.

chore: introduce TracksPendingStoragePaths trait

- Created a new trait to manage tracking of uploaded and obsolete storage paths.
- This will streamline the handling of file cleanup across various actions.

test: add tests for action failure handling and cleanup

- Added tests to verify that uploaded files are cleaned up on action failure.
- Ensured that previous files are preserved during rollback scenarios.
2026-11-15 20:31:37 +01:00
Jérémy Munsch
d2179fcdc8
style(SecureHeaders): update Content Security Policy directives
Refine CSP directives for improved security and clarity.
2026-11-15 20:15:08 +01:00
Jérémy Munsch
3ff21bdd49
feat(orders): implement CancelOrder action with output handling
Added CancelOrder action to handle order cancellations with appropriate output responses.
2026-11-15 20:12:16 +01:00
Jérémy Munsch
3f73535ce7
test(ResetCustomerPassword): update tests to check remember_token behavior
Ensure that the remember_token is retained for inactive shoppers during password reset tests.
2026-11-15 20:12:00 +01:00
Jérémy Munsch
afb385fe5d
fix(Timeslots): correct assertion for timeslotList type
Updated the assertion in the constructor to ensure all elements of $timeslotList are instances of PickupTimeSlot.
2026-11-15 20:11:37 +01:00
Jérémy Munsch
6a599b9855
feat(ProductIncos): implement Associate and Sync actions with output handling
- Added AssociateProductIncoOutput and SyncProductIncoOutput classes to handle action results.
- Updated AssociateProductInco and SyncProductInco actions to return structured output instead of raw models.
- Enhanced error handling for API interactions in both actions.
- Refactored ProductIncosController to utilize new output structures for better response management.
- Introduced new enums for status handling in actions and queries.
- Added tests for new output handling and error scenarios in Associate and Sync actions.
2026-11-15 20:11:28 +01:00
Jérémy Munsch
0aa4b449b4
feat(orders): implement ApplyPickTimeSlot action and output handling
- Introduced ApplyPickTimeSlotOutput class for structured output.
- Updated ApplyPickTimeSlot action to return ApplyPickTimeSlotOutput.
- Added ApplyPickTimeSlotStatus enum for status representation.
- Modified TunnelController to handle new output structure.
- Enhanced tests for ApplyPickTimeSlot to validate new behavior.
2026-11-15 20:08:25 +01:00
Jérémy Munsch
8892a55322
feat(orders): implement CancelOrder action and output enum
Added CancelOrder action with output handling for order cancellation.
Introduced CancelOrderOutput enum to represent cancellation states.
Refactored ShopPolicy to simplify user checks in viewPickupTimeslots.
Updated tests to reflect changes in policy behavior.
2026-11-15 20:05:41 +01:00
Jérémy Munsch
faef51091e
feat(pickup-exceptions): implement upsert and query for public holidays
Added functionality to upsert pickup exceptions for public holidays
and query for auto-updated exceptions. This includes new classes
for handling input and service integration with the public holidays API.
2026-11-15 20:04:29 +01:00
Jérémy Munsch
43d63bce2e
feat(basket): add throttling middleware for basket actions
This change introduces a throttling middleware to limit the rate of requests
for adding, removing, and emptying the basket, enhancing the application's
performance and security.
2026-11-15 20:01:02 +01:00
Jérémy Munsch
4dd7cc82fe
feat(order): add InactiveShopperException handling in order finalization
- Introduced InactiveShopperException to manage inactive shopper scenarios.
- Updated FinalizeOrder and FinalizeOrderOutput to handle new exception.
- Enhanced TunnelController and tests to ensure proper redirection and error handling.
2026-11-15 19:59:17 +01:00
Jérémy Munsch
47b0c16857
feat(auth): implement ResetCustomerPassword action and related classes
Adds functionality for resetting customer passwords, including input and output handling.
2026-11-15 19:57:38 +01:00
Jérémy Munsch
6c60e067f0
fix(auth): handle inactive employee response in password reset
Return a generic response for inactive employees instead of throwing an exception.
2026-11-15 19:52:29 +01:00
Jérémy Munsch
5a19f01270
test(product): add tests for orderable date boundaries
Added tests to verify behavior of canBeOrderOn method
when the date equals orderable_start and orderable_end.
2026-11-15 19:49:55 +01:00
Jérémy Munsch
0ae05e031d
feat(jobs): enhance SendMissingOrderReminderJob with ICS content generation
- Added IcsGeneratorService for generating ICS content.
- Updated MissingOrderReminderNotification to include cutoff date and ICS content.
- Refactored SendMissingOrderReminderJob to utilize new ICS generation logic.
- Introduced IcsContent value object for better ICS content handling.
- Added tests for new functionality in SendMissingOrderReminderJob and IcsGeneratorService.
2026-11-15 19:49:48 +01:00
Jérémy Munsch
b62e15efc2
feat(product): add GetProductIncoForEditQuery and related classes
Implement GetProductIncoForEditQuery, its input and output classes to handle product INCO data retrieval.
Update ProductIncosController to utilize the new query for editing product INCOs.
Add tests for GetProductIncoForEditQuery to ensure correct behavior.
2026-11-15 19:47:32 +01:00
Jérémy Munsch
b10c22b931
refactor(requests): inject dependencies into AddBasketRequest
Updated AddBasketRequest to use dependency injection for Executor and GetProductWithPricingQuery.
2026-11-15 19:44:35 +01:00
Jérémy Munsch
746fe1274d
fix(product): adjust orderable start condition to include equality
This change ensures that products are considered orderable if the current time is equal to the orderable start time.
2026-11-15 19:43:56 +01:00
Jérémy Munsch
d430fa01d2
fix(product): adjust orderable end condition to include equality
Updated the condition for orderable end to include equality, ensuring products are excluded correctly when the current date matches the orderable end date.
2026-11-15 19:43:45 +01:00
Jérémy Munsch
5278c3e3f9
refactor(requests): inject Currency dependency into StoreDiscountRequest and StoreProductRequest
This change improves the handling of currency in discount and product requests.
2026-11-15 19:43:25 +01:00
Jérémy Munsch
2884a76a76
refactor(auth): move URL generation for email verification and password reset to AuthServiceProvider
This change centralizes the URL generation logic for email verification and password reset, improving maintainability.
2026-11-15 19:42:03 +01:00
Jérémy Munsch
66e406499d
refactor(auth): remove parent constructor calls in auth controllers
This change simplifies the constructors in the ForgotPasswordController, LoginController, RegisterController, and ResetPasswordController by removing unnecessary parent constructor calls.
2026-11-15 19:41:27 +01:00
Jérémy Munsch
c4d9c84408
feat(policy): implement customer order limit policy with config values
Added CustomerOrderLimitPolicy to manage order limits based on configuration values.
Updated tests to reflect changes in constructor parameters.
2026-11-15 19:39:35 +01:00
Jérémy Munsch
6ff09f1369
fix(verification): remove parent constructor call in constructor
This change ensures that the parent constructor is not called,
which may be necessary for the current functionality.
2026-11-15 19:34:39 +01:00
Jérémy Munsch
ece1b7238d
fix(slides): update status handling for publishing and unpublishing
Refactor the logic to preserve scheduling dates when updating slide statuses.
2026-11-15 19:31:49 +01:00
Jérémy Munsch
fa3aec6d92
fix(pickup-exception): change date comparison to include start date
Updated the date comparison in getExceptionsForShop to use '>=' for the start date.
2026-11-15 18:57:31 +01:00
Jérémy Munsch
6f8c7a138b
fix(queue): enable after_commit for database jobs
This change ensures that jobs are committed to the database after the transaction is complete.
2026-11-15 18:57:15 +01:00
Jérémy Munsch
d8f326668d
fix(purifier): disable debug mode in custom definitions
This change sets the debug option to false for custom HTML5 definitions.
2026-11-15 18:57:00 +01:00
Jérémy Munsch
28a2504841
fix(mail): set default timeout for mail configuration
Updated the mail configuration to set a default timeout value from the environment variable.
2026-11-15 18:56:42 +01:00
Jérémy Munsch
e3611be210
fix(api): change default for ignore_self_signed_cert to false
This change ensures that self-signed certificates are not ignored by default, enhancing security.
2026-11-15 18:56:33 +01:00
Jérémy Munsch
5197e796c0
test(casts): add tests for various cast classes
- Implement tests for DiscountValueCast to validate percentage and amount handling.
- Add tests for EmailCast to ensure proper email handling.
- Create tests for EmployeeSitesCast to validate JSON and array handling.
- Implement tests for MatriculeCast to validate matricule handling.
- Add tests for MoneyCast to ensure proper money handling.
- Create tests for NutritionalValuesCast to validate nutritional values handling.
- Implement tests for OrderEmployeeCast to validate employee data handling.
- Add tests for OrderLineProductCast to validate order line product handling.
- Create tests for OrderReferenceCast to validate order reference handling.
- Implement tests for ShopperEstablishmentCodeCast to validate establishment code handling.
- Add tests for ShopperServiceCodeCast to validate service code handling.
- Create tests for ShopperSiteCodeCast to validate site code handling.
2026-11-15 18:56:19 +01:00
Jérémy Munsch
570c1e54d5
docs: document order cancellation, employee code and unverified login rules 2026-11-15 18:25:49 +01:00
Jérémy Munsch
5491c4fc30
fix(auth): avoid flashing login success for unverified customers 2026-11-15 18:25:48 +01:00
Jérémy Munsch
359f762f87 refactor(infra): enforce Infrastructure isolation from App except Models 2026-11-15 18:10:28 +01:00
Jérémy Munsch
7f1bc1c563 refactor(app): remove legacy App\Repositories and migrate callers to Eloquent 2026-11-15 18:10:26 +01:00
Jérémy Munsch
574c2a1abe refactor(stats): migrate StatsService to Eloquent and remove legacy App\Directories and dead UserRepository 2026-11-15 18:10:08 +01:00
Jérémy Munsch
5f6ccaa35d refactor(orders): rename App\Services\OrderService to OrderOwnershipService 2026-11-15 17:55:55 +01:00
Jérémy Munsch
93dc942152 test(arch): fix entity/naming test namespaces and allow mutable domain entities 2026-11-15 17:50:56 +01:00
Jérémy Munsch
7d5fc6401e fix(fo): filter unpublished ranges on product index and validate client_timezone in Date macros 2026-11-15 17:17:28 +01:00
Jérémy Munsch
4be9252c24 refactor(storage): extract PublicImageStorageService and clean up S3 image lifecycle on update/delete actions 2026-11-15 17:13:39 +01:00
Jérémy Munsch
48e9c9d38e
perf(products): avoid reloading already hydrated products in ProductDtoAssemblerService 2026-11-15 16:59:46 +01:00
Jérémy Munsch
bb23dae81e
perf(basket): eliminate N+1 queries and return BasketDto from GetBasketQuery 2026-11-15 16:59:45 +01:00
Jérémy Munsch
ee6a6607dc
fix(employee): enforce start_date and align active status rules 2026-11-15 16:45:07 +01:00
Jérémy Munsch
2f76a874d9
refactor(orders): decouple basket and order tunnel via domain events 2026-11-15 16:45:06 +01:00
Jérémy Munsch
4fe2d48f68
refactor(builders): split OrderBuilder into immutable step classes 2026-11-15 16:45:06 +01:00
Jérémy Munsch
8986570e1d
refactor(ToolboxHelper): remove unused method and import
Cleaned up ToolboxHelper by removing the unused stripCkEditorSchemesOnMediaInputs method
and its associated import, streamlining the code.
2026-11-15 16:45:06 +01:00
Jérémy Munsch
bf1c0d7d4e
test(HtmlSanitizer): add tests for HTML sanitization behavior
- Ensure password fields are preserved during sanitization.
- Validate rich HTML fields are purified correctly.
- Confirm HTTP scheme is stripped from oembed URLs after sanitization.
2026-11-15 16:45:05 +01:00
Jérémy Munsch
a0f84c5da7
fix(crm): handle CRM exceptions without caching on failures
Ensure that CrmService returns CrmServiceException when CRM fails
to retrieve customer data by hashcode or email, without caching the
result in case of errors.
2026-11-15 16:45:05 +01:00
Jérémy Munsch
d1d0585b34
fix(contact): update orderRef to use OrderReference value object
Refactor orderRef handling in contact forms to ensure proper validation and type safety.
2026-11-15 16:45:05 +01:00
Jérémy Munsch
10b97e3a00
fix(orders): handle invalid timeslot format gracefully
Catch InvalidArgumentException when timeslot format is invalid to prevent failures.
2026-11-15 16:45:04 +01:00
Jérémy Munsch
bd314a4575
fix(middlewares): handle guest and auth redirects correctly
Ensure that both guest and authenticated user redirects are processed properly.
2026-11-15 16:45:04 +01:00
Jérémy Munsch
341a66a2d1
fix(order): ensure validated status for orders with lines and shop
This change adds a condition to filter orders by validated status
when retrieving orders with lines and shop for a specific pickup day.
2026-11-15 16:45:04 +01:00
Jérémy Munsch
8c484ae053
fix(auth): correct Gate usage for customer permissions
Updated the Gate check to use forUser method for proper customer context.
2026-11-15 16:45:03 +01:00
Jérémy Munsch
3426ea22a9
security(auth): enforce active employment and email verification on password reset 2026-11-15 16:45:03 +01:00
Jérémy Munsch
ff780a7a46
security(contact): throttle contact submissions and idempotently delete S3 attachments via SendContactMailJob 2026-11-15 16:45:03 +01:00
Jérémy Munsch
3c34f4af28
fix(http): restrict trusted proxy headers to Traefik and prefer X-Real-Ip 2026-11-15 16:45:02 +01:00
Jérémy Munsch
4771ef9a72
fix(auth): prevent registration on already assigned employee 2026-11-15 16:45:02 +01:00
Jérémy Munsch
455bcd4988
fix(holidays): preserve current year holidays and add daily catch-up sync 2026-11-15 16:45:02 +01:00
Jérémy Munsch
6dfef2c7a1
feat(cqs): buffer domain events until commit and add action lifecycle hooks 2026-11-15 16:45:01 +01:00
Jérémy Munsch
79ae763e88
fix(orders): serialize order finalization with distributed lock via #[Locked] attribute 2026-11-15 16:45:01 +01:00
Jérémy Munsch
4c3fa373da
fix(orders): revalidate timeslot cutoff, product orderability and use contractual FinalizeOrderOutput 2026-11-15 16:45:01 +01:00
Jérémy Munsch
9c537d83b2
chore: add linting command to composer scripts
This enhances the development workflow by integrating a linting command
that checks code quality and style before commits.
2026-11-15 16:45:00 +01:00
Jérémy Munsch
93e4b202da
feat(products): enhance product form data with additional fields
Added support for new product attributes including tax rate, invoicing unit, order unit, and orderable dates. Updated related queries and views to accommodate these changes.
2026-11-15 16:45:00 +01:00
Jérémy Munsch
97f6085622
test(isolation): decouple unit and integration tests from service container and enforce arch rules 2026-11-15 16:45:00 +01:00
Jérémy Munsch
758fec824d
refactor(phpstan): reach PHPStan level 10 compliance and enforce global namespace prefixes 2026-11-15 16:44:59 +01:00
Jérémy Munsch
3af75ac974
feat(uploads): enforce MIME/extension validation and display upload rules on BO/FO forms 2026-11-15 16:44:59 +01:00
Jérémy Munsch
5d715094d1
refactor(cqs): delegate job, command and listener mutations to CQS actions via Executor 2026-11-15 16:44:59 +01:00
Jérémy Munsch
9808ef9769
refactor(products): decouple views, policies and queries from Eloquent model via ProductDtoAssemblerService 2026-11-15 16:44:58 +01:00
Jérémy Munsch
cfba7f4756
refactor(storage): migrate media models, basket value objects and CQS actions to S3 2026-11-15 16:44:58 +01:00
Jérémy Munsch
0684215511
feat(storage): add S3 disks, temporary file factory and image optimizer service 2026-11-15 16:44:58 +01:00
Jérémy Munsch
e4db1a476d
refactor(infra): configure PVC-less volumes, /tmp purifier cache and S3 CSP headers 2026-11-15 16:44:57 +01:00
Jérémy Munsch
4a9af4a90a
refactor(database): squash migrations into mysql-schema.sql and harden Setting singleton 2026-11-15 16:44:57 +01:00
Jérémy Munsch
f7a20c9d5d
style(queue): apply consistent formatting and add strict types
Improves code readability and enforces strict typing in queue configuration.
2026-11-15 16:44:57 +01:00
Jérémy Munsch
ba077f88b4
chore(dependencies): update AWS SDK and Flysystem packages
Updated dependencies for AWS SDK and Flysystem to ensure compatibility and access to the latest features.
2026-11-15 16:44:56 +01:00
Jérémy Munsch
30bfabfaf1
chore: remove some dead code 2026-11-15 16:44:56 +01:00
Jérémy Munsch
1fc311ee7e
refactor(env): update session and Redis configuration
Improved clarity and consistency in the environment configuration.
2026-11-15 16:44:55 +01:00
Jérémy Munsch
6bd1273f78
refactor(config): update Redis scheme handling
Ensure Redis scheme defaults to 'tcp' if not specified.
2026-11-15 16:44:55 +01:00
Jérémy Munsch
0ee0d7cce7
refactor: update configuration files for improved structure
- Added new database and queue configuration files.
- Enhanced .env.example with additional environment variables.
- Updated manifest.yaml for better deployment settings.
2026-11-15 16:44:55 +01:00
Jérémy Munsch
8b8ee17246
refactor: restore laravel 13 default configs for cache, filesystems and session 2026-11-15 16:44:54 +01:00
1021 changed files with 38159 additions and 22404 deletions

View file

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

View file

@ -79,7 +79,11 @@ phpstan:
variables: variables:
PHP_MEMORY_LIMIT: "512M" PHP_MEMORY_LIMIT: "512M"
COMPOSER_CACHE_DIR: ".composer-cache" COMPOSER_CACHE_DIR: ".composer-cache"
CRM_ENDPOINT: "http://fake-url.com"
CRM_TOKEN: "fake-token"
CRM_PASSWORD: "fake-password"
script: script:
- cp .env.example .env
- php -d memory_limit=512M vendor/bin/phpstan --error-format=junit > phpstan-report.xml - php -d memory_limit=512M vendor/bin/phpstan --error-format=junit > phpstan-report.xml
artifacts: artifacts:
when: on_failure when: on_failure
@ -253,12 +257,29 @@ tests_laravel:
- name: mysql:8.0 - name: mysql:8.0
alias: mysql alias: mysql
before_script: before_script:
- apk add --no-cache mariadb-client mariadb-connector-c icu-data-full
- printf "[client]\nssl=0\n" > ~/.my.cnf
- composer config gitlab-token.lab.s-web.fr $CI_DEPLOY_USER $CI_DEPLOY_PASSWORD - composer config gitlab-token.lab.s-web.fr $CI_DEPLOY_USER $CI_DEPLOY_PASSWORD
- composer install --no-scripts --no-interaction --no-ansi --no-progress --prefer-dist - composer install --no-scripts --no-interaction --no-ansi --no-progress --prefer-dist
script: script:
- cp .env.example .env - cp .env.example .env
- php artisan key:generate - php artisan key:generate
- php -r "while(true){try{new PDO('mysql:host=mysql;dbname=testing_db','root','password');break;}catch(Exception){sleep(1);}}" - |
php -r '
while (true) {
try {
$pdo = new PDO("mysql:host=mysql;dbname=testing_db", "root", "password");
$account = (string) $pdo->query("SELECT CURRENT_USER()")->fetchColumn();
[$user, $host] = explode("@", $account, 2);
$pdo->exec("ALTER USER " . $pdo->quote($user) . "@" . $pdo->quote($host) . " IDENTIFIED WITH mysql_native_password BY " . $pdo->quote("password"));
$pdo->exec("FLUSH PRIVILEGES");
break;
} catch (Exception) {
sleep(1);
}
}
'
- mysql --user=root --password=password --host=mysql --port=3306 --database=testing_db -e "SELECT 1"
- php artisan config:clear - php artisan config:clear
- php artisan test --coverage --colors=never --log-junit=coverage/junit.xml --coverage-cobertura=coverage/cobertura.xml --coverage-html=coverage/html - php artisan test --coverage --colors=never --log-junit=coverage/junit.xml --coverage-cobertura=coverage/cobertura.xml --coverage-html=coverage/html
after_script: after_script:

View file

@ -7,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`. La sélection du retrait se fait désormais sur une journée complète et non plus par tranches horaires via `PickupSchedulingService`.
- **Jour de retrait standard** : Uniquement le **Vendredi** (`PICKUP_DAY = WeekDay::Friday`). - **Jour de retrait standard** : Uniquement le **Vendredi** (`PICKUP_DAY = WeekDay::Friday`).
- **Heure de clôture (Cutoff)** : **Lundi à 14h00** de la même semaine (`CUTOFF_DAY = Monday`, `CUTOFF_HOUR = 14`). - **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 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. - *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.
- **Gestion des Exceptions** : - *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`. - Les fermetures et jours fériés sont gérés via des `ShopPickupException`.
- Une exception peut **fermer le retrait**, ou proposer un **jour de remplacement**. Ce jour de remplacement peut posséder sa propre limite de validation (`orderDeadlineAt`). - Une exception peut **fermer le retrait**, ou proposer un **jour de remplacement**. Ce jour de remplacement peut posséder sa propre limite de validation (`orderDeadlineAt`).
- Une tâche planifiée `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 ## 2. Limites de Montants
@ -31,3 +37,61 @@ Elle est géré par le service `ProductAvailabilityService`.
- Il est éligible INCO (`hasInco = true`). - Il est éligible INCO (`hasInco = true`).
- La date actuelle est supérieure ou égale à `orderable_start` (si défini). - La date actuelle est supérieure ou égale à `orderable_start` (si défini).
- La date actuelle est inférieure à `orderable_end` (si défini). - La date actuelle est inférieure à `orderable_end` (si défini).
## 4. Statut Actif du Salarié
Elle est vérifiée côté Domaine par `Shopper::isActive()` et côté Eloquent par `Employee::isActive` / `Employee::scopeActive()`.
- **Fuseau calendaire (`Europe/Paris`)** :
- En base de données, `start_date` et `end_date` sont des colonnes SQL `DATE` (sans heure ni fuseau, chargées via `CalendarDateCast`).
- L'activation et la désactivation sont évaluées par rapport à la date calendaire du jour en **`Europe/Paris`** (`00:00:00 Europe/Paris`), afin d'éviter le décalage nocturne de 1 h à 2 h lié à UTC.
- **Date de début (`start_date`)** :
- Le salarié est actif lorsque `start_date` est inférieure ou égale au jour courant en `Europe/Paris` (ou si `start_date` est `null` en base de données).
- Un salarié dont la `start_date` est dans le futur est considéré comme **inactif** jusqu'à la date d'effet (`00:00:00 Europe/Paris` du jour de début).
- **Date de fin (`end_date`)** :
- Le salarié est actif uniquement si `end_date` est `null` ou strictement supérieure au jour courant en `Europe/Paris` (`end_date > aujourd'hui Europe/Paris`).
- **Comportement assumé** : le salarié devient donc inactif dès `00:00:00 Europe/Paris` de son dernier jour renseigné (`end_date`).
## 5. Cycle de Vie, Tunnel de Commande & Annulation (Back-Office)
### Statuts des commandes (`Domain\Enums\OrderStatus`)
- **`WAITING` (`'waiting'`)** : reliquat historique des commandes créées avant la refonte (paniers non transformés). Conservé en lecture dans les statistiques historiques.
- **`PENDING` (`'pending'`)** : commande technique créée lors de `PlacePendingOrder` avant l'export Régate. Elle est comptabilisée dans le plafond hebdomadaire de 200 € (`EloquentEmployeeStatisticsService`), masquée en Front-Office (`GetFoCustomerPaginatedOrdersQuery`, `Frontend\OrderPolicy::viewOwn`) et masquée par défaut en Back-Office (affichable à la demande via le filtre statut).
- **`VALIDATED` (`'validated'`)** : commande confirmée après succès de l'export Régate (`ConfirmPlacedOrder`).
- **`FAILED` (`'failed'`)** : statut technique en cas d'échec de l'export Régate (`FailPendingOrder`) ou d'expiration d'une commande `PENDING` bloquée au-delà de 10 minutes (`FailStalePendingOrders` / `FailStalePendingOrdersJob`, planifié toutes les 5 minutes). Masqué en Front-Office, affichable à la demande en Back-Office, exclu du plafond hebdomadaire et des statistiques.
- **`CANCELED` (`'canceled'`)** : annulation métier (Back-Office ou Régate).
### Concurrence du tunnel & suivi des paniers non transformés
- Lors de la soumission finale (`TunnelController::confirmationSubmit()`), un verrou distribué non bloquant (`order:checkout:shopper:{id}`, `waitSeconds: 0`, TTL `60s`) protège la séquence synchrone `PlacePendingOrder` (elle-même protégée par `#[Locked]` sur `order:finalize:shopper:{id}`) → `ExportOrderToRegate` → `ConfirmPlacedOrder` / `FailPendingOrder`.
- Les entrées dans le tunnel (étape 1, `OrderTunnelService::initializeFromBasket`) créent ou réutilisent une tentative en session dans `order_tunnel_attempts` (`TunnelAttemptTrackerService::recordEntry`), marquée convertie lors de la validation (`markConverted`) ou réinitialisée en session si le panier est vidé (`BasketRemoved` → `ResetTunnelAttemptOnBasketRemoved`). `StatsService::getNbWaitingCmd()` (et `getCanceledRate()`) additionnent les commandes historiques `WAITING` et les tentatives `order_tunnel_attempts` non converties (`converted_at IS NULL`).
### Annulation de Commande (Back-Office)
Elle est autorisée côté HTTP par `App\Policies\Backend\OrderPolicy::cancel()` et exécutée côté Domaine par `Domain\Services\OrderService::cancelOrder()`.
- **Statuts autorisés & date de retrait (`pickup_day`)** : `Backend\OrderPolicy::cancel()` interdit d'annuler une commande déjà `CANCELED`, `PENDING` ou `FAILED`, mais autorise intentionnellement un administrateur à annuler toute commande métier (`WAITING` ou `VALIDATED`), y compris lorsque `pickup_day` est déjà dépassé (rattrapage/correction administrative).
- **Comportement assumé** : l'annulation d'une commande depuis le Back-Office met uniquement à jour son statut en base de données (`cancel()` puis `persist()`) sans émettre d'événement de domaine ni envoyer d'e-mail ou de notification à Régate ou au client.
## 6. Code d'Accès Salarié & Inscription
La génération des codes d'accès salariés est gérée par `App\Services\CodeGenerationService` et leur validation à l'inscription par `App\Http\Requests\Fo\Auth\RegisterRequest`.
- **Génération déterministe du code** :
- Chaque code d'accès (`Code`, longueur `7`) est dérivé de façon déterministe à partir du `matricule` du salarié via `SerialCasterBuilder` (`Code::ALLOWED_CHARACTERS`, `Code::LENGTH`). Il ne s'agit pas d'un secret aléatoire, mais d'un code d'appariement court lié au matricule.
- **Validation à l'inscription (`RegisterRequest`)** :
- L'existence d'un `matricule` non encore associé à un compte client (`employees.customer_id IS NULL`) est validée explicitement (`Rule::exists('employees', 'matricule')->whereNull('customer_id')`), séparément de la règle sur `code` (`Rule::exists('employees', 'code')->where('matricule', ...)->whereNull('customer_id')`).
- Les messages d'erreur distincts entre « matricule inconnu / déjà utilisé » et « code incorrect » sont assumés pour faciliter le support utilisateur, les routes d'authentification étant protégées par un rate limiter (`throttle`).
## 7. Connexion d'un Compte Non Activé (CRM & `laravel/ui`)
Elle est gérée par `App\Auth\CrmUserProvider::validateCredentials()` et `App\Http\Controllers\Fo\Auth\LoginController::authenticated()`.
- **Validation CRM (`CrmService::login()`)** :
- L'API CRM (`Api\V4\CustomerController::authenticate()`) vérifie **d'abord** le mot de passe (`ApiError::authFailed`) avant de vérifier si le compte est activé (`ApiError::customerNotActivated` → `CrmCustomerNotActivatedException`).
- **Alignement sur `laravel/ui` (`VerificationController`)** :
- Conformément au fonctionnement standard de `laravel/ui`, `VerificationController` requiert une session authentifiée (`auth:frontend`) pour accéder aux routes `email/verify`, `email/verify/{id}/{hash}` et `email/resend`.
- Lorsqu'un client saisit le **bon mot de passe** sur un compte non encore activé, `CrmUserProvider::validateCredentials()` intercepte `CrmCustomerNotActivatedException`, renvoie l'e-mail de vérification et retourne `true` afin d'ouvrir la session et de laisser le middleware `verified` (`EnsureCustomerEmailIsVerified`) rediriger vers `fo.auth.verification.notice`.
- En revanche, `LoginController::authenticated()` ne flashe le message `"You are logged in!"` que si l'e-mail du client est déjà vérifié (`AppCustomerAuthService::hasVerifiedEmail()`).

24
app/Attributes/Locked.php Normal file
View 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));
}
}
}

View file

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

View file

@ -9,23 +9,16 @@ use App\Exceptions\Crm\CrmCustomerNotActivatedException;
use App\Exceptions\CrmServiceException; use App\Exceptions\CrmServiceException;
use App\Models\Customer; use App\Models\Customer;
use App\Services\CrmService; use App\Services\CrmService;
use Domain\Models\ValueObjects\CrmCustomer;
use Domain\Models\ValueObjects\Email;
use Illuminate\Auth\EloquentUserProvider; use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Hashing\Hasher; use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use Shared\ValueObjects\CrmHashcode;
use UnexpectedValueException;
class CrmUserProvider extends EloquentUserProvider implements UserProvider class CrmUserProvider extends EloquentUserProvider implements UserProvider
{ {
private ?CrmCustomer $crmCustomer = null;
/** /**
* @param class-string<\Illuminate\Contracts\Auth\Authenticatable&\Illuminate\Database\Eloquent\Model> $model * @param class-string<\Illuminate\Contracts\Auth\Authenticatable&\Illuminate\Database\Eloquent\Model> $model
*/ */
@ -56,7 +49,12 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
#[\Override] #[\Override]
public function retrieveByCredentials(array $credentials): ?Authenticatable public function retrieveByCredentials(array $credentials): ?Authenticatable
{ {
$model = parent::retrieveByCredentials($credentials); $model = parent::retrieveByCredentials($credentials);
if ($model === null) {
return null;
}
$result = $this->crmService->getCustomerFromEmail(Arr::string($credentials, 'email')); $result = $this->crmService->getCustomerFromEmail(Arr::string($credentials, 'email'));
if ($result instanceof CrmServiceException) { if ($result instanceof CrmServiceException) {
@ -66,13 +64,7 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
]); ]);
} }
$this->crmCustomer = $result; return $result !== null ? $model : null;
if ($this->crmCustomer instanceof CrmCustomer && $model === null) {
$model = $this->createLocalCustomer($this->crmCustomer);
}
return $this->crmCustomer !== null ? $model : null;
} }
/** /**
@ -88,11 +80,11 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
public function validateCredentials(Authenticatable $model, array $credentials): bool public function validateCredentials(Authenticatable $model, array $credentials): bool
{ {
if ($model::class !== $this->usedModel) { if ($model::class !== $this->usedModel) {
throw new UnexpectedValueException("Cannot authenticate any thing else than '{$this->usedModel}'"); throw new \UnexpectedValueException("Cannot authenticate any thing else than '{$this->usedModel}'");
} }
if (! in_array(MustVerifyEmail::class, \class_implements($model))) { if (! in_array(MustVerifyEmail::class, \class_implements($model))) {
throw new UnexpectedValueException("Model '{$this->usedModel}' should implement 'MustVerifyEmail'"); throw new \UnexpectedValueException("Model '{$this->usedModel}' should implement 'MustVerifyEmail'");
} }
/** @var \Illuminate\Contracts\Auth\Authenticatable&\Illuminate\Contracts\Auth\MustVerifyEmail $model */ /** @var \Illuminate\Contracts\Auth\Authenticatable&\Illuminate\Contracts\Auth\MustVerifyEmail $model */
$requestEmail = Arr::string($credentials, 'email'); $requestEmail = Arr::string($credentials, 'email');
@ -106,7 +98,11 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
return true; return true;
} catch (CrmCustomerNotActivatedException) { } catch (CrmCustomerNotActivatedException) {
$model->sendEmailVerificationNotification(); try {
$model->sendEmailVerificationNotification();
} catch (\Throwable $e) {
report($e);
}
return true; return true;
} catch (CrmAuthenticationFailedException) { } catch (CrmAuthenticationFailedException) {
@ -125,26 +121,4 @@ class CrmUserProvider extends EloquentUserProvider implements UserProvider
{ {
// No hashing. // No hashing.
} }
private function createLocalCustomer(CrmCustomer $crmCustomer): Model & Authenticatable
{
$email = $crmCustomer->email ?
new Email($crmCustomer->email) :
throw new UnexpectedValueException('Email is required ti create a customer');
$hashcode = $crmCustomer->hashcode ?
$crmCustomer->hashcode :
throw new UnexpectedValueException('Hashcode is required to create a customer');
/** @var \App\Models\Customer&\Illuminate\Contracts\Auth\Authenticatable $model */
$model = $this->usedModel::query()
->where('email', $crmCustomer->email)
->firstOrNew();
$model->email = $email;
$model->hashcode = CrmHashcode::fromString($hashcode);
$model->saveOrFail();
return $model;
}
} }

View file

@ -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.');
}
}

View file

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

View 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.');
}
}

View file

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

View 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.');
}
}

View file

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

View file

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

View file

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

View file

@ -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;
}

View file

@ -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;
}

View file

@ -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;
}

View file

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

View 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;
}

View 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;
}

View 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;
}

View 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;
}

View file

@ -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;
}

View file

@ -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;
}

View file

@ -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;
}

View file

@ -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
{
}

View 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();
}
}

View 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)
);
}
}

View 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);
}
}

View 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,
);
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -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);
}
}
}
}

View 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));
}
}

View file

@ -4,34 +4,78 @@ declare(strict_types=1);
namespace App\Cqs\Actions\Customers; namespace App\Cqs\Actions\Customers;
use App\Attributes\Locked;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Contracts\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\Crm\CrmCustomerExistsException;
use App\Exceptions\CrmServiceException; use App\Exceptions\CrmServiceException;
use App\Models\Customer; use App\Models\Customer;
use App\Models\Employee;
use App\Services\CrmService; use App\Services\CrmService;
use Domain\Enums\Country; use Domain\Enums\Country;
use Domain\Models\ValueObjects\CrmCustomer; use Domain\Models\ValueObjects\CrmCustomer;
use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use Infrastructure\Adapters\Services\AppCustomerAuthService; use Infrastructure\Adapters\Services\AppCustomerAuthService;
use Ramsey\Uuid\Uuid; use Shared\Helpers\UuidHelper;
use Shared\ValueObjects\CrmHashcode; use Shared\ValueObjects\CrmHashcode;
use Webmozart\Assert\Assert; 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( public function __construct(
private readonly AppCustomerAuthService $authService, private readonly AppCustomerAuthService $authService,
private readonly CrmService $crmService, private readonly CrmService $crmService,
private readonly EmployeeRepository $employeeRepository,
) { ) {
} }
/**
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
*/
#[\Override]
public function lockKey(ActionInput $input): string
{
Assert::isInstanceOf($input, RegisterCustomerInput::class);
return "customer:register:employee:{$input->matricule->value}";
}
/**
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
*/
#[\Override]
public function onLockTimeout(ActionInput $input): RegisterCustomerOutput
{
Assert::isInstanceOf($input, RegisterCustomerInput::class);
return RegisterCustomerOutput::lockTimeout();
}
/** /**
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input * @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
* *
@ -40,27 +84,39 @@ final class RegisterCustomer implements Action
* @throws ModelNotFoundException * @throws ModelNotFoundException
*/ */
#[\Override] #[\Override]
public function __invoke(ActionInput $input): Customer public function __invoke(ActionInput $input): RegisterCustomerOutput
{ {
Assert::isInstanceOf($input, RegisterCustomerInput::class); Assert::isInstanceOf($input, RegisterCustomerInput::class);
$inputKey = spl_object_id($input);
unset($this->createdCrmCustomers[$inputKey]);
$employee = Employee::query()
->where('matricule', $input->matricule->value)
->where('code', $input->code->value)
->lockForUpdate()
->first();
if (! $employee) {
throw new ModelNotFoundException('Employee not found');
}
if ($employee->customer_id !== null) {
return RegisterCustomerOutput::employeeAlreadyRegistered();
}
if (! $employee->is_active) {
return RegisterCustomerOutput::employeeInactive();
}
// * Persist and associate Customer + Employee // * Persist and associate Customer + Employee
$customer = new Customer([ $customer = new Customer([
'email' => $input->email, 'email' => $input->email,
]); ]);
// * Temp hashcode to satisfy constraint // * Temp hashcode to satisfy constraint
$customer->hashcode = new CrmHashcode(Uuid::uuid4()); $customer->hashcode = new CrmHashcode(UuidHelper::v4());
$customer->saveOrFail(); $customer->saveOrFail();
$employee = $this->employeeRepository->findByMatriculeAndCode(
$input->matricule,
$input->code
);
if (! $employee) {
throw new ModelNotFoundException('Employee not found');
}
$employee->customer()->associate($customer); $employee->customer()->associate($customer);
$employee->saveOrFail(); $employee->saveOrFail();
@ -84,21 +140,6 @@ final class RegisterCustomer implements Action
try { try {
$result = $this->crmService->persist($crmCustomer); $result = $this->crmService->persist($crmCustomer);
if (! $result->hashcode) {
throw new \UnexpectedValueException(
'CRM did not return a hashcode for the created customer'
);
}
$customer->hashcode = CrmHashcode::fromString($result->hashcode);
$customer->saveOrFail();
$customer->sendEmailVerificationNotification();
$this->authService->logIn($customer);
return $customer;
} catch (CrmCustomerExistsException) { } catch (CrmCustomerExistsException) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'error' => trans('An account is already associated with this email address'), 'error' => trans('An account is already associated with this email address'),
@ -109,5 +150,70 @@ final class RegisterCustomer implements Action
'error' => trans('An error has occurred. Please try again later'), 'error' => trans('An error has occurred. Please try again later'),
]); ]);
} }
if (! $result->hashcode) {
throw new \UnexpectedValueException(
'CRM did not return a hashcode for the created customer'
);
}
$crmHashcode = CrmHashcode::fromString($result->hashcode);
$this->createdCrmCustomers[$inputKey] = [
'hashcode' => $crmHashcode,
'email' => $input->email,
];
$customer->hashcode = $crmHashcode;
$customer->saveOrFail();
return RegisterCustomerOutput::success($customer);
}
/**
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
* @param \App\Cqs\Actions\Customers\RegisterCustomerOutput $result
*/
#[\Override]
public function onSuccess(ActionInput $input, mixed $result): void
{
Assert::isInstanceOf($input, RegisterCustomerInput::class);
Assert::isInstanceOf($result, RegisterCustomerOutput::class);
unset($this->createdCrmCustomers[spl_object_id($input)]);
if ($result->status !== RegisterCustomerStatus::SUCCESS || ! $result->customer instanceof Customer) {
return;
}
$this->authService->logIn($result->customer);
try {
$result->customer->sendEmailVerificationNotification();
} catch (\Throwable $e) {
report($e);
}
}
/**
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
*/
#[\Override]
public function onFailure(ActionInput $input, \Throwable $exception): void
{
Assert::isInstanceOf($input, RegisterCustomerInput::class);
$inputKey = spl_object_id($input);
$createdCrm = $this->createdCrmCustomers[$inputKey] ?? null;
unset($this->createdCrmCustomers[$inputKey]);
if ($createdCrm === null) {
return;
}
try {
$this->crmService->deleteByHashcode($createdCrm['hashcode'], $createdCrm['email']);
} catch (\Throwable $e) {
report($e);
}
} }
} }

View file

@ -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,
);
}
}

View 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;
}
}

View 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,
) {
}
}

View file

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

View file

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

View 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,
);
}
}

View file

@ -6,16 +6,16 @@ namespace App\Cqs\Actions\Orders;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use Domain\Services\OrderService as DomainOrderService; use Domain\Services\OrderService;
use Webmozart\Assert\Assert; 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 final class CancelOrder implements Action
{ {
public function __construct( 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 * @param \App\Cqs\Actions\Orders\CancelOrderInput $input
*/ */
#[\Override] #[\Override]
public function __invoke(ActionInput $input): void public function __invoke(ActionInput $input): CancelOrderOutput
{ {
Assert::isInstanceOf($input, CancelOrderInput::class); 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;
} }
} }

View file

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

View 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;
}
}

View 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,
) {
}
}

View 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;
}
}

View 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,
) {
}
}

View file

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

View 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;
}
}

View 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,
) {
}
}

View file

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

View 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;
}
}

View 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,
) {
}
}

View 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;
}

View 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;
}
}

View 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);
}
}

View file

@ -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;
}
}

View 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);
}
}

View file

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

View 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,
);
}
}

View 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;
}
}

View 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,
) {
}
}

View file

@ -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));
}
}

View file

@ -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);
}
}

View file

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

View file

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

View file

@ -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,
);
}
}

View file

@ -11,7 +11,10 @@ use App\Services\ArcadiaIncoService;
use Webmozart\Assert\Assert; 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 final class SyncProductInco implements Action
{ {
@ -24,31 +27,31 @@ final class SyncProductInco implements Action
* @param \App\Cqs\Actions\ProductIncos\SyncProductIncoInput $input * @param \App\Cqs\Actions\ProductIncos\SyncProductIncoInput $input
*/ */
#[\Override] #[\Override]
public function __invoke(ActionInput $input): ProductInco public function __invoke(ActionInput $input): SyncProductIncoOutput
{ {
Assert::isInstanceOf($input, SyncProductIncoInput::class); Assert::isInstanceOf($input, SyncProductIncoInput::class);
$inco = $input->product->inco; $inco = ProductInco::query()
->where('product_id', $input->productId->value->toString())
->first();
if ($inco === null) { 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) { 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->hydrateFromArcadiaDto($incoData);
$inco->preparation = $incoData->preparation;
$inco->servings = $incoData->servings;
$inco->allergens = $incoData->allergens;
$inco->selling_argument = $incoData->sellingArgument;
$inco->nutriscore = $incoData->nutriscore;
$inco->nutriscore_args = $incoData->nutriscoreArgs;
$inco->nutrition = $incoData->nutrition;
$inco->saveOrFail(); $inco->saveOrFail();
return $inco; return SyncProductIncoOutput::success($inco);
} }
} }

View file

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

View 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,
);
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -6,14 +6,33 @@ namespace App\Cqs\Actions\Ranges;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesSuccess;
use App\Lib\PublicS3Disk;
use App\Models\Range; use App\Models\Range;
use App\Services\ImageOptimizerService;
use App\Traits\TracksPendingStoragePaths;
use Illuminate\Http\UploadedFile;
use Uwil\Storage\Contracts\StorageService;
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Ranges\CreateRangeInput, \App\Models\Range> * @implements \App\Contracts\Action<\App\Cqs\Actions\Ranges\CreateRangeInput, \App\Models\Range>
* @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Ranges\CreateRangeInput, \App\Models\Range>
* @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Ranges\CreateRangeInput>
*/ */
final class CreateRange implements Action 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 * @param \App\Cqs\Actions\Ranges\CreateRangeInput $input
*/ */
@ -30,8 +49,10 @@ final class CreateRange implements Action
'status' => $input->status, 'status' => $input->status,
]; ];
if ($input->picture !== null) { if ($input->picture instanceof UploadedFile) {
$attributes['picture'] = $input->picture; $storedPath = $this->storeFile($input->picture);
$attributes['picture'] = $storedPath;
$this->trackUploadedPath($input, $storedPath);
} }
$range = new Range(); $range = new Range();
@ -40,4 +61,27 @@ final class CreateRange implements Action
return $range; return $range;
} }
#[\Override]
public function onSuccess(ActionInput $input, mixed $result): void
{
$this->clearTrackedPaths($input);
}
#[\Override]
public function onFailure(ActionInput $input, \Throwable $exception): void
{
foreach ($this->pullUploadedPaths($input) as $path) {
if ($this->storageService->fileExistsOnDisk($path, $this->s3Disk->disk)) {
$this->storageService->removeFromDisk($path, $this->s3Disk->disk);
}
}
}
protected function storeFile(UploadedFile $file): StorageFilePath
{
$optimized = $this->imageOptimizerService->optimize($file);
return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk);
}
} }

View file

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

View file

@ -6,13 +6,28 @@ namespace App\Cqs\Actions\Ranges;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesSuccess;
use App\Lib\PublicS3Disk;
use App\Traits\TracksPendingStoragePaths;
use Uwil\Storage\Contracts\StorageService;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Ranges\DeleteRangeInput, bool> * @implements \App\Contracts\Action<\App\Cqs\Actions\Ranges\DeleteRangeInput, bool>
* @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Ranges\DeleteRangeInput, bool>
* @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Ranges\DeleteRangeInput>
*/ */
final class DeleteRange implements Action 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 * @param \App\Cqs\Actions\Ranges\DeleteRangeInput $input
*/ */
@ -21,6 +36,29 @@ final class DeleteRange implements Action
{ {
Assert::isInstanceOf($input, DeleteRangeInput::class); 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);
} }
} }

View file

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

View file

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

View file

@ -6,7 +6,9 @@ namespace App\Cqs\Actions\Shops;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Models\PickupException;
use App\Models\Shop; use App\Models\Shop;
use Illuminate\Support\Facades\Date;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
@ -37,6 +39,15 @@ final class CreateShop implements Action
$shop->default = $input->default; $shop->default = $input->default;
$shop->saveOrFail(); $shop->saveOrFail();
$publicHolidays = PickupException::query()
->where('auto_updated', true)
->where('date', '>=', Date::now('Europe/Paris')->startOfYear()->format('Y-m-d'))
->get();
if ($publicHolidays->isNotEmpty()) {
$shop->pickupExceptions()->syncWithoutDetaching($publicHolidays);
}
return $shop; return $shop;
} }
} }

View file

@ -6,15 +6,34 @@ namespace App\Cqs\Actions\Slides;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesSuccess;
use App\Lib\PublicS3Disk;
use App\Models\Slide; use App\Models\Slide;
use App\Services\ImageOptimizerService;
use App\Traits\TracksPendingStoragePaths;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Uwil\Storage\Contracts\StorageService;
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Slides\CreateSlideInput, \App\Models\Slide> * @implements \App\Contracts\Action<\App\Cqs\Actions\Slides\CreateSlideInput, \App\Models\Slide>
* @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Slides\CreateSlideInput, \App\Models\Slide>
* @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Slides\CreateSlideInput>
*/ */
final class CreateSlide implements Action 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 * @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, 'date_end' => $input->period->end !== null ? Carbon::instance($input->period->end) : null,
]; ];
if ($input->picture !== null) { if ($input->picture instanceof UploadedFile) {
$attributes['picture'] = $input->picture; $storedPath = $this->storeFile($input->picture);
$attributes['picture'] = $storedPath;
$this->trackUploadedPath($input, $storedPath);
} }
$slide = new Slide(); $slide = new Slide();
@ -46,4 +67,27 @@ final class CreateSlide implements Action
return $slide; return $slide;
} }
#[\Override]
public function onSuccess(ActionInput $input, mixed $result): void
{
$this->clearTrackedPaths($input);
}
#[\Override]
public function onFailure(ActionInput $input, \Throwable $exception): void
{
foreach ($this->pullUploadedPaths($input) as $path) {
if ($this->storageService->fileExistsOnDisk($path, $this->s3Disk->disk)) {
$this->storageService->removeFromDisk($path, $this->s3Disk->disk);
}
}
}
protected function storeFile(UploadedFile $file): StorageFilePath
{
$optimized = $this->imageOptimizerService->optimize($file);
return $this->storageService->storeFileOntoDisk($optimized, $this->s3Disk->disk);
}
} }

View file

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

View file

@ -6,13 +6,28 @@ namespace App\Cqs\Actions\Slides;
use App\Contracts\Action; use App\Contracts\Action;
use App\Contracts\ActionInput; use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesSuccess;
use App\Lib\PublicS3Disk;
use App\Traits\TracksPendingStoragePaths;
use Uwil\Storage\Contracts\StorageService;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
/** /**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Slides\DeleteSlideInput, bool> * @implements \App\Contracts\Action<\App\Cqs\Actions\Slides\DeleteSlideInput, bool>
* @implements \App\Contracts\HandlesSuccess<\App\Cqs\Actions\Slides\DeleteSlideInput, bool>
* @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Slides\DeleteSlideInput>
*/ */
final class DeleteSlide implements Action 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 * @param \App\Cqs\Actions\Slides\DeleteSlideInput $input
*/ */
@ -21,6 +36,29 @@ final class DeleteSlide implements Action
{ {
Assert::isInstanceOf($input, DeleteSlideInput::class); 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);
} }
} }

View file

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

View file

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

View file

@ -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,
]);
}
}
}

View 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;
}
}

View 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);
}
}

View file

@ -7,12 +7,15 @@ namespace App\Cqs\Queries\Basket;
use App\Contracts\Query; use App\Contracts\Query;
use App\Contracts\QueryInput; use App\Contracts\QueryInput;
use App\Contracts\QueryInputEmpty; use App\Contracts\QueryInputEmpty;
use 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 Domain\Services\BasketService;
use Webmozart\Assert\Assert; 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 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( Assert::isAOf(
$input, $input,
QueryInputEmpty::class, 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);
} }
} }

View file

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

View file

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

View file

@ -9,6 +9,7 @@ use App\Contracts\QueryInput;
use App\Dto\OrderDto; use App\Dto\OrderDto;
use App\Models\Order; use App\Models\Order;
use App\Services\DataTableService; use App\Services\DataTableService;
use Domain\Enums\OrderStatus;
use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Date;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
@ -35,7 +36,9 @@ final readonly class GetBoTodayOrdersQuery implements Query
{ {
Assert::isInstanceOf($input, GetBoTodayOrdersQueryInput::class); 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()); $query->whereCreatedAtBetween(Date::now(), Date::now());

View file

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

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