Compare commits
492 Commits
auth/googl
...
tennant/on
| Author | SHA1 | Date | |
|---|---|---|---|
| a4a8a3ef8f | |||
| f5f4cb4e87 | |||
| d33b435ba5 | |||
| 969e99b3ae | |||
| 3e3b3bfac0 | |||
| f4de2ff5b2 | |||
| fcb8386735 | |||
| 6d077647ba | |||
| 14c81fec1b | |||
| 9a14b8fbbd | |||
| c665222837 | |||
| d61a5d459d | |||
| 8395c7f24d | |||
| 79d402e210 | |||
| b0702b7e15 | |||
| dc5134a6ec | |||
| 801d25b218 | |||
| f6e8716218 | |||
| 8d2250d247 | |||
| 22ef5619f3 | |||
| cdc17a13e2 | |||
| ee9f2ba538 | |||
| 0170a2eabb | |||
| 1e67d27a90 | |||
| 1241e1f7e8 | |||
| 4659c1049d | |||
| 49be167029 | |||
| 164187f47b | |||
| 5aad43f2e3 | |||
| eb1e4df63f | |||
| 131eb1a7ee | |||
| 486129a92f | |||
| 6bc784519f | |||
| b9b5f8ec9c | |||
| 8595300071 | |||
| 5503559899 | |||
| 7323707424 | |||
| 830f65c402 | |||
| df6892c662 | |||
| de08ee4ac7 | |||
| 1269ebcda0 | |||
| 04e54fefad | |||
| a46bf905e8 | |||
| 353fd34db2 | |||
| f8a3296821 | |||
| 9aa0c1f3b9 | |||
| 708037677a | |||
| e6b5da366c | |||
| 69bea10519 | |||
| 3d6548ce4a | |||
| 8ad9b3a4e3 | |||
| 3a4f6b64d2 | |||
| 44178d72a5 | |||
| d02ad5fce2 | |||
| 69f2dbe056 | |||
| 24d87623cc | |||
| 51937ca93f | |||
| dcf4383fbf | |||
| ff43ba32f3 | |||
| 9fa4da7de2 | |||
| c27d9628fd | |||
| b1e09b71ad | |||
| 7d45734ad7 | |||
| 91022c5897 | |||
| 61314d5166 | |||
| 0d54887602 | |||
| 54827fbc58 | |||
| 18a0d14fa8 | |||
| b4a7b80430 | |||
| 2bd3bf9dc1 | |||
| e42bc545a5 | |||
| aa14129fe7 | |||
| 289ceba3af | |||
| 28ab6c9ae4 | |||
| 67deca095e | |||
| caed44fcc8 | |||
| adec5d1725 | |||
| a62e989bb4 | |||
| 9c14153199 | |||
| 756f4dad0a | |||
| 205d77bc0b | |||
| 4f7ede1072 | |||
| 4bb4f526e4 | |||
| c0c19c9c01 | |||
| b4da6e3747 | |||
| 1880fc8147 | |||
| 96df431d60 | |||
| 106cf017dc | |||
| d5fdae9a24 | |||
| 4abb6c67fd | |||
| 6384c0046d | |||
| 2ddb046c26 | |||
| 5d00dc439e | |||
| 210c854fee | |||
| beb5d18b29 | |||
| de259f4286 | |||
| f19bca64d0 | |||
| 18f739b712 | |||
| 1564985259 | |||
| 471a941587 | |||
| 4c647968cb | |||
| 55dcc2e37f | |||
| cac4fcf2b2 | |||
| 64e965aff7 | |||
| 002f08a8fa | |||
| 531dbe52b9 | |||
| a885a2fc0e | |||
| 0c49bae752 | |||
| 67bcb420e4 | |||
| 34058e6a81 | |||
| 8a65d358a4 | |||
| 193e10dc48 | |||
| b607c1b673 | |||
| e9521e65d0 | |||
| d0625f25e5 | |||
| 1fdcfc1547 | |||
| ca4ea0aa6c | |||
| bb1f9c8e91 | |||
| 99fe94fa6a | |||
| a4b5c2eb19 | |||
| 2feca2bed5 | |||
| a35ff69140 | |||
| 75152b53a4 | |||
| 99594b17e7 | |||
| 85edea0661 | |||
| ab5ea7dd33 | |||
| c0057c237a | |||
| e4146288f1 | |||
| f11ba5a470 | |||
| e4db36e650 | |||
| ffa3f10b18 | |||
| 7acef66ee7 | |||
| 18f1217daa | |||
| ac44e82454 | |||
| 1e7a9b6876 | |||
| deea4fd4af | |||
| c4ff695f2e | |||
| 703158bd06 | |||
| eda2343380 | |||
| 0baad641d5 | |||
| ddb8c3743f | |||
| c2233389d0 | |||
| 334ffe92e7 | |||
| a19ace3115 | |||
| acc0a68736 | |||
| dcf105c316 | |||
| f74bf41931 | |||
| 34217be630 | |||
| ee906d2d2e | |||
| 836aa1afd7 | |||
| 6896646c54 | |||
| 5e541f7cd0 | |||
| 80b8707771 | |||
| 58b15f3026 | |||
| 2e9355c85c | |||
| fa1e11a69f | |||
| 6a00d8d09c | |||
| fbfcb5cf63 | |||
| adce4ab59e | |||
| 5250d1a818 | |||
| 457eba68a9 | |||
| 52b0b339d6 | |||
| 9175df1d7f | |||
| 38341b2bda | |||
| 34a0a14404 | |||
| af516ce9e3 | |||
| dca35e7b0c | |||
| df853de843 | |||
| 4ba464bf85 | |||
| 208e929262 | |||
| ffe47d903e | |||
| 24983439b1 | |||
| d179a0f74e | |||
| 636e39e98e | |||
| bda94d02af | |||
| bfb16ef60e | |||
| 1b6303237a | |||
| 9da92c880a | |||
| 63012838a4 | |||
| 27544a23be | |||
| a71c80248c | |||
| 1ca8fb20af | |||
| ba167559a6 | |||
| 495515b1f3 | |||
| 781e282f16 | |||
| 7fb4c9674a | |||
| 0d85c3df19 | |||
| a93b260043 | |||
| c209e716e3 | |||
| 900ef6cf98 | |||
| 71c914a389 | |||
| 705b1247f5 | |||
| b1f42775d6 | |||
| 0f6f39cce7 | |||
| 1ec7ab3e35 | |||
| ba0e2dd00c | |||
| c792e7d306 | |||
| 6ee3f22e41 | |||
| d4ec34db1a | |||
| 351178d9da | |||
| b617285148 | |||
| 9bca41bfa5 | |||
| 5601285369 | |||
| 6fb60c9a73 | |||
| c3f1c320a4 | |||
| 899bf12457 | |||
| a460743ae0 | |||
| a4d7b1b789 | |||
| 10655b8c07 | |||
| adc7b21ab8 | |||
| ba1355448a | |||
| 1c76e56f2d | |||
| daa74845b7 | |||
| 05944cec9c | |||
| c820741e5f | |||
| adc4cc9595 | |||
| c67dfcc1a1 | |||
| f61b7e4dee | |||
| e53fa949cf | |||
| c51e24311f | |||
| a650de79c1 | |||
| 8f4fc39858 | |||
| 09554b9f80 | |||
| 0d2198a3db | |||
| 52732da960 | |||
| 1f7bb35f63 | |||
| 22c6631652 | |||
| bbe3cf82f5 | |||
| ff61a3d3b8 | |||
| 6c5d49bf45 | |||
| 2596b5df18 | |||
| 733064c0dc | |||
| 99808c1053 | |||
| e2ad78b1fb | |||
| 8ed8a11b7b | |||
| dc33e5dc09 | |||
| 414df97e9d | |||
| d0424c5589 | |||
| 28d09dedab | |||
| 8220fb5aaf | |||
| bf02d37a33 | |||
| 78ce263849 | |||
| 0c8419a5eb | |||
| 843659583e | |||
| c2921166bd | |||
| 0f67e66b6b | |||
| 725abed06a | |||
| 743939fc63 | |||
| eb50e65fef | |||
| 1cf13501d8 | |||
| 2eeef8d392 | |||
| 87a4fa6288 | |||
| 07d2129410 | |||
| ceb1d1f1af | |||
| 885ab2a6e3 | |||
| 47196a572a | |||
| 45bba9516d | |||
| c6da71894e | |||
| 75d3c819d9 | |||
| bd6d672df2 | |||
| 6b06028771 | |||
| 0aa423e90e | |||
| e7bf2f887a | |||
| 80a02fdc52 | |||
| 4162e2c1cc | |||
| 8d01620fa8 | |||
| f8b8bab474 | |||
| 53d1415b18 | |||
| 6ff9119086 | |||
| 24e000b423 | |||
| c69ebe5f7c | |||
| c3a2da607d | |||
| d1c4acc7ae | |||
| f8c4cc7428 | |||
| 21cfbe2a46 | |||
| abc060ab25 | |||
| 80adbd9ca9 | |||
| 12c10bbe06 | |||
| 36eb41a18a | |||
| 1dd2366957 | |||
| e8bcaa2026 | |||
| 5548fe8511 | |||
| dc0fbe06b8 | |||
| afd69b8393 | |||
| a34d5cba1a | |||
| 1650176aa0 | |||
| 79e721ae63 | |||
| 4e7e42d16e | |||
| 3a2dc8b7e0 | |||
| 0510c1aa12 | |||
| 9d870be294 | |||
| 559bf5d264 | |||
| eafb02ffd5 | |||
| 786cf2db52 | |||
| cb56e33685 | |||
| dd81e3b3f7 | |||
| 4d51531c5d | |||
| 7fd8a00054 | |||
| 23163a6eb8 | |||
| 944cf8ee18 | |||
| 8c09ca1204 | |||
| 98d502a8ef | |||
| 318e6559cb | |||
| 9fd34f900f | |||
| ae6149df84 | |||
| 1776cfe581 | |||
| 5ad18694e1 | |||
| 6775fb110c | |||
| 9c46eff880 | |||
| c8ce3b0da3 | |||
| d36a929f8c | |||
| 2de02dfd31 | |||
| f9a766dee1 | |||
| 8bc57cf0ff | |||
| a78c5cee58 | |||
| cc22e33799 | |||
| 5c0b3503b7 | |||
| 8537d2ed0a | |||
| d97cc12af6 | |||
| 7a19b3a97a | |||
| a94ac7a473 | |||
| 161693509f | |||
| 93c99afb13 | |||
| 32d2b182c6 | |||
| 2632a80722 | |||
| 3cee9c28f8 | |||
| 2091b1361a | |||
| a2c5e687f9 | |||
| 172e14ae9b | |||
| 58cbeae9d3 | |||
| 1dc4e29c69 | |||
| 093e894cc3 | |||
| fdf0f3328f | |||
| 8d6bcdcc43 | |||
| 3206e293eb | |||
| aed99bd05e | |||
| f1649e0e4b | |||
| e6c4b40a37 | |||
| 15878cd9ba | |||
| d6574bfd0d | |||
| 16bc657a31 | |||
| 7cea8d3495 | |||
| 014b5bb012 | |||
| 67e6211857 | |||
| 58471cb13d | |||
| 864bed0113 | |||
| ced7d594e8 | |||
| 38e87fff6c | |||
| a8973f6171 | |||
| 8e26611097 | |||
| 817d0de6d2 | |||
| a2298c9de2 | |||
| d73b4d1daf | |||
| e6785eb5af | |||
| 1a3f564afd | |||
| e619c51ac9 | |||
| c00b3d609c | |||
| 9cfd49f233 | |||
| 58cc35fd61 | |||
| 460ed528cf | |||
| 1c2f6c4127 | |||
| 9e74e21fb5 | |||
| 7c2880646f | |||
| 4817cb28fe | |||
| c1bfab471c | |||
| de8da72354 | |||
| 4be94275f1 | |||
| 21b0517e6c | |||
| 7fbdc00c64 | |||
| 58c7a0f580 | |||
| a63aea0463 | |||
| b8251f3b63 | |||
| a919e9366b | |||
| 11dbcb4082 | |||
| ed321d6c6c | |||
| 573d4fe5e6 | |||
| bfdaf1c38b | |||
| 4de08ff2f2 | |||
| a4a4c9afbc | |||
| 630b49cad7 | |||
| e33ebf0af1 | |||
| a2592987f5 | |||
| 329e0b1953 | |||
| 97995ae728 | |||
| 7c7a295625 | |||
| 8359f0831f | |||
| a12b3dd0c8 | |||
| 1b22989252 | |||
| 8e94cf7856 | |||
| 5b089e71b2 | |||
| 45d74e166f | |||
| f50d3d0587 | |||
| 36c1c185ee | |||
| 0fae1ca1d7 | |||
| 1d7c484510 | |||
| cb98652e2f | |||
| 622a3eef86 | |||
| 498b4d9eac | |||
| 7d9489169d | |||
| 3eaa3f8202 | |||
| 254faedf2c | |||
| e0f0fb1a72 | |||
| 02cf3f3773 | |||
| b294e5c46e | |||
| d02b0c5551 | |||
| ee911171be | |||
| e17d1fa15e | |||
| 2a15dc92be | |||
| 3a039a6055 | |||
| 84e45bb964 | |||
| 8aa3a26ee7 | |||
| 1de08c1ca4 | |||
| 3f9bcd84c4 | |||
| 96f26e2e9d | |||
| c4b317d5fc | |||
| 3b2977a330 | |||
| 3b36abd46d | |||
| 12697c2268 | |||
| f4638bc984 | |||
| c3713c62a6 | |||
| 4a51f3afde | |||
| f1df6a5918 | |||
| dbeaf19513 | |||
| dd76d5d951 | |||
| f603a82b5e | |||
| b478c23f3b | |||
| 6858b387c3 | |||
| 893bea1492 | |||
| ec1d80dff2 | |||
| 3968a10f6a | |||
| cf2beb2ff5 | |||
| 484fa204b3 | |||
| 6dd057874a | |||
| 40cbac17c6 | |||
| 45e56c43a6 | |||
| cbb7b1c3a1 | |||
| 6b3a12b624 | |||
| 40a7dece11 | |||
| 5ec65ce3d3 | |||
| b7e1332b8c | |||
| a087a511e0 | |||
| a20b1713d3 | |||
| d56d387933 | |||
| cba32e90e7 | |||
| a674bcfabc | |||
| ace3f136e4 | |||
| 2cc72be850 | |||
| 8e3ee7eff6 | |||
| 27d4f9fac6 | |||
| 9e3163b74f | |||
| b9ad2e589f | |||
| 5416c0fd61 | |||
| 04bf03fc2e | |||
| 7c9ebc6d4d | |||
| 45553dc514 | |||
| 1c870d9cfa | |||
| 8ab94ec61f | |||
| 4eacff86bc | |||
| 5c457db1c9 | |||
| 8dc80411d7 | |||
| e16d91f3f9 | |||
| 89f6dab0c4 | |||
| ff9d7728e8 | |||
| 754aeebe3a | |||
| 5107d858cc | |||
| aa4f3303fc | |||
| 069867522a | |||
| 8a19b0136d | |||
| 8b26a2b63e | |||
| c37b8894e4 | |||
| 7b565e7fa7 | |||
| cb76d1c559 | |||
| 135a3bea3e | |||
| 9e6923e732 | |||
| 18c23a112a | |||
| c1be9ecf7f | |||
| 979ed428a2 | |||
| 7889d747d9 | |||
| f6ce85cbde | |||
| 460eec3c78 | |||
| 2b1ef5f8a9 | |||
| 5ada399adf | |||
| aed818da6e | |||
| 018f3f6c13 | |||
| 217f86f624 | |||
| 25891cefbc | |||
| c66d2019d6 | |||
| 12d496544d | |||
| c31be9c927 | |||
| 67ede1a2b4 | |||
| e778d862ba | |||
| 1438ff66c7 |
73
.env.example
73
.env.example
@@ -3,11 +3,17 @@ APP_ENV=production
|
||||
APP_KEY=
|
||||
APP_DEBUG=false
|
||||
APP_URL=http://localhost
|
||||
FRONTEND_URL=http://localhost:4200
|
||||
INTEGRATION_SECRET=
|
||||
|
||||
APP_LOCALE=en
|
||||
APP_FALLBACK_LOCALE=en
|
||||
PURCHASE_CHECKOUT_EXPIRATION_MINUTES=30
|
||||
PURCHASE_QR_EXPIRATION_MINUTES=15
|
||||
PURCHASE_TELEPAGOS_EXPIRATION_MINUTES=30
|
||||
PURCHASE_TRANSFER_EXPIRATION_MINUTES=1440
|
||||
PURCHASE_TRANSFER_CANDIDATE_AMOUNT_TOLERANCE_PERCENTAGE=5
|
||||
STOCK_RESERVATION_EXPIRATION_MINUTES=30
|
||||
FRONTEND_URLS=http://localhost:4200
|
||||
|
||||
APP_LOCALE=es
|
||||
APP_FALLBACK_LOCALE=es
|
||||
APP_FAKER_LOCALE=en_US
|
||||
|
||||
APP_MAINTENANCE_DRIVER=file
|
||||
@@ -15,27 +21,47 @@ APP_MAINTENANCE_DRIVER=file
|
||||
|
||||
# PHP_CLI_SERVER_WORKERS=4
|
||||
|
||||
BCRYPT_ROUNDS=12
|
||||
GOOGLE_CLIENT_ID=
|
||||
GOOGLE_CLIENT_SECRET=
|
||||
GOOGLE_REDIRECT_URI=http://localhost/auth/google/callback
|
||||
|
||||
LOG_CHANNEL=stack
|
||||
|
||||
BCRYPT_ROUNDS=12
|
||||
AUTH_MAX_LOGIN_ATTEMPTS=5
|
||||
AUTH_LOGIN_ATTEMPT_WINDOW_MINUTES=30
|
||||
AUTH_LOGIN_LOCK_MINUTES=15
|
||||
AUTH_LOGIN_RATE_LIMIT_PER_MINUTE=10
|
||||
AUTH_LOGIN_IP_RATE_LIMIT_PER_MINUTE=30
|
||||
AUTH_PASSWORD_RESET_EXPIRATION_MINUTES=60
|
||||
|
||||
LOG_CHANNEL=daily
|
||||
LOG_STACK=single
|
||||
LOG_DEPRECATIONS_CHANNEL=null
|
||||
LOG_LEVEL=debug
|
||||
LOG_DAILY_DAYS=14
|
||||
TELEPAGOS_LOG_LEVEL=info
|
||||
TELEPAGOS_LOG_DAYS=30
|
||||
COMMANDS_LOG_LEVEL=info
|
||||
COMMANDS_LOG_DAYS=30
|
||||
EMAILS_LOG_LEVEL=info
|
||||
EMAILS_LOG_DAYS=30
|
||||
EMAIL_DELIVERY_LEASE_SECONDS=300
|
||||
|
||||
DB_CONNECTION=sqlite
|
||||
# DB_HOST=127.0.0.1
|
||||
# DB_PORT=3306
|
||||
# DB_DATABASE=laravel
|
||||
# DB_USERNAME=root
|
||||
# DB_PASSWORD=
|
||||
|
||||
DB_CONNECTION=mysql
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=laravel
|
||||
DB_USERNAME=root
|
||||
DB_PASSWORD=
|
||||
INTEGRATION_SECRET=change-me
|
||||
SESSION_DRIVER=database
|
||||
SESSION_LIFETIME=120
|
||||
SESSION_ENCRYPT=false
|
||||
SESSION_PATH=/
|
||||
SESSION_DOMAIN=null
|
||||
|
||||
SANCTUM_STATEFUL_DOMAINS=localhost,127.0.0.1,*.shopit.com.ar
|
||||
SANCTUM_EXPIRATION=720
|
||||
SESSION_SECURE_COOKIE=false
|
||||
|
||||
BROADCAST_CONNECTION=log
|
||||
FILESYSTEM_DISK=local
|
||||
@@ -51,27 +77,20 @@ REDIS_HOST=127.0.0.1
|
||||
REDIS_PASSWORD=null
|
||||
REDIS_PORT=6379
|
||||
|
||||
|
||||
GOOGLE_CLIENT_ID=...
|
||||
GOOGLE_CLIENT_SECRET=...
|
||||
GOOGLE_REDIRECT_URI=https://grub-renewed-nicely.ngrok-free.app/auth/google/callback
|
||||
|
||||
MAIL_MAILER=smtp
|
||||
MAIL_SCHEME=smtp
|
||||
MAIL_HOST=smtp.gmail.com
|
||||
MAIL_PORT=587
|
||||
MAIL_SCHEME=null
|
||||
MAIL_HOST=127.0.0.1
|
||||
MAIL_PORT=2525
|
||||
MAIL_USERNAME=null
|
||||
MAIL_PASSWORD=null
|
||||
MAIL_FROM_ADDRESS="hello@example.com"
|
||||
MAIL_FROM_NAME="${APP_NAME}"
|
||||
|
||||
|
||||
AWS_ENDPOINT=
|
||||
AWS_ACCESS_KEY_ID=
|
||||
AWS_SECRET_ACCESS_KEY=
|
||||
AWS_DEFAULT_REGION=garage
|
||||
AWS_DEFAULT_REGION=us-east-1
|
||||
AWS_BUCKET=
|
||||
AWS_USE_PATH_STYLE_ENDPOINT=
|
||||
AWS_HTTP_VERIFY=
|
||||
|
||||
AWS_USE_PATH_STYLE_ENDPOINT=false
|
||||
AWS_HTTP_VERIFY=true
|
||||
VITE_APP_NAME="${APP_NAME}"
|
||||
|
||||
54
AGENTS.md
54
AGENTS.md
@@ -1,19 +1,29 @@
|
||||
# Project Conventions
|
||||
|
||||
## Test database safety
|
||||
|
||||
- Tests must use SQLite `:memory:` through `tests/bootstrap.php` and `Tests\TestCase`.
|
||||
- Never run tests, `migrate:fresh`, `migrate:refresh`, or `db:wipe` against a persistent database, including the developer's `shopit` database.
|
||||
- Never bypass the connection safety guard to resolve test failures. Use `php tests/verify-database-safety.php` to verify isolation without queries or migrations.
|
||||
|
||||
## Architecture
|
||||
|
||||
This project uses a domain-oriented structure under `app/Domains`.
|
||||
This project uses a domain-oriented structure grouped by business area under
|
||||
`app/Domains`. Cross-cutting modules live under `app/Shared`.
|
||||
|
||||
Each domain must live in:
|
||||
Business domains must live in:
|
||||
|
||||
```text
|
||||
app/Domains/<DomainName>/
|
||||
app/Domains/<Area>/<DomainName>/
|
||||
```
|
||||
|
||||
The current areas are `Core`, `Commerce`, and `Ticketing`. Cross-cutting
|
||||
modules live in `app/Shared/<ModuleName>/`.
|
||||
|
||||
Supported folders inside each domain:
|
||||
|
||||
```text
|
||||
app/Domains/<DomainName>/
|
||||
app/Domains/<Area>/<DomainName>/
|
||||
├── Models/
|
||||
├── Controllers/
|
||||
├── Requests/
|
||||
@@ -28,22 +38,28 @@ app/Domains/<DomainName>/
|
||||
|
||||
- Root API routes live in `routes/api.php`.
|
||||
- `routes/api.php` should act as an aggregator only.
|
||||
- Each domain defines its own routes in `app/Domains/<DomainName>/routes/api.php`.
|
||||
- Each business domain defines its own routes in
|
||||
`app/Domains/<Area>/<DomainName>/routes/api.php`.
|
||||
- Shared modules that expose routes define them in
|
||||
`app/Shared/<ModuleName>/routes/api.php`.
|
||||
|
||||
## Namespaces
|
||||
|
||||
Use this namespace pattern:
|
||||
|
||||
```php
|
||||
App\Domains\<DomainName>\Models
|
||||
App\Domains\<DomainName>\Controllers
|
||||
App\Domains\<DomainName>\Requests
|
||||
App\Domains\<DomainName>\Resources
|
||||
App\Domains\<DomainName>\Services
|
||||
App\Domains\<DomainName>\Policies
|
||||
App\Domains\<DomainName>\Exceptions
|
||||
App\Domains\<Area>\<DomainName>\Models
|
||||
App\Domains\<Area>\<DomainName>\Controllers
|
||||
App\Domains\<Area>\<DomainName>\Requests
|
||||
App\Domains\<Area>\<DomainName>\Resources
|
||||
App\Domains\<Area>\<DomainName>\Services
|
||||
App\Domains\<Area>\<DomainName>\Policies
|
||||
App\Domains\<Area>\<DomainName>\Exceptions
|
||||
```
|
||||
|
||||
For cross-cutting modules, use `App\Shared\<ModuleName>\...`. Reusable enums
|
||||
and rules live directly under `App\Shared`.
|
||||
|
||||
## Responsibilities
|
||||
|
||||
- `Models/`: Eloquent models and model relationships.
|
||||
@@ -74,13 +90,19 @@ App\Domains\<DomainName>\Exceptions
|
||||
- Namespace, folder, and class names must stay aligned.
|
||||
- Route files should be named `api.php`.
|
||||
|
||||
## Current Domains
|
||||
## Current Areas and Modules
|
||||
|
||||
- `Tenant`
|
||||
- `Product`
|
||||
- `Core`: `Administrator`, `Auth`, `Authorization`, `Bootstrap`, `Client`,
|
||||
`Menu`, `Staff`, `Tenant`.
|
||||
- `Commerce`: `Cart`, `Catalog`, `Purchase`, `Sale`.
|
||||
- `Ticketing`: `Desfile`, `Event`, `FiestaFutbolInfantil`, `Ticket`.
|
||||
- `Shared`: `Attachable`, `Forms`, `Integration`, `Logging`, `MailTest`,
|
||||
`Notification`, `StorageTest`, plus shared enums and rules.
|
||||
|
||||
## Notes For Future Changes
|
||||
|
||||
- New features should be added inside the corresponding domain first.
|
||||
- If a concern does not belong to an existing domain, create a new domain under `app/Domains`.
|
||||
- Add new business features to the appropriate area under `app/Domains`.
|
||||
- Keep generic reusable code in `app/Shared`; do not use it as a catch-all for
|
||||
business features.
|
||||
- Avoid placing new business code in `app/Http/Controllers` or `app/Models`.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -41,15 +41,18 @@
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/tenants/bootstrap/acme.com",
|
||||
"raw": "{{base_url}}/api/tenants/bootstrap?dominio=acme.com&path=/",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"tenants",
|
||||
"bootstrap",
|
||||
"acme.com"
|
||||
"bootstrap"
|
||||
],
|
||||
"query": [
|
||||
{"key": "dominio", "value": "acme.com"},
|
||||
{"key": "path", "value": "/"}
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,289 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Attachable\Services;
|
||||
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Exceptions\AttachmentStorageException;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\Mime\MimeTypes;
|
||||
use Throwable;
|
||||
|
||||
class AttachmentService
|
||||
{
|
||||
public function store(
|
||||
UploadedFile|string $file,
|
||||
string $path,
|
||||
): Attachment {
|
||||
$normalizedPath = $this->normalizeDirectory($path);
|
||||
|
||||
if ($normalizedPath === '') {
|
||||
throw new AttachmentStorageException('The attachment path cannot be empty.');
|
||||
}
|
||||
|
||||
$key = (string) Str::uuid();
|
||||
$fileData = $this->resolveFileData($file, $key);
|
||||
$storedPath = $this->storeFile(
|
||||
$fileData,
|
||||
$normalizedPath,
|
||||
$this->buildStoredFilename($key, $fileData['extension']),
|
||||
);
|
||||
|
||||
if (! is_string($storedPath) || $storedPath === '') {
|
||||
throw new AttachmentStorageException('No se pudo subir el archivo al disco s3.');
|
||||
}
|
||||
|
||||
try {
|
||||
/** @var Attachment $attachment */
|
||||
$attachment = Attachment::query()->create([
|
||||
'key' => $key,
|
||||
'path' => $storedPath,
|
||||
'filename' => $this->resolveFilename($file, $key),
|
||||
'type' => $this->resolveAttachmentType($fileData['mime_type']),
|
||||
'mime_type' => $fileData['mime_type'],
|
||||
'extension' => $fileData['extension'],
|
||||
'size' => $fileData['size'],
|
||||
]);
|
||||
|
||||
return $attachment;
|
||||
} catch (Throwable $throwable) {
|
||||
Storage::disk('s3')->delete($storedPath);
|
||||
|
||||
throw $throwable;
|
||||
}
|
||||
}
|
||||
|
||||
public function delete(Attachment $attachment): void
|
||||
{
|
||||
$deleted = Storage::disk('s3')->delete($attachment->path);
|
||||
|
||||
if (! $deleted) {
|
||||
throw new AttachmentStorageException('No se pudo eliminar el archivo del disco s3.');
|
||||
}
|
||||
|
||||
$attachment->delete();
|
||||
}
|
||||
|
||||
public function copy(Attachment $source, string $path): Attachment
|
||||
{
|
||||
$normalizedPath = $this->normalizeDirectory($path);
|
||||
|
||||
if ($normalizedPath === '') {
|
||||
throw new AttachmentStorageException('The attachment path cannot be empty.');
|
||||
}
|
||||
|
||||
$key = (string) Str::uuid();
|
||||
$storedPath = $normalizedPath.'/'.$this->buildStoredFilename($key, (string) $source->extension);
|
||||
$copied = Storage::disk('s3')->copy($source->path, $storedPath);
|
||||
|
||||
if (! $copied) {
|
||||
throw new AttachmentStorageException('No se pudo copiar el archivo en el disco s3.');
|
||||
}
|
||||
|
||||
try {
|
||||
/** @var Attachment $attachment */
|
||||
$attachment = Attachment::query()->create([
|
||||
'key' => $key,
|
||||
'path' => $storedPath,
|
||||
'filename' => $source->filename,
|
||||
'type' => $source->type,
|
||||
'mime_type' => $source->mime_type,
|
||||
'extension' => $source->extension,
|
||||
'size' => $source->size,
|
||||
]);
|
||||
|
||||
return $attachment;
|
||||
} catch (Throwable $throwable) {
|
||||
Storage::disk('s3')->delete($storedPath);
|
||||
|
||||
throw $throwable;
|
||||
}
|
||||
}
|
||||
|
||||
protected function normalizeDirectory(string $path): string
|
||||
{
|
||||
return trim($path, '/');
|
||||
}
|
||||
|
||||
protected function resolveFilename(UploadedFile|string $file, string $key): string
|
||||
{
|
||||
if ($file instanceof UploadedFile) {
|
||||
$originalName = trim($file->getClientOriginalName());
|
||||
|
||||
if ($originalName !== '') {
|
||||
return $originalName;
|
||||
}
|
||||
}
|
||||
|
||||
return $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{contents: string|null, extension: string, file: UploadedFile|null, mime_type: string, size: int}
|
||||
*/
|
||||
protected function resolveFileData(UploadedFile|string $file, string $filename): array
|
||||
{
|
||||
if ($file instanceof UploadedFile) {
|
||||
return $this->fileDataFromUploadedFile($file);
|
||||
}
|
||||
|
||||
return $this->fileDataFromBase64($file, $filename);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{contents: string|null, extension: string, file: UploadedFile, mime_type: string, size: int}
|
||||
*/
|
||||
protected function fileDataFromUploadedFile(UploadedFile $file): array
|
||||
{
|
||||
$mimeType = strtolower($file->getClientMimeType() ?? $file->getMimeType() ?? 'application/octet-stream');
|
||||
|
||||
return [
|
||||
'contents' => null,
|
||||
'extension' => strtolower($file->getClientOriginalExtension() ?: $file->extension() ?: ''),
|
||||
'file' => $file,
|
||||
'mime_type' => $mimeType,
|
||||
'size' => $file->getSize() ?? 0,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{contents: string, extension: string, file: null, mime_type: string, size: int}
|
||||
*/
|
||||
protected function fileDataFromBase64(string $file, string $filename): array
|
||||
{
|
||||
['data' => $contents, 'mime_type' => $declaredMimeType] = $this->decodeBase64File($file);
|
||||
$mimeType = $this->detectMimeType($contents, $declaredMimeType);
|
||||
|
||||
return [
|
||||
'contents' => $contents,
|
||||
'extension' => $this->resolveExtension($filename, $mimeType),
|
||||
'file' => null,
|
||||
'mime_type' => $mimeType,
|
||||
'size' => strlen($contents),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{data: string, mime_type: string|null}
|
||||
*/
|
||||
protected function decodeBase64File(string $file): array
|
||||
{
|
||||
$payload = trim($file);
|
||||
|
||||
if ($payload === '') {
|
||||
throw new AttachmentStorageException('The base64 attachment content cannot be empty.');
|
||||
}
|
||||
|
||||
$declaredMimeType = null;
|
||||
|
||||
if (preg_match('/^data:(?<mime>[-\w.+\/]+);base64,(?<data>.+)$/s', $payload, $matches) === 1) {
|
||||
$declaredMimeType = strtolower($matches['mime']);
|
||||
$payload = $matches['data'];
|
||||
}
|
||||
|
||||
$decoded = base64_decode(preg_replace('/\s+/', '', $payload), true);
|
||||
|
||||
if ($decoded === false || $decoded === '') {
|
||||
throw new AttachmentStorageException('The attachment base64 payload is invalid.');
|
||||
}
|
||||
|
||||
return [
|
||||
'data' => $decoded,
|
||||
'mime_type' => $declaredMimeType,
|
||||
];
|
||||
}
|
||||
|
||||
protected function detectMimeType(string $contents, ?string $fallback = null): string
|
||||
{
|
||||
if (is_string($fallback) && $fallback !== '') {
|
||||
return strtolower($fallback);
|
||||
}
|
||||
|
||||
$detectedMimeType = (new \finfo(FILEINFO_MIME_TYPE))->buffer($contents);
|
||||
|
||||
if (is_string($detectedMimeType) && $detectedMimeType !== '') {
|
||||
return strtolower($detectedMimeType);
|
||||
}
|
||||
|
||||
return strtolower($fallback ?? 'application/octet-stream');
|
||||
}
|
||||
|
||||
protected function resolveExtension(string $filename, string $mimeType): string
|
||||
{
|
||||
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
|
||||
|
||||
if ($extension !== '') {
|
||||
return $extension;
|
||||
}
|
||||
|
||||
return strtolower(MimeTypes::getDefault()->getExtensions($mimeType)[0] ?? '');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{contents: string|null, extension: string, file: UploadedFile|null, mime_type: string, size: int} $fileData
|
||||
*/
|
||||
protected function storeFile(array $fileData, string $directory, string $storedFilename): string
|
||||
{
|
||||
if ($fileData['file'] instanceof UploadedFile) {
|
||||
return Storage::disk('s3')->putFileAs($directory, $fileData['file'], $storedFilename);
|
||||
}
|
||||
|
||||
$storedPath = $directory !== ''
|
||||
? $directory.'/'.$storedFilename
|
||||
: $storedFilename;
|
||||
|
||||
$stored = Storage::disk('s3')->put($storedPath, $fileData['contents'] ?? '');
|
||||
|
||||
if (! $stored) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return $storedPath;
|
||||
}
|
||||
|
||||
protected function resolveAttachmentType(string $mimeType): AttachmentType
|
||||
{
|
||||
$mimeType = strtolower($mimeType);
|
||||
|
||||
if (str_starts_with($mimeType, 'image/')) {
|
||||
return AttachmentType::Image;
|
||||
}
|
||||
|
||||
if (str_starts_with($mimeType, 'video/')) {
|
||||
return AttachmentType::Video;
|
||||
}
|
||||
|
||||
if ($mimeType === 'application/pdf') {
|
||||
return AttachmentType::Pdf;
|
||||
}
|
||||
|
||||
if (str_starts_with($mimeType, 'audio/')) {
|
||||
return AttachmentType::Audio;
|
||||
}
|
||||
|
||||
if (
|
||||
str_starts_with($mimeType, 'text/')
|
||||
|| str_contains($mimeType, 'document')
|
||||
|| str_contains($mimeType, 'word')
|
||||
|| str_contains($mimeType, 'excel')
|
||||
|| str_contains($mimeType, 'spreadsheet')
|
||||
|| str_contains($mimeType, 'presentation')
|
||||
|| str_contains($mimeType, 'officedocument')
|
||||
) {
|
||||
return AttachmentType::Document;
|
||||
}
|
||||
|
||||
return AttachmentType::Other;
|
||||
}
|
||||
|
||||
protected function buildStoredFilename(string $key, string $extension): string
|
||||
{
|
||||
if ($extension === '') {
|
||||
return $key;
|
||||
}
|
||||
|
||||
return $key.'.'.$extension;
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Requests\GoogleTokenExchangeRequest;
|
||||
use App\Domains\Auth\Resources\UserResource;
|
||||
use App\Domains\Auth\Services\GoogleAuthService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class GoogleTokenExchangeController extends Controller
|
||||
{
|
||||
public function __construct(private readonly GoogleAuthService $googleAuthService) {}
|
||||
|
||||
public function __invoke(GoogleTokenExchangeRequest $request): JsonResponse
|
||||
{
|
||||
$authentication = $this->googleAuthService->exchange($request->validated('oauth_code'));
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Sesion iniciada correctamente.',
|
||||
'token' => $authentication['token'],
|
||||
'token_type' => 'Bearer',
|
||||
'user' => UserResource::make($authentication['user']),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Requests\LoginUserRequest;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Auth\Resources\UserResource;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class LoginController extends Controller
|
||||
{
|
||||
/**
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function __invoke(LoginUserRequest $request): JsonResponse
|
||||
{
|
||||
$credentials = $request->validated();
|
||||
$user = User::query()->where('email', $credentials['email'])->first();
|
||||
|
||||
if (! $user || ! Hash::check($credentials['password'], $user->password)) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => 'Email o Contraseña incorrectos.',
|
||||
]);
|
||||
}
|
||||
|
||||
$expirationMinutes = (int) config('sanctum.expiration');
|
||||
$token = $user->createToken(
|
||||
'api-token',
|
||||
['*'],
|
||||
now()->addMinutes($expirationMinutes),
|
||||
)->plainTextToken;
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Sesion iniciada correctamente.',
|
||||
'token' => $token,
|
||||
'token_type' => 'Bearer',
|
||||
'user' => UserResource::make($user),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Models;
|
||||
|
||||
use Database\Factories\UserFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Laravel\Sanctum\HasApiTokens;
|
||||
|
||||
#[Fillable(['nombre_apellido', 'email', 'password', 'dni', 'telefono', 'google_id'])]
|
||||
#[Hidden(['password', 'remember_token'])]
|
||||
class User extends Authenticatable
|
||||
{
|
||||
/** @use HasFactory<UserFactory> */
|
||||
use HasApiTokens, HasFactory, Notifiable;
|
||||
|
||||
protected static function newFactory(): UserFactory
|
||||
{
|
||||
return UserFactory::new();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'email_verified_at' => 'datetime',
|
||||
'password' => 'hashed',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Auth\Controllers\GoogleTokenExchangeController;
|
||||
use App\Domains\Auth\Controllers\LoginController;
|
||||
use App\Domains\Auth\Controllers\LogoutController;
|
||||
use App\Domains\Auth\Controllers\MeController;
|
||||
use App\Domains\Auth\Controllers\RegisterController;
|
||||
use App\Domains\Auth\Controllers\UpdateProfileController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::post('/register', RegisterController::class);
|
||||
Route::post('/login', LoginController::class);
|
||||
Route::post('/auth/google/exchange', GoogleTokenExchangeController::class);
|
||||
Route::middleware('auth:sanctum')->post('/logout', LogoutController::class);
|
||||
Route::middleware('auth:sanctum')->get('/me', MeController::class);
|
||||
Route::middleware('auth:sanctum')->put('/me', UpdateProfileController::class);
|
||||
@@ -1,73 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Middleware;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Cookie;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class MergeGuestCartMiddleware
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$guestToken = $request->cookie('guest_token');
|
||||
|
||||
// Resolve authenticated user optionally (from default guard or sanctum guard)
|
||||
$user = $request->user() ?? Auth::guard('sanctum')->user();
|
||||
$userId = $user?->getKey();
|
||||
|
||||
\Illuminate\Support\Facades\Log::info('MergeGuestCartMiddleware processed', [
|
||||
'user_id' => $userId,
|
||||
'guest_token' => $guestToken,
|
||||
]);
|
||||
|
||||
if ($user !== null && is_string($guestToken) && $guestToken !== '') {
|
||||
$tenantParam = $request->route('tenant');
|
||||
$tenantCodigo = null;
|
||||
|
||||
if ($tenantParam instanceof Tenant) {
|
||||
$tenantCodigo = $tenantParam->codigo;
|
||||
} elseif (is_string($tenantParam)) {
|
||||
$tenantCodigo = $tenantParam;
|
||||
}
|
||||
|
||||
if ($tenantCodigo !== null) {
|
||||
$guestCart = Cart::query()
|
||||
->where('tenant_codigo', $tenantCodigo)
|
||||
->where('guest_token', $guestToken)
|
||||
->first();
|
||||
|
||||
if ($guestCart !== null && $guestCart->items()->exists()) {
|
||||
$userCart = Cart::query()
|
||||
->where('tenant_codigo', $tenantCodigo)
|
||||
->where('user_id', $userId)
|
||||
->first();
|
||||
|
||||
if ($userCart !== null) {
|
||||
$userCart->delete();
|
||||
}
|
||||
|
||||
$guestCart->update([
|
||||
'user_id' => $userId,
|
||||
'guest_token' => null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$response = $next($request);
|
||||
|
||||
if ($user !== null && is_string($guestToken) && $guestToken !== '') {
|
||||
// Remove the cookie from the response since the user is authenticated.
|
||||
if (method_exists($response, 'withCookie')) {
|
||||
$response->withCookie(Cookie::forget('guest_token'));
|
||||
}
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -1,269 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_codigo',
|
||||
'user_id',
|
||||
'guest_token',
|
||||
'status',
|
||||
])]
|
||||
class Cart extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use SoftDeletes;
|
||||
|
||||
protected $table = 'carritos';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'user_id' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Tenant, $this>
|
||||
*/
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_codigo', 'codigo');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<CartItem, $this>
|
||||
*/
|
||||
public function items(): HasMany
|
||||
{
|
||||
return $this->hasMany(CartItem::class, 'cart_id');
|
||||
}
|
||||
|
||||
public function getTotalAmount(): float
|
||||
{
|
||||
$items = $this->relationLoaded('items')
|
||||
? $this->getRelation('items')
|
||||
: $this->items()->with(['catalogItem', 'variant'])->get();
|
||||
|
||||
return (float) $items->reduce(
|
||||
fn (float $carry, CartItem $item): float => $carry
|
||||
+ (($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad),
|
||||
0.0,
|
||||
);
|
||||
}
|
||||
|
||||
public function addItem(int $catalogItemId, ?int $variantId, int $quantity): CartItem
|
||||
{
|
||||
if ($quantity <= 0) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => 'La cantidad debe ser mayor a cero.',
|
||||
]);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
|
||||
self::query()->whereKey($this->getKey())->lockForUpdate()->firstOrFail();
|
||||
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
|
||||
$inventoryService = app(CatalogInventoryService::class);
|
||||
$availableQuantity = $inventoryService->availableQuantity($selectedItem);
|
||||
|
||||
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => "Stock insuficiente para el producto solicitado. Maximo disponible: {$availableQuantity}.",
|
||||
]);
|
||||
}
|
||||
|
||||
/** @var CartItem|null $item */
|
||||
$item = $this->items()
|
||||
->where('catalog_item_id', $catalogItemId)
|
||||
->where('variant_id', $variantId)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($item === null) {
|
||||
$item = $this->items()->create([
|
||||
'catalog_item_id' => $catalogItemId,
|
||||
'variant_id' => $variantId,
|
||||
'cantidad' => $quantity,
|
||||
]);
|
||||
} else {
|
||||
$item->cantidad += $quantity;
|
||||
$item->save();
|
||||
}
|
||||
|
||||
$inventoryService->reserve($selectedItem, $quantity);
|
||||
|
||||
return $item->fresh();
|
||||
});
|
||||
}
|
||||
|
||||
public function updateItem(int $cartItemId, int $quantity): CartItem
|
||||
{
|
||||
if ($quantity <= 0) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => 'La cantidad debe ser mayor a cero.',
|
||||
]);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($cartItemId, $quantity): CartItem {
|
||||
/** @var CartItem $item */
|
||||
$item = $this->items()
|
||||
->where('id', $cartItemId)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$selectedItem = $this->resolveScopedItem(
|
||||
$item->catalog_item_id,
|
||||
$item->variant_id,
|
||||
true,
|
||||
);
|
||||
$inventoryService = app(CatalogInventoryService::class);
|
||||
$delta = $quantity - $item->cantidad;
|
||||
$availableQuantity = $inventoryService->availableQuantity($selectedItem);
|
||||
|
||||
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
|
||||
$maxAvailable = $availableQuantity + $item->cantidad;
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => "El máximo que se puede agregar es {$maxAvailable}.",
|
||||
]);
|
||||
}
|
||||
|
||||
$item->cantidad = $quantity;
|
||||
$item->save();
|
||||
|
||||
if ($delta > 0) {
|
||||
$inventoryService->reserve($selectedItem, $delta);
|
||||
}
|
||||
|
||||
if ($delta < 0) {
|
||||
$inventoryService->release($selectedItem, abs($delta));
|
||||
}
|
||||
|
||||
return $item->fresh();
|
||||
});
|
||||
}
|
||||
|
||||
public function removeItem(int $cartItemId): void
|
||||
{
|
||||
DB::transaction(function () use ($cartItemId): void {
|
||||
/** @var CartItem $item */
|
||||
$item = $this->items()
|
||||
->where('id', $cartItemId)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$selectedItem = $this->resolveScopedItem(
|
||||
$item->catalog_item_id,
|
||||
$item->variant_id,
|
||||
true,
|
||||
);
|
||||
app(CatalogInventoryService::class)->release(
|
||||
$selectedItem,
|
||||
$item->cantidad,
|
||||
);
|
||||
$item->delete();
|
||||
});
|
||||
}
|
||||
|
||||
protected function resolveScopedItem(
|
||||
int $catalogItemId,
|
||||
?int $variantId,
|
||||
bool $lockForUpdate = false,
|
||||
): CatalogItem|Variant {
|
||||
$catalogItemQuery = CatalogItem::query()
|
||||
->whereKey($catalogItemId)
|
||||
->where('tenant_code', $this->tenant_codigo);
|
||||
|
||||
if ($lockForUpdate) {
|
||||
$catalogItemQuery->lockForUpdate();
|
||||
}
|
||||
|
||||
$catalogItem = $catalogItemQuery->first();
|
||||
|
||||
if ($catalogItem === null) {
|
||||
throw new NotFoundHttpException('Catalog item not found for tenant.');
|
||||
}
|
||||
|
||||
if ($catalogItem->isBundle()) {
|
||||
if ($variantId !== null) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => 'Un bundle no admite una variante.',
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $catalogItem->bundleComponents()->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
'catalog_item_id' => 'El bundle no tiene componentes.',
|
||||
]);
|
||||
}
|
||||
|
||||
return $catalogItem;
|
||||
}
|
||||
|
||||
if ($variantId === null) {
|
||||
if ($catalogItem->inventory_id === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => 'Debe seleccionar una variante para este ítem.',
|
||||
]);
|
||||
}
|
||||
|
||||
$inventory = $this->resolveInventory($catalogItem->inventory_id, $lockForUpdate);
|
||||
$catalogItem->setRelation('inventory', $inventory);
|
||||
|
||||
return $catalogItem;
|
||||
}
|
||||
|
||||
$variantQuery = Variant::query()
|
||||
->whereKey($variantId)
|
||||
->where('catalog_item_id', $catalogItem->id);
|
||||
|
||||
if ($lockForUpdate) {
|
||||
$variantQuery->lockForUpdate();
|
||||
}
|
||||
|
||||
$variant = $variantQuery->first();
|
||||
|
||||
if ($variant === null) {
|
||||
throw new NotFoundHttpException('Variant not found for catalog item.');
|
||||
}
|
||||
|
||||
$inventory = $this->resolveInventory($variant->inventory_id, $lockForUpdate);
|
||||
$variant->setRelation('catalogItem', $catalogItem);
|
||||
$variant->setRelation('inventory', $inventory);
|
||||
|
||||
return $variant;
|
||||
}
|
||||
|
||||
protected function resolveInventory(int $inventoryId, bool $lockForUpdate): Inventory
|
||||
{
|
||||
$query = Inventory::query()->whereKey($inventoryId);
|
||||
|
||||
if ($lockForUpdate) {
|
||||
$query->lockForUpdate();
|
||||
}
|
||||
|
||||
return $query->firstOrFail();
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Resources;
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin CartItem
|
||||
*/
|
||||
class CartItemResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$selectedItem = $this->selectedItem();
|
||||
$imageUrl = null;
|
||||
|
||||
if ($selectedItem?->relationLoaded('attachments')) {
|
||||
$imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440);
|
||||
}
|
||||
|
||||
if ($imageUrl === null && $this->catalogItem?->relationLoaded('attachments')) {
|
||||
$imageUrl = $this->catalogItem->attachments->first()?->getTemporaryUrl(1440);
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'cantidad' => $this->cantidad,
|
||||
'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()),
|
||||
'catalog_item_id' => $this->catalog_item_id,
|
||||
'variant_id' => $this->variant_id,
|
||||
'product' => $selectedItem === null ? null : [
|
||||
'nombre' => $selectedItem->getName(),
|
||||
'imagen' => $imageUrl,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
protected function formatMoney(float|int|string|null $amount): string
|
||||
{
|
||||
return number_format((float) ($amount ?? 0), 2, '.', '');
|
||||
}
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpFoundation\Cookie;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class CartService
|
||||
{
|
||||
public function show(Tenant $tenant, Request $request): Cart
|
||||
{
|
||||
$resolvedIdentity = $this->resolveIdentity($request);
|
||||
|
||||
if ($resolvedIdentity === null) {
|
||||
return $this->makeEmptyCart($tenant);
|
||||
}
|
||||
|
||||
$cart = $this->findCart($tenant, $resolvedIdentity['identity']);
|
||||
|
||||
if ($cart === null) {
|
||||
return $this->makeEmptyCart($tenant);
|
||||
}
|
||||
|
||||
return $this->loadCart($cart);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{cart: Cart, guest_token: ?string}
|
||||
*/
|
||||
public function addItem(
|
||||
Tenant $tenant,
|
||||
Request $request,
|
||||
int $catalogItemId,
|
||||
?int $variantId,
|
||||
int $quantity,
|
||||
): array {
|
||||
$resolvedIdentity = $this->resolveIdentity($request, true);
|
||||
$identity = $resolvedIdentity['identity'];
|
||||
$cart = $this->findOrCreateCart($tenant, $identity);
|
||||
$cart->addItem($catalogItemId, $variantId, $quantity);
|
||||
|
||||
return [
|
||||
'cart' => $this->loadCart($cart),
|
||||
'guest_token' => $resolvedIdentity['generated_guest_token'],
|
||||
];
|
||||
}
|
||||
|
||||
public function updateItemQuantity(Tenant $tenant, Request $request, int $cartItemId, int $quantity): Cart
|
||||
{
|
||||
$identity = $this->requireIdentity($request);
|
||||
$cart = $this->findCartOrFail($tenant, $identity);
|
||||
$cart->updateItem($cartItemId, $quantity);
|
||||
|
||||
return $this->loadCart($cart);
|
||||
}
|
||||
|
||||
public function removeItem(Tenant $tenant, Request $request, int $cartItemId): Cart
|
||||
{
|
||||
$identity = $this->requireIdentity($request);
|
||||
$cart = $this->findCartOrFail($tenant, $identity);
|
||||
$cart->removeItem($cartItemId);
|
||||
|
||||
return $this->loadCart($cart);
|
||||
}
|
||||
|
||||
public function makeGuestTokenCookie(string $guestToken): Cookie
|
||||
{
|
||||
return cookie(
|
||||
'guest_token',
|
||||
$guestToken,
|
||||
60 * 24 * 180,
|
||||
'/',
|
||||
null,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
'lax',
|
||||
);
|
||||
}
|
||||
|
||||
protected function makeEmptyCart(Tenant $tenant): Cart
|
||||
{
|
||||
$cart = new Cart([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
$cart->setRelation('items', collect());
|
||||
|
||||
return $cart;
|
||||
}
|
||||
|
||||
protected function loadCart(Cart $cart): Cart
|
||||
{
|
||||
return $cart->fresh()->load([
|
||||
'items.catalogItem.attachments',
|
||||
'items.catalogItem.inventory',
|
||||
'items.variant.attachments',
|
||||
'items.variant.inventory',
|
||||
'items.variant.definitions.itemAttribute.attribute',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{identity: array{user_id: ?int, guest_token: ?string}, generated_guest_token: ?string}|null
|
||||
*/
|
||||
protected function resolveIdentity(Request $request, bool $generateGuestToken = false): ?array
|
||||
{
|
||||
$user = $request->user() ?? Auth::guard('sanctum')->user();
|
||||
|
||||
if ($user instanceof User) {
|
||||
return [
|
||||
'identity' => [
|
||||
'user_id' => $user->getKey(),
|
||||
'guest_token' => null,
|
||||
],
|
||||
'generated_guest_token' => null,
|
||||
];
|
||||
}
|
||||
|
||||
$guestToken = $request->cookie('guest_token');
|
||||
|
||||
if (is_string($guestToken) && $guestToken !== '') {
|
||||
return [
|
||||
'identity' => [
|
||||
'user_id' => null,
|
||||
'guest_token' => $guestToken,
|
||||
],
|
||||
'generated_guest_token' => null,
|
||||
];
|
||||
}
|
||||
|
||||
if (! $generateGuestToken) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$generatedGuestToken = (string) Str::uuid();
|
||||
|
||||
return [
|
||||
'identity' => [
|
||||
'user_id' => null,
|
||||
'guest_token' => $generatedGuestToken,
|
||||
],
|
||||
'generated_guest_token' => $generatedGuestToken,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{user_id: ?int, guest_token: ?string}
|
||||
*/
|
||||
protected function requireIdentity(Request $request): array
|
||||
{
|
||||
$resolvedIdentity = $this->resolveIdentity($request);
|
||||
|
||||
if ($resolvedIdentity === null) {
|
||||
throw new NotFoundHttpException('Cart not found.');
|
||||
}
|
||||
|
||||
return $resolvedIdentity['identity'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{user_id: ?int, guest_token: ?string} $identity
|
||||
*/
|
||||
protected function findCart(Tenant $tenant, array $identity): ?Cart
|
||||
{
|
||||
return Cart::query()
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->when(
|
||||
$identity['user_id'] !== null,
|
||||
fn ($query) => $query->where('user_id', $identity['user_id']),
|
||||
fn ($query) => $query->where('guest_token', $identity['guest_token']),
|
||||
)
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{user_id: ?int, guest_token: ?string} $identity
|
||||
*/
|
||||
protected function findCartOrFail(Tenant $tenant, array $identity): Cart
|
||||
{
|
||||
$cart = $this->findCart($tenant, $identity);
|
||||
|
||||
if ($cart === null) {
|
||||
throw new NotFoundHttpException('Cart not found.');
|
||||
}
|
||||
|
||||
return $cart;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{user_id: ?int, guest_token: ?string} $identity
|
||||
*/
|
||||
protected function findOrCreateCart(Tenant $tenant, array $identity): Cart
|
||||
{
|
||||
$attributes = ['tenant_codigo' => $tenant->codigo];
|
||||
|
||||
if ($identity['user_id'] !== null) {
|
||||
$attributes['user_id'] = $identity['user_id'];
|
||||
} else {
|
||||
$attributes['guest_token'] = $identity['guest_token'];
|
||||
}
|
||||
|
||||
return Cart::query()->firstOrCreate($attributes, ['status' => 'active']);
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Controllers;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Catalog\Requests\CatalogItemDetailRequest;
|
||||
use App\Domains\Catalog\Requests\FeaturedGroupPageRequest;
|
||||
use App\Domains\Catalog\Requests\StoreCatalogItemRequest;
|
||||
use App\Domains\Catalog\Resources\CatalogFeaturedGroupResource;
|
||||
use App\Domains\Catalog\Resources\CatalogFeaturedItemResource;
|
||||
use App\Domains\Catalog\Resources\CatalogItemDetailResource;
|
||||
use App\Domains\Catalog\Resources\CatalogItemResource;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
class CatalogController extends Controller
|
||||
{
|
||||
private const ITEMS_PER_PAGE = 12;
|
||||
|
||||
public function index(Tenant $tenant): JsonResponse
|
||||
{
|
||||
$featuredGroups = FeaturedGroup::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->orderBy('group_order')
|
||||
->get();
|
||||
|
||||
return response()->json($featuredGroups->map(
|
||||
fn (FeaturedGroup $featuredGroup): array => (new CatalogFeaturedGroupResource(
|
||||
$featuredGroup,
|
||||
$this->featuredItemsResponse($featuredGroup, 1),
|
||||
))->resolve()
|
||||
));
|
||||
}
|
||||
|
||||
public function featuredGroupItems(
|
||||
FeaturedGroupPageRequest $request,
|
||||
Tenant $tenant,
|
||||
FeaturedGroup $featuredGroup,
|
||||
): JsonResponse {
|
||||
abort_unless($featuredGroup->tenant_code === $tenant->codigo, 404);
|
||||
|
||||
$page = (int) $request->validated('page', 1);
|
||||
|
||||
return response()->json($this->featuredItemsResponse($featuredGroup, $page));
|
||||
}
|
||||
|
||||
public function show(
|
||||
CatalogItemDetailRequest $request,
|
||||
Tenant $tenant,
|
||||
CatalogItem $catalogItem,
|
||||
CatalogService $catalogService,
|
||||
): CatalogItemDetailResource {
|
||||
abort_unless($catalogItem->tenant_code === $tenant->codigo, 404);
|
||||
|
||||
$variantId = $request->validated('variant_id');
|
||||
|
||||
return CatalogItemDetailResource::make(
|
||||
$catalogService->getDetail(
|
||||
$catalogItem,
|
||||
$variantId === null ? null : (int) $variantId,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function store(
|
||||
StoreCatalogItemRequest $request,
|
||||
Tenant $tenant,
|
||||
CatalogService $catalogService,
|
||||
): JsonResponse {
|
||||
$catalogItem = $catalogService->create([
|
||||
...$request->validated(),
|
||||
'tenant_code' => $tenant->codigo,
|
||||
]);
|
||||
|
||||
return CatalogItemResource::make($catalogItem)
|
||||
->response()
|
||||
->setStatusCode(201);
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function featuredItemsResponse(FeaturedGroup $featuredGroup, int $page): array
|
||||
{
|
||||
$paginator = $this->paginateFeaturedItems($featuredGroup, $page);
|
||||
|
||||
$paginator->getCollection()->each(
|
||||
fn ($featuredItem) => $featuredItem->setRelation('featuredGroup', $featuredGroup)
|
||||
);
|
||||
|
||||
return CatalogFeaturedItemResource::collection($paginator)
|
||||
->response()
|
||||
->getData(true);
|
||||
}
|
||||
|
||||
private function paginateFeaturedItems(
|
||||
FeaturedGroup $featuredGroup,
|
||||
int $page,
|
||||
): LengthAwarePaginator {
|
||||
$paginator = $featuredGroup->featuredItems()
|
||||
->with([
|
||||
'catalogItem.inventory',
|
||||
'catalogItem.attachments',
|
||||
'catalogItem.variants.inventory',
|
||||
'catalogItem.variants.attachments',
|
||||
'catalogItem.variants.definitions.itemAttribute.attribute',
|
||||
'catalogItem.bundleComponents.catalogItem',
|
||||
'catalogItem.bundleComponents.variant.catalogItem',
|
||||
])
|
||||
->paginate(
|
||||
perPage: self::ITEMS_PER_PAGE,
|
||||
pageName: 'page',
|
||||
page: $page,
|
||||
);
|
||||
|
||||
return $paginator->withPath(route('catalog.featured-groups.items.index', [
|
||||
'tenant' => $featuredGroup->tenant_code,
|
||||
'featuredGroup' => $featuredGroup->id,
|
||||
]));
|
||||
}
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_code',
|
||||
'category_id',
|
||||
'brand_id',
|
||||
'inventory_id',
|
||||
'type',
|
||||
'slug',
|
||||
'nombre',
|
||||
'descripcion',
|
||||
'precio',
|
||||
'inventory_policy',
|
||||
'has_tickets',
|
||||
'maximum_use_date',
|
||||
'minimum_use_date',
|
||||
])]
|
||||
class CatalogItem extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $table = 'catalog_items';
|
||||
|
||||
protected $attributes = [
|
||||
'type' => CatalogItemType::Standard->value,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => false,
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'category_id' => 'integer',
|
||||
'brand_id' => 'integer',
|
||||
'inventory_id' => 'integer',
|
||||
'type' => CatalogItemType::class,
|
||||
'precio' => 'decimal:2',
|
||||
'inventory_policy' => InventoryPolicy::class,
|
||||
'has_tickets' => 'boolean',
|
||||
'maximum_use_date' => 'datetime',
|
||||
'minimum_use_date' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Tenant, $this> */
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Category, $this> */
|
||||
public function category(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Category::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Brand, $this> */
|
||||
public function brand(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Brand::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Inventory, $this> */
|
||||
public function inventory(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Inventory::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<BundleComponent, $this> */
|
||||
public function bundleComponents(): HasMany
|
||||
{
|
||||
return $this->hasMany(BundleComponent::class, 'bundle_catalog_item_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<BundleComponent, $this> */
|
||||
public function bundleComponentUsages(): HasMany
|
||||
{
|
||||
return $this->hasMany(BundleComponent::class, 'component_catalog_item_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<Variant, $this> */
|
||||
public function variants(): HasMany
|
||||
{
|
||||
return $this->hasMany(Variant::class);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attribute, $this> */
|
||||
public function attributes(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Attribute::class, 'item_attributes')
|
||||
->withTimestamps();
|
||||
}
|
||||
|
||||
/** @return HasMany<ItemAttribute, $this> */
|
||||
public function itemAttributes(): HasMany
|
||||
{
|
||||
return $this->hasMany(ItemAttribute::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<FeaturedItem, $this> */
|
||||
public function featuredItems(): HasMany
|
||||
{
|
||||
return $this->hasMany(FeaturedItem::class);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function attachments(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
Attachment::class,
|
||||
'catalog_items_attachments',
|
||||
'catalog_item_id',
|
||||
'attachment_id'
|
||||
)
|
||||
->withPivot('orden')
|
||||
->wherePivotNull('variant_id')
|
||||
->orderByPivot('orden');
|
||||
}
|
||||
|
||||
public function availableStock(): ?int
|
||||
{
|
||||
return app(CatalogInventoryService::class)->availableQuantity($this);
|
||||
}
|
||||
|
||||
public function isAvailable(): bool
|
||||
{
|
||||
if ($this->type === CatalogItemType::Bundle) {
|
||||
$availableStock = $this->availableStock();
|
||||
|
||||
return $availableStock === null || $availableStock > 0;
|
||||
}
|
||||
|
||||
if ($this->inventory_policy === InventoryPolicy::Unlimited) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return ($this->availableStock() ?? 0) > 0;
|
||||
}
|
||||
|
||||
public function getPrice(): float
|
||||
{
|
||||
return (float) $this->precio;
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return $this->nombre;
|
||||
}
|
||||
|
||||
public function isBundle(): bool
|
||||
{
|
||||
return $this->type === CatalogItemType::Bundle;
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_code',
|
||||
'product_layout',
|
||||
'group_name',
|
||||
'group_order',
|
||||
])]
|
||||
class FeaturedGroup extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $table = 'featured_groups';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'product_layout' => ProductLayout::class,
|
||||
'group_order' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Tenant, $this> */
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
||||
}
|
||||
|
||||
/** @return HasMany<FeaturedItem, $this> */
|
||||
public function featuredItems(): HasMany
|
||||
{
|
||||
return $this->hasMany(FeaturedItem::class)->orderBy('order');
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
'catalog_item_id',
|
||||
'inventory_id',
|
||||
])]
|
||||
class Variant extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $table = 'variantes';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'catalog_item_id' => 'integer',
|
||||
'inventory_id' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<CatalogItem, $this> */
|
||||
public function catalogItem(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CatalogItem::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Inventory, $this> */
|
||||
public function inventory(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Inventory::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<VariantDefinition, $this> */
|
||||
public function definitions(): HasMany
|
||||
{
|
||||
return $this->hasMany(VariantDefinition::class);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function attachments(): BelongsToMany
|
||||
{
|
||||
$relation = $this->belongsToMany(
|
||||
Attachment::class,
|
||||
'catalog_items_attachments',
|
||||
'variant_id',
|
||||
'attachment_id'
|
||||
)
|
||||
->withPivot('orden')
|
||||
->orderByPivot('orden');
|
||||
|
||||
if ($this->catalog_item_id !== null) {
|
||||
$relation->withPivotValue('catalog_item_id', $this->catalog_item_id);
|
||||
}
|
||||
|
||||
return $relation;
|
||||
}
|
||||
|
||||
public function getPrice(): float
|
||||
{
|
||||
return $this->catalogItem->getPrice();
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
$name = $this->catalogItem->nombre;
|
||||
$this->loadMissing('definitions.itemAttribute.attribute');
|
||||
$definitions = $this->definitions
|
||||
->map(function (VariantDefinition $definition): ?string {
|
||||
$attributeName = $definition->itemAttribute?->attribute?->nombre;
|
||||
|
||||
return $attributeName
|
||||
? "{$attributeName}: {$definition->value}"
|
||||
: $definition->value;
|
||||
})
|
||||
->filter()
|
||||
->implode(', ');
|
||||
|
||||
return $definitions === '' ? $name : "{$name} ({$definitions})";
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Requests;
|
||||
|
||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class StoreCatalogItemRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
$tenantCode = $this->route('tenant')?->codigo;
|
||||
$type = $this->input('type', CatalogItemType::Standard->value);
|
||||
$isBundle = $type === CatalogItemType::Bundle->value;
|
||||
|
||||
return [
|
||||
'tenant_code' => ['prohibited'],
|
||||
'type' => ['sometimes', Rule::enum(CatalogItemType::class)],
|
||||
'category_id' => [
|
||||
'sometimes',
|
||||
'nullable',
|
||||
'integer',
|
||||
Rule::exists('categorias', 'id')->where(
|
||||
fn ($query) => $query->where('tenant_code', $tenantCode)
|
||||
),
|
||||
],
|
||||
'brand_id' => [
|
||||
'sometimes',
|
||||
'nullable',
|
||||
'integer',
|
||||
Rule::exists('brands', 'id')->where(
|
||||
fn ($query) => $query->where('tenant_codigo', $tenantCode)
|
||||
),
|
||||
],
|
||||
'slug' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('catalog_items', 'slug')->where(
|
||||
fn ($query) => $query->where('tenant_code', $tenantCode)
|
||||
),
|
||||
],
|
||||
'nombre' => ['required', 'string', 'max:255'],
|
||||
'descripcion' => ['sometimes', 'nullable', 'string'],
|
||||
'precio' => ['required', 'numeric', 'min:0'],
|
||||
'inventory_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(InventoryPolicy::class)],
|
||||
'has_tickets' => [Rule::prohibitedIf($isBundle), 'sometimes', 'boolean'],
|
||||
'minimum_use_date' => [Rule::prohibitedIf($isBundle), 'sometimes', 'nullable', 'date'],
|
||||
'maximum_use_date' => [Rule::prohibitedIf($isBundle), 'sometimes', 'nullable', 'date', 'after_or_equal:minimum_use_date'],
|
||||
'real_stock' => [Rule::prohibitedIf($isBundle), 'sometimes', 'integer', 'min:0'],
|
||||
'inventory_id' => ['prohibited'],
|
||||
'reserved_stock' => ['prohibited'],
|
||||
'sold_units' => ['prohibited'],
|
||||
'attribute_codes' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
|
||||
'attribute_codes.*' => [
|
||||
'required',
|
||||
'string',
|
||||
'distinct',
|
||||
Rule::exists('attribute', 'codigo')->where(
|
||||
fn ($query) => $query->where('tenant_codigo', $tenantCode)
|
||||
),
|
||||
],
|
||||
'images' => ['sometimes', 'array'],
|
||||
'images.*' => ['required', new ImageOrBase64Rule],
|
||||
'variants' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
|
||||
'variants.*.real_stock' => ['sometimes', 'integer', 'min:0'],
|
||||
'variants.*.inventory_id' => ['prohibited'],
|
||||
'variants.*.reserved_stock' => ['prohibited'],
|
||||
'variants.*.sold_units' => ['prohibited'],
|
||||
'variants.*.values' => ['sometimes', 'array'],
|
||||
'variants.*.values.*' => ['nullable', 'string'],
|
||||
'variants.*.images' => ['sometimes', 'array'],
|
||||
'variants.*.images.*' => ['required', new ImageOrBase64Rule],
|
||||
'components' => [
|
||||
Rule::requiredIf($isBundle),
|
||||
Rule::prohibitedIf(! $isBundle),
|
||||
'array',
|
||||
'min:1',
|
||||
],
|
||||
'components.*.catalog_item_id' => [
|
||||
'required',
|
||||
'integer',
|
||||
Rule::exists('catalog_items', 'id')->where(
|
||||
fn ($query) => $query->where('tenant_code', $tenantCode)
|
||||
),
|
||||
],
|
||||
'components.*.variant_id' => [
|
||||
'sometimes',
|
||||
'nullable',
|
||||
'integer',
|
||||
Rule::exists('variantes', 'id'),
|
||||
],
|
||||
'components.*.quantity' => ['required', 'integer', 'min:1'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Resources;
|
||||
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\FeaturedItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin FeaturedItem */
|
||||
class CatalogFeaturedItemResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$catalogItem = $this->catalogItem;
|
||||
|
||||
if ($this->featuredGroup->product_layout === ProductLayout::ColumnWithImage) {
|
||||
return $this->columnWithImageData($catalogItem);
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => $catalogItem->id,
|
||||
'type' => $catalogItem->type->value,
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'descripcion' => $catalogItem->descripcion,
|
||||
'precio' => $catalogItem->precio,
|
||||
'stock_tecnico' => $catalogItem->availableStock(),
|
||||
'variants' => $catalogItem->variants
|
||||
->map(fn (Variant $variant): array => [
|
||||
'id' => $variant->id,
|
||||
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock(),
|
||||
'values' => $variant->definitions
|
||||
->mapWithKeys(fn ($definition) => [
|
||||
$definition->itemAttribute?->attribute?->codigo => $definition->value,
|
||||
])
|
||||
->filter(fn ($value, $key): bool => $key !== null),
|
||||
])
|
||||
->values(),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function columnWithImageData(CatalogItem $catalogItem): array
|
||||
{
|
||||
$attachment = $catalogItem->attachments->first()
|
||||
?? $catalogItem->variants
|
||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||
->first();
|
||||
|
||||
return [
|
||||
'id' => $catalogItem->id,
|
||||
'type' => $catalogItem->type->value,
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'precio' => $catalogItem->precio,
|
||||
'image' => $attachment?->getTemporaryUrl(1440),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Resources;
|
||||
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/** @mixin CatalogItem */
|
||||
class CatalogItemDetailResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
/** @var Variant|null $selectedVariant */
|
||||
$selectedVariant = $this->resource->getRelation('selectedVariant');
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'type' => $this->type->value,
|
||||
'category_id' => $this->category_id,
|
||||
'brand_id' => $this->brand_id,
|
||||
'slug' => $this->slug,
|
||||
'nombre' => $this->nombre,
|
||||
'descripcion' => $this->descripcion,
|
||||
'precio' => $this->precio,
|
||||
'category' => $this->category?->nombre,
|
||||
'brand' => $this->brand?->nombre,
|
||||
'inventory_policy' => $this->inventory_policy?->value,
|
||||
'has_tickets' => $this->has_tickets,
|
||||
'minimum_use_date' => $this->minimum_use_date,
|
||||
'maximum_use_date' => $this->maximum_use_date,
|
||||
'attributes' => $this->itemAttributes
|
||||
->map(fn (ItemAttribute $itemAttribute): array => $this->attributeData($itemAttribute))
|
||||
->values(),
|
||||
'stock_tecnico' => $this->when(
|
||||
$selectedVariant === null,
|
||||
fn () => $this->availableStock(),
|
||||
),
|
||||
'images' => $this->when(
|
||||
$selectedVariant === null,
|
||||
fn () => $this->imageUrls($this->attachments),
|
||||
),
|
||||
'variants' => $this->variants
|
||||
->map(fn (Variant $variant): array => $this->variantData($variant))
|
||||
->values(),
|
||||
'selected_variant' => $this->when(
|
||||
$selectedVariant !== null,
|
||||
fn (): array => [
|
||||
...$this->variantData($selectedVariant),
|
||||
'images' => $this->imageUrls($selectedVariant->attachments),
|
||||
],
|
||||
),
|
||||
'components' => $this->when(
|
||||
$this->isBundle(),
|
||||
fn () => $this->bundleComponents
|
||||
->map(function ($component): array {
|
||||
$selectedItem = $component->variant ?? $component->catalogItem;
|
||||
|
||||
return [
|
||||
'catalog_item_id' => $component->component_catalog_item_id,
|
||||
'variant_id' => $component->component_variant_id,
|
||||
'quantity' => $component->quantity,
|
||||
'nombre' => $component->catalogItem->nombre,
|
||||
'item_nombre' => $selectedItem->getName(),
|
||||
];
|
||||
})
|
||||
->values(),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function attributeData(ItemAttribute $itemAttribute): array
|
||||
{
|
||||
$attribute = $itemAttribute->attribute;
|
||||
$availableValues = $this->variants
|
||||
->flatMap->definitions
|
||||
->where('item_attribute_id', $itemAttribute->id)
|
||||
->pluck('value')
|
||||
->filter()
|
||||
->unique();
|
||||
|
||||
return [
|
||||
'id' => $attribute->id,
|
||||
'codigo' => $attribute->codigo,
|
||||
'nombre' => $attribute->nombre,
|
||||
'is_required' => $attribute->is_required,
|
||||
'metadata_schema' => $attribute->metadata_schema,
|
||||
'type' => $attribute->type->value,
|
||||
'options' => $attribute->options
|
||||
->whereIn('value', $availableValues)
|
||||
->map(fn ($option): array => [
|
||||
'id' => $option->id,
|
||||
'value' => $option->value,
|
||||
'label' => $option->label,
|
||||
'sort_order' => $option->sort_order,
|
||||
'metadata' => $option->metadata,
|
||||
])
|
||||
->values(),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function variantData(Variant $variant): array
|
||||
{
|
||||
return [
|
||||
'id' => $variant->id,
|
||||
'stock_tecnico' => $this->variantStock($variant),
|
||||
'values' => $variant->definitions
|
||||
->mapWithKeys(fn ($definition) => [
|
||||
$definition->itemAttribute?->attribute?->codigo => $definition->value,
|
||||
])
|
||||
->filter(fn ($value, $key): bool => $key !== null),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return Collection<int, string> */
|
||||
private function imageUrls(Collection $attachments): Collection
|
||||
{
|
||||
return $attachments
|
||||
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
||||
->values();
|
||||
}
|
||||
|
||||
private function variantStock(Variant $variant): ?int
|
||||
{
|
||||
return $this->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock();
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Resources;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin CatalogItem */
|
||||
class CatalogItemResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'type' => $this->type->value,
|
||||
'category_id' => $this->category_id,
|
||||
'brand_id' => $this->brand_id,
|
||||
'slug' => $this->slug,
|
||||
'nombre' => $this->nombre,
|
||||
'descripcion' => $this->descripcion,
|
||||
'precio' => $this->precio,
|
||||
'inventory_policy' => $this->inventory_policy?->value,
|
||||
'has_tickets' => $this->has_tickets,
|
||||
'minimum_use_date' => $this->minimum_use_date,
|
||||
'maximum_use_date' => $this->maximum_use_date,
|
||||
'real_stock' => $this->whenLoaded('inventory', fn () => $this->inventory?->real_stock),
|
||||
'images' => $this->whenLoaded('attachments', fn () => $this->attachments
|
||||
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
||||
->values()),
|
||||
'variants' => $this->whenLoaded('variants', fn () => $this->variants
|
||||
->map(fn ($variant) => [
|
||||
'id' => $variant->id,
|
||||
'real_stock' => $variant->inventory?->real_stock,
|
||||
'values' => $variant->definitions
|
||||
->mapWithKeys(fn ($definition) => [
|
||||
$definition->itemAttribute?->attribute?->codigo => $definition->value,
|
||||
])
|
||||
->filter(fn ($value, $key) => $key !== null),
|
||||
'images' => $variant->attachments
|
||||
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
||||
->values(),
|
||||
])
|
||||
->values()),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,469 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Services;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Services\AttachmentService;
|
||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||
use App\Domains\Catalog\Models\Attribute;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class CatalogService
|
||||
{
|
||||
public function __construct(protected AttachmentService $attachmentService) {}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public function create(array $data): CatalogItem
|
||||
{
|
||||
return DB::transaction(function () use ($data): CatalogItem {
|
||||
$type = CatalogItemType::from(
|
||||
$data['type'] ?? CatalogItemType::Standard->value,
|
||||
);
|
||||
$variants = $data['variants'] ?? [];
|
||||
$images = $data['images'] ?? [];
|
||||
$attributeCodes = $data['attribute_codes'] ?? [];
|
||||
$components = $data['components'] ?? [];
|
||||
$hasDirectStock = array_key_exists('real_stock', $data);
|
||||
$realStock = (int) ($data['real_stock'] ?? 0);
|
||||
|
||||
$hasVariants = $attributeCodes !== [];
|
||||
|
||||
if ($type === CatalogItemType::Bundle) {
|
||||
$this->validateBundleData($data, $components);
|
||||
} else {
|
||||
if (array_key_exists('components', $data)) {
|
||||
throw ValidationException::withMessages([
|
||||
'components' => ['Un item standard no puede tener componentes.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$this->validateInventoryStrategy(
|
||||
$data,
|
||||
$variants,
|
||||
$hasVariants,
|
||||
$hasDirectStock,
|
||||
);
|
||||
}
|
||||
|
||||
unset(
|
||||
$data['variants'],
|
||||
$data['images'],
|
||||
$data['attribute_codes'],
|
||||
$data['components'],
|
||||
$data['real_stock'],
|
||||
$data['reserved_stock'],
|
||||
$data['sold_units'],
|
||||
$data['inventory_id'],
|
||||
);
|
||||
|
||||
$data['type'] = $type;
|
||||
|
||||
if ($type === CatalogItemType::Bundle) {
|
||||
$data['inventory_id'] = null;
|
||||
$data['inventory_policy'] = null;
|
||||
$data['has_tickets'] = false;
|
||||
$data['minimum_use_date'] = null;
|
||||
$data['maximum_use_date'] = null;
|
||||
} elseif ($hasVariants) {
|
||||
$data['inventory_id'] = null;
|
||||
} else {
|
||||
$data['inventory_id'] = $this->createInventory($realStock)->id;
|
||||
}
|
||||
|
||||
$catalogItem = CatalogItem::query()->create($data);
|
||||
$itemAttributes = $type === CatalogItemType::Standard
|
||||
? $this->createItemAttributes($catalogItem, $attributeCodes)
|
||||
: [];
|
||||
|
||||
if ($type === CatalogItemType::Bundle) {
|
||||
$this->createBundleComponents($catalogItem, $components);
|
||||
}
|
||||
|
||||
$createdVariants = [];
|
||||
foreach ($variants as $index => $variantData) {
|
||||
$createdVariants[] = [
|
||||
'variant' => $this->createVariant(
|
||||
$catalogItem,
|
||||
$variantData,
|
||||
$itemAttributes,
|
||||
$index,
|
||||
),
|
||||
'images' => $variantData['images'] ?? [],
|
||||
'index' => $index,
|
||||
];
|
||||
}
|
||||
|
||||
$this->attachImages($catalogItem, $images, 'images');
|
||||
|
||||
foreach ($createdVariants as $createdVariant) {
|
||||
$this->attachImages(
|
||||
$createdVariant['variant'],
|
||||
$createdVariant['images'],
|
||||
"variants.{$createdVariant['index']}.images",
|
||||
);
|
||||
}
|
||||
|
||||
return $catalogItem->load([
|
||||
'attachments',
|
||||
'inventory',
|
||||
'category',
|
||||
'brand',
|
||||
'itemAttributes.attribute',
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
'variants.definitions.itemAttribute.attribute',
|
||||
'bundleComponents.catalogItem',
|
||||
'bundleComponents.variant.catalogItem',
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
public function getDetail(CatalogItem $catalogItem, ?int $variantId = null): CatalogItem
|
||||
{
|
||||
$catalogItem->load([
|
||||
'attachments',
|
||||
'inventory',
|
||||
'category',
|
||||
'brand',
|
||||
'itemAttributes.attribute.options',
|
||||
'variants' => fn ($query) => $query->orderBy('id'),
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
'variants.definitions' => fn ($query) => $query->orderBy('id'),
|
||||
'variants.definitions.itemAttribute.attribute',
|
||||
'bundleComponents.catalogItem.inventory',
|
||||
'bundleComponents.variant.inventory',
|
||||
'bundleComponents.variant.definitions.itemAttribute.attribute',
|
||||
]);
|
||||
|
||||
$selectedVariant = $variantId === null
|
||||
? $catalogItem->variants->first()
|
||||
: $catalogItem->variants->firstWhere('id', $variantId);
|
||||
|
||||
if ($variantId !== null && $selectedVariant === null) {
|
||||
throw new NotFoundHttpException('Variant not found for catalog item.');
|
||||
}
|
||||
|
||||
$catalogItem->setRelation('selectedVariant', $selectedVariant);
|
||||
|
||||
return $catalogItem;
|
||||
}
|
||||
|
||||
public function delete(CatalogItem $catalogItem): void
|
||||
{
|
||||
DB::transaction(function () use ($catalogItem): void {
|
||||
$catalogItem->load([
|
||||
'attachments',
|
||||
'variants.attachments',
|
||||
]);
|
||||
|
||||
$attachments = $catalogItem->attachments
|
||||
->merge($catalogItem->variants->flatMap->attachments)
|
||||
->unique('id');
|
||||
$inventoryIds = collect([$catalogItem->inventory_id])
|
||||
->merge($catalogItem->variants->pluck('inventory_id'))
|
||||
->filter()
|
||||
->unique();
|
||||
|
||||
$catalogItem->attachments()->detach();
|
||||
foreach ($catalogItem->variants as $variant) {
|
||||
$variant->attachments()->detach();
|
||||
}
|
||||
|
||||
$catalogItem->delete();
|
||||
Inventory::query()->whereKey($inventoryIds)->delete();
|
||||
|
||||
foreach ($attachments as $attachment) {
|
||||
if (! DB::table('catalog_items_attachments')->where('attachment_id', $attachment->id)->exists()) {
|
||||
$this->attachmentService->delete($attachment);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private function createInventory(int $realStock): Inventory
|
||||
{
|
||||
return Inventory::query()->create([
|
||||
'real_stock' => $realStock,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $components
|
||||
*/
|
||||
private function createBundleComponents(CatalogItem $bundle, array $components): void
|
||||
{
|
||||
$seen = [];
|
||||
|
||||
foreach (array_values($components) as $index => $componentData) {
|
||||
$catalogItemId = (int) $componentData['catalog_item_id'];
|
||||
$variantId = isset($componentData['variant_id'])
|
||||
? (int) $componentData['variant_id']
|
||||
: null;
|
||||
$key = $catalogItemId.':'.($variantId ?? 'direct');
|
||||
|
||||
if (isset($seen[$key])) {
|
||||
throw ValidationException::withMessages([
|
||||
"components.{$index}" => ['El componente esta duplicado.'],
|
||||
]);
|
||||
}
|
||||
$seen[$key] = true;
|
||||
|
||||
$componentItem = CatalogItem::query()
|
||||
->whereKey($catalogItemId)
|
||||
->where('tenant_code', $bundle->tenant_code)
|
||||
->first();
|
||||
|
||||
if ($componentItem === null) {
|
||||
throw ValidationException::withMessages([
|
||||
"components.{$index}.catalog_item_id" => [
|
||||
'El item no pertenece al tenant del bundle.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($componentItem->is($bundle) || $componentItem->type !== CatalogItemType::Standard) {
|
||||
throw ValidationException::withMessages([
|
||||
"components.{$index}.catalog_item_id" => [
|
||||
'El componente debe ser un item standard distinto del bundle.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$hasVariants = $componentItem->variants()->exists();
|
||||
if ($hasVariants && $variantId === null) {
|
||||
throw ValidationException::withMessages([
|
||||
"components.{$index}.variant_id" => [
|
||||
'Debe seleccionar una variante para este componente.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $hasVariants && $variantId !== null) {
|
||||
throw ValidationException::withMessages([
|
||||
"components.{$index}.variant_id" => [
|
||||
'El componente con inventario directo no admite una variante.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($variantId !== null && ! $componentItem->variants()->whereKey($variantId)->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
"components.{$index}.variant_id" => [
|
||||
'La variante no pertenece al componente indicado.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$bundle->bundleComponents()->create([
|
||||
'component_catalog_item_id' => $componentItem->id,
|
||||
'component_variant_id' => $variantId,
|
||||
'quantity' => (int) $componentData['quantity'],
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @param array<int, array<string, mixed>> $components
|
||||
*/
|
||||
private function validateBundleData(array $data, array $components): void
|
||||
{
|
||||
if ($components === []) {
|
||||
throw ValidationException::withMessages([
|
||||
'components' => ['Un bundle debe tener al menos un componente.'],
|
||||
]);
|
||||
}
|
||||
|
||||
foreach ([
|
||||
'real_stock',
|
||||
'inventory_policy',
|
||||
'attribute_codes',
|
||||
'variants',
|
||||
'has_tickets',
|
||||
'minimum_use_date',
|
||||
'maximum_use_date',
|
||||
] as $field) {
|
||||
if (array_key_exists($field, $data)) {
|
||||
throw ValidationException::withMessages([
|
||||
$field => ["{$field} no se admite para un bundle."],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, mixed> $images
|
||||
*/
|
||||
private function attachImages(
|
||||
CatalogItem|Variant $owner,
|
||||
array $images,
|
||||
string $validationKey,
|
||||
): void {
|
||||
foreach (array_values($images) as $order => $image) {
|
||||
$attachment = $this->resolveAttachment($image, "{$validationKey}.{$order}");
|
||||
|
||||
$owner->attachments()->attach($attachment->id, ['orden' => $order]);
|
||||
}
|
||||
}
|
||||
|
||||
private function resolveAttachment(mixed $image, string $validationKey): Attachment
|
||||
{
|
||||
if (is_string($image) && Str::isUuid($image)) {
|
||||
$attachment = Attachment::query()->where('key', $image)->first();
|
||||
|
||||
if ($attachment === null) {
|
||||
throw ValidationException::withMessages([
|
||||
$validationKey => ['El attachment indicado no existe.'],
|
||||
]);
|
||||
}
|
||||
|
||||
return $attachment;
|
||||
}
|
||||
|
||||
return $this->attachmentService->store($image, 'catalog-items');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $attributeCodes
|
||||
* @return array<string, ItemAttribute>
|
||||
*/
|
||||
private function createItemAttributes(
|
||||
CatalogItem $catalogItem,
|
||||
array $attributeCodes,
|
||||
): array {
|
||||
$itemAttributes = [];
|
||||
$attributeCodes = array_values(array_unique($attributeCodes));
|
||||
$attributes = Attribute::query()
|
||||
->where('tenant_codigo', $catalogItem->tenant_code)
|
||||
->whereIn('codigo', $attributeCodes)
|
||||
->get()
|
||||
->keyBy('codigo');
|
||||
|
||||
foreach ($attributeCodes as $attributeCode) {
|
||||
$attribute = $attributes->get($attributeCode);
|
||||
|
||||
if ($attribute === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'attribute_codes' => [
|
||||
"El atributo {$attributeCode} no existe para el tenant del ítem.",
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$itemAttribute = $catalogItem->itemAttributes()->create([
|
||||
'attribute_id' => $attribute->id,
|
||||
]);
|
||||
|
||||
$itemAttributes[$attributeCode] = $itemAttribute;
|
||||
}
|
||||
|
||||
return $itemAttributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @param array<string, ItemAttribute> $itemAttributes
|
||||
*/
|
||||
private function createVariant(
|
||||
CatalogItem $catalogItem,
|
||||
array $data,
|
||||
array $itemAttributes,
|
||||
int $index,
|
||||
): Variant {
|
||||
unset($data['images']);
|
||||
|
||||
if (
|
||||
array_key_exists('inventory_id', $data)
|
||||
|| array_key_exists('reserved_stock', $data)
|
||||
|| array_key_exists('sold_units', $data)
|
||||
) {
|
||||
throw ValidationException::withMessages([
|
||||
"variants.{$index}.inventory" => [
|
||||
'inventory_id, reserved_stock y sold_units son administrados internamente.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$inventory = $this->createInventory((int) ($data['real_stock'] ?? 0));
|
||||
$variant = $catalogItem->variants()->create([
|
||||
'inventory_id' => $inventory->id,
|
||||
]);
|
||||
|
||||
foreach ($data['values'] ?? [] as $attributeCode => $value) {
|
||||
$itemAttribute = $itemAttributes[$attributeCode] ?? null;
|
||||
|
||||
if ($itemAttribute === null) {
|
||||
throw ValidationException::withMessages([
|
||||
"variants.{$index}.values.{$attributeCode}" => [
|
||||
'El atributo no pertenece al ítem de catálogo.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$variant->definitions()->create([
|
||||
'item_attribute_id' => $itemAttribute->id,
|
||||
'value' => $value,
|
||||
]);
|
||||
}
|
||||
|
||||
return $variant;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @param array<int, array<string, mixed>> $variants
|
||||
*/
|
||||
private function validateInventoryStrategy(
|
||||
array $data,
|
||||
array $variants,
|
||||
bool $hasVariants,
|
||||
bool $hasDirectStock,
|
||||
): void {
|
||||
if ($hasVariants && $variants === []) {
|
||||
throw ValidationException::withMessages([
|
||||
'variants' => [
|
||||
'Un ítem con attribute_codes debe tener variantes.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $hasVariants && $variants !== []) {
|
||||
throw ValidationException::withMessages([
|
||||
'variants' => [
|
||||
'Un ítem sin attribute_codes no puede tener variantes.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($hasVariants && $hasDirectStock) {
|
||||
throw ValidationException::withMessages([
|
||||
'real_stock' => [
|
||||
'Un ítem con variantes no puede tener inventario directo.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if (
|
||||
array_key_exists('inventory_id', $data)
|
||||
|| array_key_exists('reserved_stock', $data)
|
||||
|| array_key_exists('sold_units', $data)
|
||||
) {
|
||||
throw ValidationException::withMessages([
|
||||
'inventory' => [
|
||||
'inventory_id, reserved_stock y sold_units son administrados internamente.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Controllers;
|
||||
namespace App\Domains\Commerce\Cart\Controllers;
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Cart\Requests\AddCartItemRequest;
|
||||
use App\Domains\Cart\Requests\UpdateCartItemQuantityRequest;
|
||||
use App\Domains\Cart\Resources\CartResource;
|
||||
use App\Domains\Cart\Services\CartService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Commerce\Cart\Models\CartItem;
|
||||
use App\Domains\Commerce\Cart\Requests\AddCartItemRequest;
|
||||
use App\Domains\Commerce\Cart\Requests\UpdateCartItemQuantityRequest;
|
||||
use App\Domains\Commerce\Cart\Resources\CartResource;
|
||||
use App\Domains\Commerce\Cart\Services\CartService;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -36,7 +36,10 @@ class CartController extends Controller
|
||||
);
|
||||
|
||||
$response = CartResource::make($result['cart'])
|
||||
->additional(['message' => 'Producto agregado al carrito.'])
|
||||
->additional([
|
||||
'code' => 'cart.item_added',
|
||||
'message' => __('api.cart.item_added'),
|
||||
])
|
||||
->response();
|
||||
|
||||
if ($result['guest_token'] !== null) {
|
||||
@@ -51,20 +54,36 @@ class CartController extends Controller
|
||||
Tenant $tenant,
|
||||
CartItem $cartItem,
|
||||
): CartResource {
|
||||
$updatesVariant = $request->exists('variant_id');
|
||||
|
||||
return CartResource::make(
|
||||
$this->cartService->updateItemQuantity(
|
||||
$this->cartService->updateItem(
|
||||
$tenant,
|
||||
$request,
|
||||
$cartItem->getKey(),
|
||||
(int) $request->validated('cantidad'),
|
||||
$updatesVariant
|
||||
? ($request->validated('variant_id') !== null
|
||||
? (int) $request->validated('variant_id')
|
||||
: null)
|
||||
: $cartItem->variant_id,
|
||||
$updatesVariant,
|
||||
)
|
||||
)->additional(['message' => 'Cantidad de producto actualizada.']);
|
||||
)->additional([
|
||||
'code' => $updatesVariant ? 'cart.item_updated' : 'cart.quantity_updated',
|
||||
'message' => $updatesVariant
|
||||
? __('api.cart.item_updated')
|
||||
: __('api.cart.quantity_updated'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function removeItem(Request $request, Tenant $tenant, CartItem $cartItem): CartResource
|
||||
{
|
||||
return CartResource::make(
|
||||
$this->cartService->removeItem($tenant, $request, $cartItem->getKey())
|
||||
)->additional(['message' => 'Producto eliminado del carrito.']);
|
||||
)->additional([
|
||||
'code' => 'cart.item_removed',
|
||||
'message' => __('api.cart.item_removed'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
494
app/Domains/Commerce/Cart/Models/Cart.php
Normal file
494
app/Domains/Commerce/Cart/Models/Cart.php
Normal file
@@ -0,0 +1,494 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Cart\Models;
|
||||
|
||||
use App\Domains\Core\Auth\Models\User;
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Commerce\Catalog\Models\Inventory;
|
||||
use App\Domains\Commerce\Catalog\Models\StockReservation;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use App\Domains\Commerce\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Commerce\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||
use App\Domains\Commerce\Purchase\Services\UserPurchaseLimitService;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_codigo',
|
||||
'user_id',
|
||||
'guest_token',
|
||||
'status',
|
||||
'origin',
|
||||
'current_purchase_id',
|
||||
'current_stock_reservation_id',
|
||||
])]
|
||||
class Cart extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use SoftDeletes;
|
||||
|
||||
protected $table = 'carritos';
|
||||
|
||||
public const STATUS_ACTIVE = 'active';
|
||||
|
||||
public const STATUS_CHECKOUT = 'checkout';
|
||||
|
||||
public const STATUS_CONVERTED = 'converted';
|
||||
|
||||
public const STATUS_EXPIRED = 'expired';
|
||||
|
||||
public const STATUS_ABANDONED = 'abandoned';
|
||||
|
||||
public const ORIGIN_USER = 'user';
|
||||
|
||||
public const ORIGIN_DIRECT_CHECKOUT = 'direct_checkout';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'user_id' => 'integer',
|
||||
'current_purchase_id' => 'integer',
|
||||
'current_stock_reservation_id' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Tenant, $this>
|
||||
*/
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_codigo', 'codigo');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<CartItem, $this>
|
||||
*/
|
||||
public function items(): HasMany
|
||||
{
|
||||
return $this->hasMany(CartItem::class, 'cart_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<Purchase, $this> */
|
||||
public function purchases(): HasMany
|
||||
{
|
||||
return $this->hasMany(Purchase::class, 'cart_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Purchase, $this> */
|
||||
public function currentPurchase(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Purchase::class, 'current_purchase_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<StockReservation, $this> */
|
||||
public function currentStockReservation(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(
|
||||
StockReservation::class,
|
||||
'current_stock_reservation_id',
|
||||
);
|
||||
}
|
||||
|
||||
public function getTotalAmount(): float
|
||||
{
|
||||
$items = $this->relationLoaded('items')
|
||||
? $this->getRelation('items')
|
||||
: $this->items()->with(['catalogItem', 'variant'])->get();
|
||||
|
||||
return (float) $items->reduce(
|
||||
fn (float $carry, CartItem $item): float => $carry
|
||||
+ (($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad),
|
||||
0.0,
|
||||
);
|
||||
}
|
||||
|
||||
public function addItem(int $catalogItemId, ?int $variantId, int $quantity): CartItem
|
||||
{
|
||||
if ($quantity <= 0) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => __('api.cart.positive_quantity'),
|
||||
]);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
|
||||
$this->invalidateCurrentCheckout();
|
||||
app(StockReservationService::class)->assertCartReservationUsable($this);
|
||||
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
|
||||
$cartQuantity = (int) $this->items()
|
||||
->where('catalog_item_id', $catalogItemId)
|
||||
->sum('cantidad');
|
||||
$inventoryService = app(CatalogInventoryService::class);
|
||||
$availableQuantity = $inventoryService->availableQuantity($selectedItem);
|
||||
$this->assertUserPurchaseLimit(
|
||||
$selectedItem,
|
||||
$cartQuantity + $quantity,
|
||||
heldQuantity: $cartQuantity,
|
||||
maximumAddableCeiling: $availableQuantity,
|
||||
);
|
||||
|
||||
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => __('api.cart.insufficient_stock', ['max' => $availableQuantity]),
|
||||
]);
|
||||
}
|
||||
|
||||
/** @var CartItem|null $item */
|
||||
$item = $this->items()
|
||||
->where('catalog_item_id', $catalogItemId)
|
||||
->where('variant_id', $variantId)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($item === null) {
|
||||
$item = $this->items()->create([
|
||||
'catalog_item_id' => $catalogItemId,
|
||||
'variant_id' => $variantId,
|
||||
'cantidad' => $quantity,
|
||||
]);
|
||||
} else {
|
||||
$item->cantidad += $quantity;
|
||||
$item->save();
|
||||
}
|
||||
|
||||
app(StockReservationService::class)->syncCart($this);
|
||||
|
||||
return $item->fresh();
|
||||
});
|
||||
}
|
||||
|
||||
public function updateItem(
|
||||
int $cartItemId,
|
||||
int $quantity,
|
||||
?int $variantId = null,
|
||||
bool $updateVariant = false,
|
||||
?int $excludedPurchaseId = null,
|
||||
): CartItem {
|
||||
if ($quantity <= 0) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => __('api.cart.positive_quantity'),
|
||||
]);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use (
|
||||
$cartItemId,
|
||||
$quantity,
|
||||
$variantId,
|
||||
$updateVariant,
|
||||
$excludedPurchaseId,
|
||||
): CartItem {
|
||||
$this->invalidateCurrentCheckout();
|
||||
app(StockReservationService::class)->assertCartReservationUsable($this);
|
||||
|
||||
/** @var CartItem $item */
|
||||
$item = $this->items()
|
||||
->where('id', $cartItemId)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$currentSelection = $this->resolveScopedItem(
|
||||
$item->catalog_item_id,
|
||||
$item->variant_id,
|
||||
true,
|
||||
);
|
||||
$inventoryService = app(CatalogInventoryService::class);
|
||||
|
||||
if ($updateVariant && $variantId !== $item->variant_id) {
|
||||
$nextSelection = $this->resolveScopedItem(
|
||||
$item->catalog_item_id,
|
||||
$variantId,
|
||||
true,
|
||||
);
|
||||
$otherVariantsQuantity = (int) $this->items()
|
||||
->where('catalog_item_id', $item->catalog_item_id)
|
||||
->whereKeyNot($item->getKey())
|
||||
->sum('cantidad');
|
||||
$nextAvailableQuantity = $inventoryService->availableQuantity($nextSelection);
|
||||
$this->assertUserPurchaseLimit(
|
||||
$nextSelection,
|
||||
$otherVariantsQuantity + $quantity,
|
||||
$excludedPurchaseId,
|
||||
$otherVariantsQuantity + $item->cantidad,
|
||||
$nextAvailableQuantity,
|
||||
);
|
||||
|
||||
$availableQuantity = $inventoryService->availableQuantity($nextSelection);
|
||||
|
||||
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => __('api.cart.insufficient_stock', ['max' => $availableQuantity]),
|
||||
]);
|
||||
}
|
||||
|
||||
$targetItem = $this->items()
|
||||
->where('catalog_item_id', $item->catalog_item_id)
|
||||
->where('variant_id', $variantId)
|
||||
->whereKeyNot($item->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($targetItem !== null) {
|
||||
$targetItem->cantidad += $quantity;
|
||||
$targetItem->save();
|
||||
$item->delete();
|
||||
app(StockReservationService::class)->syncCart($this);
|
||||
|
||||
return $targetItem->fresh();
|
||||
}
|
||||
|
||||
$item->variant_id = $variantId;
|
||||
$item->cantidad = $quantity;
|
||||
$item->save();
|
||||
app(StockReservationService::class)->syncCart($this);
|
||||
|
||||
return $item->fresh();
|
||||
}
|
||||
|
||||
$delta = $quantity - $item->cantidad;
|
||||
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
|
||||
|
||||
if ($delta > 0) {
|
||||
$otherVariantsQuantity = (int) $this->items()
|
||||
->where('catalog_item_id', $item->catalog_item_id)
|
||||
->whereKeyNot($item->getKey())
|
||||
->sum('cantidad');
|
||||
$this->assertUserPurchaseLimit(
|
||||
$currentSelection,
|
||||
$otherVariantsQuantity + $quantity,
|
||||
$excludedPurchaseId,
|
||||
$otherVariantsQuantity + $item->cantidad,
|
||||
$availableQuantity,
|
||||
);
|
||||
}
|
||||
|
||||
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
|
||||
$maxAvailable = $availableQuantity + $item->cantidad;
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => __('api.cart.max_quantity', ['max' => $maxAvailable]),
|
||||
]);
|
||||
}
|
||||
|
||||
$item->cantidad = $quantity;
|
||||
$item->save();
|
||||
app(StockReservationService::class)->syncCart($this);
|
||||
|
||||
return $item->fresh();
|
||||
});
|
||||
}
|
||||
|
||||
public function removeItem(int $cartItemId): void
|
||||
{
|
||||
DB::transaction(function () use ($cartItemId): void {
|
||||
$this->invalidateCurrentCheckout();
|
||||
app(StockReservationService::class)->assertCartReservationUsable($this);
|
||||
|
||||
/** @var CartItem $item */
|
||||
$item = $this->items()
|
||||
->where('id', $cartItemId)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$item->delete();
|
||||
app(StockReservationService::class)->syncCart($this);
|
||||
});
|
||||
}
|
||||
|
||||
private function invalidateCurrentCheckout(): void
|
||||
{
|
||||
$candidatePurchaseId = self::query()
|
||||
->whereKey($this->getKey())
|
||||
->value('current_purchase_id');
|
||||
$currentPurchase = $candidatePurchaseId === null
|
||||
? null
|
||||
: Purchase::query()->lockForUpdate()->find($candidatePurchaseId);
|
||||
|
||||
/** @var self $cart */
|
||||
$cart = self::query()->lockForUpdate()->findOrFail($this->getKey());
|
||||
|
||||
if ($cart->current_purchase_id !== $candidatePurchaseId) {
|
||||
if ($cart->current_purchase_id !== null) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart' => __('api.purchase.checkout_in_progress'),
|
||||
]);
|
||||
}
|
||||
|
||||
$this->current_purchase_id = null;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($currentPurchase === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($currentPurchase->status === Purchase::STATUS_PAID) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart' => __('api.cart.editing_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
if (in_array($currentPurchase->status, [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)) {
|
||||
app(StockReservationService::class)->returnToCart($currentPurchase, $cart);
|
||||
$currentPurchase->update([
|
||||
'status' => Purchase::STATUS_SUPERSEDED,
|
||||
]);
|
||||
|
||||
$this->current_purchase_id = null;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
app(StockReservationService::class)->releaseForPurchase(
|
||||
$currentPurchase,
|
||||
reason: StockReservationService::REASON_PURCHASE_SUPERSEDED,
|
||||
);
|
||||
self::query()
|
||||
->whereKey($cart->getKey())
|
||||
->where('current_purchase_id', $currentPurchase->getKey())
|
||||
->update(['current_purchase_id' => null]);
|
||||
$this->current_purchase_id = null;
|
||||
}
|
||||
|
||||
protected function resolveScopedItem(
|
||||
int $catalogItemId,
|
||||
?int $variantId,
|
||||
bool $lockForUpdate = false,
|
||||
): CatalogItem|Variant {
|
||||
$catalogItemQuery = CatalogItem::query()
|
||||
->whereKey($catalogItemId)
|
||||
->forTenantCatalog($this->tenant()->firstOrFail());
|
||||
|
||||
if ($lockForUpdate) {
|
||||
$catalogItemQuery->lockForUpdate();
|
||||
}
|
||||
|
||||
$catalogItem = $catalogItemQuery->first();
|
||||
|
||||
if ($catalogItem === null) {
|
||||
throw new NotFoundHttpException('Catalog item not found for tenant.');
|
||||
}
|
||||
|
||||
if ($catalogItem->isBundle()) {
|
||||
if ($variantId !== null) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => __('api.cart.bundle_variant_forbidden'),
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $catalogItem->bundleComponents()->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
'catalog_item_id' => __('api.cart.empty_bundle'),
|
||||
]);
|
||||
}
|
||||
|
||||
if ($catalogItem->bundleComponents()
|
||||
->whereNotNull('component_variant_id')
|
||||
->whereHas('variant', fn ($query) => $query
|
||||
->whereNotNull('sales_disabled_at')
|
||||
->orWhereNotNull('replaced_by_variant_id'))
|
||||
->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
'catalog_item_id' => [__('api.cart.bundle_component_unavailable')],
|
||||
]);
|
||||
}
|
||||
|
||||
return $catalogItem;
|
||||
}
|
||||
|
||||
if ($variantId === null) {
|
||||
if ($catalogItem->inventory_id === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => __('api.cart.variant_required'),
|
||||
]);
|
||||
}
|
||||
|
||||
$inventory = $this->resolveInventory($catalogItem->inventory_id, $lockForUpdate);
|
||||
$catalogItem->setRelation('inventory', $inventory);
|
||||
|
||||
return $catalogItem;
|
||||
}
|
||||
|
||||
$variantQuery = Variant::query()
|
||||
->whereKey($variantId)
|
||||
->where('catalog_item_id', $catalogItem->id);
|
||||
|
||||
if ($lockForUpdate) {
|
||||
$variantQuery->lockForUpdate();
|
||||
}
|
||||
|
||||
$variant = $variantQuery->first();
|
||||
|
||||
if ($variant === null) {
|
||||
throw new NotFoundHttpException('Variant not found for catalog item.');
|
||||
}
|
||||
|
||||
if (! $variant->isSellable()) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => [__('api.cart.variant_unavailable')],
|
||||
]);
|
||||
}
|
||||
|
||||
$inventory = $this->resolveInventory($variant->inventory_id, $lockForUpdate);
|
||||
$variant->setRelation('catalogItem', $catalogItem);
|
||||
$variant->setRelation('inventory', $inventory);
|
||||
|
||||
return $variant;
|
||||
}
|
||||
|
||||
private function assertUserPurchaseLimit(
|
||||
CatalogItem|Variant $selectedItem,
|
||||
int $cartQuantity,
|
||||
?int $excludedPurchaseId = null,
|
||||
int $heldQuantity = 0,
|
||||
?int $maximumAddableCeiling = null,
|
||||
): void {
|
||||
if ($this->user_id === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$catalogItem = $selectedItem instanceof Variant
|
||||
? $selectedItem->catalogItem
|
||||
: $selectedItem;
|
||||
|
||||
app(UserPurchaseLimitService::class)->assertCanPurchase(
|
||||
$catalogItem,
|
||||
$this->user_id,
|
||||
$cartQuantity,
|
||||
$excludedPurchaseId,
|
||||
$this->getKey(),
|
||||
$heldQuantity,
|
||||
$maximumAddableCeiling,
|
||||
field: 'cantidad',
|
||||
);
|
||||
}
|
||||
|
||||
protected function resolveInventory(int $inventoryId, bool $lockForUpdate): Inventory
|
||||
{
|
||||
$query = Inventory::query()->whereKey($inventoryId);
|
||||
|
||||
if ($lockForUpdate) {
|
||||
$query->lockForUpdate();
|
||||
}
|
||||
|
||||
return $query->firstOrFail();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Models;
|
||||
namespace App\Domains\Commerce\Cart\Models;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Requests;
|
||||
namespace App\Domains\Commerce\Cart\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Requests;
|
||||
namespace App\Domains\Commerce\Cart\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
@@ -19,7 +19,7 @@ class UpdateCartItemQuantityRequest extends FormRequest
|
||||
return [
|
||||
'cantidad' => ['required', 'integer', 'min:1'],
|
||||
'catalog_item_id' => ['prohibited'],
|
||||
'variant_id' => ['prohibited'],
|
||||
'variant_id' => ['sometimes', 'nullable', 'integer'],
|
||||
];
|
||||
}
|
||||
}
|
||||
73
app/Domains/Commerce/Cart/Resources/CartItemResource.php
Normal file
73
app/Domains/Commerce/Cart/Resources/CartItemResource.php
Normal file
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Cart\Resources;
|
||||
|
||||
use App\Domains\Commerce\Cart\Models\CartItem;
|
||||
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin CartItem
|
||||
*/
|
||||
class CartItemResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$selectedItem = $this->selectedItem();
|
||||
$imageUrl = null;
|
||||
$tenant = $request->route('tenant');
|
||||
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
|
||||
$includeVariants = $tenant instanceof Tenant
|
||||
&& $tenant->cart_editing_policy->allowsVariantChanges();
|
||||
|
||||
if ($displayImage && $selectedItem?->relationLoaded('attachments')) {
|
||||
$imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440);
|
||||
}
|
||||
|
||||
if ($displayImage && $imageUrl === null && $this->catalogItem?->relationLoaded('attachments')) {
|
||||
$imageUrl = $this->catalogItem->attachments->first()?->getTemporaryUrl(1440);
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'cantidad' => $this->cantidad,
|
||||
'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()),
|
||||
'catalog_item_id' => $this->catalog_item_id,
|
||||
'variant_id' => $this->variant_id,
|
||||
'nombre' => $selectedItem?->getName(),
|
||||
'imagen' => $imageUrl,
|
||||
'variant' => $this->variant === null ? null : $this->variantData($this->variant),
|
||||
'variants' => $this->when(
|
||||
$includeVariants,
|
||||
fn () => $this->catalogItem
|
||||
->visibleVariants($this->variant_id)
|
||||
->map(fn (Variant $variant): array => $this->variantData($variant))
|
||||
->values(),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
protected function variantData(Variant $variant): array
|
||||
{
|
||||
return [
|
||||
'id' => $variant->id,
|
||||
'precio' => $this->formatMoney($variant->precio ?? $this->catalogItem->precio),
|
||||
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock(),
|
||||
'values' => $variant->selectorOptions($this->catalogItem->itemAttributes),
|
||||
];
|
||||
}
|
||||
|
||||
protected function formatMoney(float|int|string|null $amount): string
|
||||
{
|
||||
return number_format((float) ($amount ?? 0), 2, '.', '');
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Resources;
|
||||
namespace App\Domains\Commerce\Cart\Resources;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Commerce\Cart\Models\Cart;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
332
app/Domains/Commerce/Cart/Services/CartService.php
Normal file
332
app/Domains/Commerce/Cart/Services/CartService.php
Normal file
@@ -0,0 +1,332 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Cart\Services;
|
||||
|
||||
use App\Domains\Core\Auth\Models\User;
|
||||
use App\Domains\Commerce\Cart\Models\Cart;
|
||||
use App\Domains\Commerce\Catalog\Exceptions\StockReservationExpiredException;
|
||||
use App\Domains\Commerce\Catalog\Services\ExpireStockReservationsService;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpFoundation\Cookie;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class CartService
|
||||
{
|
||||
public function show(Tenant $tenant, Request $request): Cart
|
||||
{
|
||||
$resolvedIdentity = $this->resolveIdentity($request);
|
||||
|
||||
if ($resolvedIdentity === null) {
|
||||
return $this->makeEmptyCart($tenant);
|
||||
}
|
||||
|
||||
$cart = $this->resolveCart($tenant, $resolvedIdentity['identity']);
|
||||
|
||||
if ($cart === null) {
|
||||
return $this->makeEmptyCart($tenant);
|
||||
}
|
||||
|
||||
return $this->loadCart($cart, $tenant);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{cart: Cart, guest_token: ?string}
|
||||
*/
|
||||
public function addItem(
|
||||
Tenant $tenant,
|
||||
Request $request,
|
||||
int $catalogItemId,
|
||||
?int $variantId,
|
||||
int $quantity,
|
||||
): array {
|
||||
$resolvedIdentity = $this->resolveIdentity($request, true);
|
||||
$identity = $resolvedIdentity['identity'];
|
||||
$cart = $this->findOrCreateCart($tenant, $identity);
|
||||
$cart->addItem($catalogItemId, $variantId, $quantity);
|
||||
|
||||
return [
|
||||
'cart' => $this->loadCart($cart, $tenant),
|
||||
'guest_token' => $resolvedIdentity['generated_guest_token'],
|
||||
];
|
||||
}
|
||||
|
||||
public function updateItem(
|
||||
Tenant $tenant,
|
||||
Request $request,
|
||||
int $cartItemId,
|
||||
int $quantity,
|
||||
?int $variantId,
|
||||
bool $updateVariant,
|
||||
): Cart {
|
||||
if ($updateVariant && ! $tenant->cart_editing_policy->allowsVariantChanges()) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => __('api.cart.variant_change_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $updateVariant && ! $tenant->cart_editing_policy->allowsQuantityChanges()) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => __('api.cart.editing_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
$identity = $this->requireIdentity($request);
|
||||
$cart = $this->findCartOrFail($tenant, $identity);
|
||||
$cart->updateItem($cartItemId, $quantity, $variantId, $updateVariant);
|
||||
|
||||
return $this->loadCart($cart, $tenant);
|
||||
}
|
||||
|
||||
public function removeItem(Tenant $tenant, Request $request, int $cartItemId): Cart
|
||||
{
|
||||
if (! $tenant->cart_editing_policy->allowsRemoval()) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_item' => __('api.cart.editing_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
$identity = $this->requireIdentity($request);
|
||||
$cart = $this->findCartOrFail($tenant, $identity);
|
||||
$cart->removeItem($cartItemId);
|
||||
|
||||
return $this->loadCart($cart, $tenant);
|
||||
}
|
||||
|
||||
public function makeGuestTokenCookie(string $guestToken): Cookie
|
||||
{
|
||||
$secure = (bool) config('session.secure');
|
||||
$sameSite = config('session.same_site');
|
||||
$partitioned = (bool) config('session.partitioned')
|
||||
|| ($secure && strtolower((string) $sameSite) === 'none');
|
||||
|
||||
return Cookie::create(
|
||||
name: 'guest_token',
|
||||
value: $guestToken,
|
||||
expire: now()->addDays(180),
|
||||
path: '/',
|
||||
domain: config('session.domain'),
|
||||
secure: $secure,
|
||||
httpOnly: true,
|
||||
raw: false,
|
||||
sameSite: $sameSite,
|
||||
partitioned: $partitioned,
|
||||
);
|
||||
}
|
||||
|
||||
protected function makeEmptyCart(Tenant $tenant): Cart
|
||||
{
|
||||
$cart = new Cart([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'status' => Cart::STATUS_ACTIVE,
|
||||
]);
|
||||
|
||||
$cart->setRelation('items', collect());
|
||||
|
||||
return $cart;
|
||||
}
|
||||
|
||||
protected function loadCart(Cart $cart, Tenant $tenant): Cart
|
||||
{
|
||||
$relations = [
|
||||
'items.catalogItem.attachments',
|
||||
'items.catalogItem.inventory',
|
||||
'items.catalogItem.itemAttributes.attribute',
|
||||
'items.variant.attachments',
|
||||
'items.variant.inventory',
|
||||
'items.variant.definitions.itemAttribute.attribute.options',
|
||||
'items.variant.eventDates',
|
||||
'items.variant.eventDate',
|
||||
];
|
||||
|
||||
if ($tenant->cart_editing_policy->allowsVariantChanges()) {
|
||||
$relations = [
|
||||
...$relations,
|
||||
'items.catalogItem.variants' => fn ($query) => $query->orderBy('id'),
|
||||
'items.catalogItem.variants.inventory',
|
||||
'items.catalogItem.variants.definitions' => fn ($query) => $query->orderBy('id'),
|
||||
'items.catalogItem.variants.definitions.itemAttribute.attribute.options',
|
||||
'items.catalogItem.variants.eventDates',
|
||||
'items.catalogItem.variants.eventDate',
|
||||
];
|
||||
}
|
||||
|
||||
return $cart->fresh()->load($relations);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{identity: array{user_id: ?int, guest_token: ?string}, generated_guest_token: ?string}|null
|
||||
*/
|
||||
protected function resolveIdentity(Request $request, bool $generateGuestToken = false): ?array
|
||||
{
|
||||
$user = $request->user() ?? Auth::guard('sanctum')->user();
|
||||
|
||||
if ($user instanceof User) {
|
||||
return [
|
||||
'identity' => [
|
||||
'user_id' => $user->getKey(),
|
||||
'guest_token' => null,
|
||||
],
|
||||
'generated_guest_token' => null,
|
||||
];
|
||||
}
|
||||
|
||||
$guestToken = $request->cookie('guest_token');
|
||||
|
||||
if (is_string($guestToken) && $guestToken !== '') {
|
||||
return [
|
||||
'identity' => [
|
||||
'user_id' => null,
|
||||
'guest_token' => $guestToken,
|
||||
],
|
||||
'generated_guest_token' => null,
|
||||
];
|
||||
}
|
||||
|
||||
if (! $generateGuestToken) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$generatedGuestToken = (string) Str::uuid();
|
||||
|
||||
return [
|
||||
'identity' => [
|
||||
'user_id' => null,
|
||||
'guest_token' => $generatedGuestToken,
|
||||
],
|
||||
'generated_guest_token' => $generatedGuestToken,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{user_id: ?int, guest_token: ?string}
|
||||
*/
|
||||
protected function requireIdentity(Request $request): array
|
||||
{
|
||||
$resolvedIdentity = $this->resolveIdentity($request);
|
||||
|
||||
if ($resolvedIdentity === null) {
|
||||
throw new NotFoundHttpException('Cart not found.');
|
||||
}
|
||||
|
||||
return $resolvedIdentity['identity'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{user_id: ?int, guest_token: ?string} $identity
|
||||
*/
|
||||
protected function findCart(Tenant $tenant, array $identity): ?Cart
|
||||
{
|
||||
return Cart::query()
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('origin', Cart::ORIGIN_USER)
|
||||
->whereIn('status', [Cart::STATUS_ACTIVE, Cart::STATUS_EXPIRED])
|
||||
->when(
|
||||
$identity['user_id'] !== null,
|
||||
fn ($query) => $query->where('user_id', $identity['user_id']),
|
||||
fn ($query) => $query->where('guest_token', $identity['guest_token']),
|
||||
)
|
||||
->orderByRaw('CASE WHEN status = ? THEN 0 ELSE 1 END', [Cart::STATUS_ACTIVE])
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{user_id: ?int, guest_token: ?string} $identity
|
||||
*/
|
||||
protected function findCartOrFail(Tenant $tenant, array $identity): Cart
|
||||
{
|
||||
$cart = $this->resolveCart($tenant, $identity, replaceExpired: false);
|
||||
|
||||
if ($cart === null) {
|
||||
throw new NotFoundHttpException('Cart not found.');
|
||||
}
|
||||
|
||||
return $cart;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{user_id: ?int, guest_token: ?string} $identity
|
||||
*/
|
||||
protected function findOrCreateCart(Tenant $tenant, array $identity): Cart
|
||||
{
|
||||
return $this->resolveCart($tenant, $identity)
|
||||
?? $this->createCart($tenant, $identity);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{user_id: ?int, guest_token: ?string} $identity
|
||||
*/
|
||||
protected function resolveCart(
|
||||
Tenant $tenant,
|
||||
array $identity,
|
||||
bool $replaceExpired = true,
|
||||
): ?Cart {
|
||||
$cart = $this->findCart($tenant, $identity);
|
||||
|
||||
if ($cart?->status === Cart::STATUS_ACTIVE
|
||||
&& $cart->current_stock_reservation_id !== null
|
||||
&& app(ExpireStockReservationsService::class)
|
||||
->expireIfOverdue($cart->current_stock_reservation_id)) {
|
||||
$cart = $this->findCart($tenant, $identity);
|
||||
}
|
||||
|
||||
if ($cart?->status === Cart::STATUS_EXPIRED) {
|
||||
if (! $replaceExpired) {
|
||||
throw new StockReservationExpiredException;
|
||||
}
|
||||
|
||||
return $this->replaceExpiredCart($cart, $tenant, $identity);
|
||||
}
|
||||
|
||||
if ($cart !== null) {
|
||||
return $cart;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{user_id: ?int, guest_token: ?string} $identity
|
||||
*/
|
||||
protected function replaceExpiredCart(Cart $expiredCart, Tenant $tenant, array $identity): Cart
|
||||
{
|
||||
return DB::transaction(function () use ($expiredCart, $tenant, $identity): Cart {
|
||||
/** @var Cart|null $lockedCart */
|
||||
$lockedCart = Cart::query()->lockForUpdate()->find($expiredCart->getKey());
|
||||
|
||||
if ($lockedCart?->status === Cart::STATUS_EXPIRED) {
|
||||
$lockedCart->update([
|
||||
'status' => Cart::STATUS_ABANDONED,
|
||||
'current_purchase_id' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
return $this->findCart($tenant, $identity)
|
||||
?? $this->createCart($tenant, $identity);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{user_id: ?int, guest_token: ?string} $identity
|
||||
*/
|
||||
protected function createCart(Tenant $tenant, array $identity): Cart
|
||||
{
|
||||
$attributes = [
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'status' => Cart::STATUS_ACTIVE,
|
||||
'origin' => Cart::ORIGIN_USER,
|
||||
];
|
||||
|
||||
if ($identity['user_id'] !== null) {
|
||||
$attributes['user_id'] = $identity['user_id'];
|
||||
} else {
|
||||
$attributes['guest_token'] = $identity['guest_token'];
|
||||
}
|
||||
|
||||
return Cart::query()->firstOrCreate($attributes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Cart\Services;
|
||||
|
||||
use App\Domains\Commerce\Cart\Models\Cart;
|
||||
use App\Domains\Commerce\Cart\Models\CartItem;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use App\Domains\Commerce\Catalog\Services\CatalogInventoryService;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class CartVariantReplacementService
|
||||
{
|
||||
public function __construct(private readonly CatalogInventoryService $inventory) {}
|
||||
|
||||
public function replaceHistoricalVariants(Cart $cart): void
|
||||
{
|
||||
$items = $cart->items()
|
||||
->whereNotNull('variant_id')
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
foreach ($items as $item) {
|
||||
$variant = Variant::query()->lockForUpdate()->find($item->variant_id);
|
||||
|
||||
if ($variant === null) {
|
||||
throw $this->unavailableVariant();
|
||||
}
|
||||
|
||||
$replacement = $this->latestReplacement($variant);
|
||||
|
||||
if ($replacement->is($variant)) {
|
||||
if (! $variant->isSellable()) {
|
||||
throw $this->unavailableVariant();
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $replacement->isSellable()) {
|
||||
throw $this->unavailableVariant();
|
||||
}
|
||||
|
||||
/** @var CartItem|null $targetItem */
|
||||
$targetItem = $cart->items()
|
||||
->whereKeyNot($item->getKey())
|
||||
->where('catalog_item_id', $item->catalog_item_id)
|
||||
->where('variant_id', $replacement->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
$replacementQuantity = $item->cantidad + ($targetItem?->cantidad ?? 0);
|
||||
if ($replacement->inventory_id !== $variant->inventory_id) {
|
||||
$available = $this->inventory->availableQuantity($replacement);
|
||||
|
||||
if ($available !== null && $available < $replacementQuantity) {
|
||||
throw $this->unavailableVariant();
|
||||
}
|
||||
}
|
||||
|
||||
if ($targetItem !== null) {
|
||||
$targetItem->cantidad += $item->cantidad;
|
||||
$targetItem->save();
|
||||
$item->delete();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$item->update(['variant_id' => $replacement->getKey()]);
|
||||
}
|
||||
}
|
||||
|
||||
private function latestReplacement(Variant $variant): Variant
|
||||
{
|
||||
$current = $variant;
|
||||
$visited = [];
|
||||
|
||||
while ($current->replaced_by_variant_id !== null) {
|
||||
if (isset($visited[$current->getKey()])) {
|
||||
throw $this->unavailableVariant();
|
||||
}
|
||||
|
||||
$visited[$current->getKey()] = true;
|
||||
$current = Variant::query()
|
||||
->lockForUpdate()
|
||||
->find($current->replaced_by_variant_id)
|
||||
?? throw $this->unavailableVariant();
|
||||
}
|
||||
|
||||
return $current;
|
||||
}
|
||||
|
||||
private function unavailableVariant(): ValidationException
|
||||
{
|
||||
return ValidationException::withMessages([
|
||||
'cart_id' => [__('api.cart.cart_variant_unavailable')],
|
||||
]);
|
||||
}
|
||||
}
|
||||
53
app/Domains/Commerce/Cart/Services/GuestCartMergeService.php
Normal file
53
app/Domains/Commerce/Cart/Services/GuestCartMergeService.php
Normal file
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Cart\Services;
|
||||
|
||||
use App\Domains\Core\Auth\Models\User;
|
||||
use App\Domains\Commerce\Cart\Models\Cart;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class GuestCartMergeService
|
||||
{
|
||||
public function merge(string $tenantCodigo, User $user, ?string $guestToken): void
|
||||
{
|
||||
if ($guestToken === null || $guestToken === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($tenantCodigo, $user, $guestToken): void {
|
||||
$guestCart = Cart::query()
|
||||
->where('tenant_codigo', $tenantCodigo)
|
||||
->where('guest_token', $guestToken)
|
||||
->where('status', 'active')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($guestCart === null || ! $guestCart->items()->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$userCart = Cart::query()
|
||||
->where('tenant_codigo', $tenantCodigo)
|
||||
->where('user_id', $user->getKey())
|
||||
->where('status', 'active')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($userCart !== null) {
|
||||
$userCart->items()
|
||||
->orderBy('id')
|
||||
->pluck('id')
|
||||
->each(fn (int $itemId) => $userCart->removeItem($itemId));
|
||||
$userCart->update([
|
||||
'status' => 'converted',
|
||||
]);
|
||||
$userCart->delete();
|
||||
}
|
||||
|
||||
$guestCart->update([
|
||||
'user_id' => $user->getKey(),
|
||||
'guest_token' => null,
|
||||
]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Cart\Services;
|
||||
|
||||
use App\Domains\Commerce\Cart\Models\Cart;
|
||||
use App\Domains\Commerce\Catalog\Models\StockReservation;
|
||||
use App\Domains\Commerce\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class InvalidateEventDateCartsService
|
||||
{
|
||||
public function __construct(private readonly StockReservationService $reservations) {}
|
||||
|
||||
/** @param Collection<int, int> $eventDateIds */
|
||||
public function invalidate(
|
||||
Tenant $tenant,
|
||||
Collection $eventDateIds,
|
||||
string $reason = StockReservationService::REASON_EVENT_DATE_RESCHEDULED,
|
||||
): void {
|
||||
DB::transaction(function () use ($tenant, $eventDateIds, $reason): void {
|
||||
$carts = Cart::query()
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('status', Cart::STATUS_ACTIVE)
|
||||
->whereNull('current_purchase_id')
|
||||
->whereHas('currentStockReservation', fn ($reservation) => $reservation
|
||||
->where('status', StockReservation::STATUS_ACTIVE))
|
||||
->whereHas('items.variant', fn ($variant) => $variant
|
||||
->withTrashed()
|
||||
->where(fn ($dates) => $dates
|
||||
->whereIn('event_date_id', $eventDateIds)
|
||||
->orWhereHas('eventDates', fn ($date) => $date
|
||||
->whereIn('event_dates.id', $eventDateIds))))
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
foreach ($carts as $cart) {
|
||||
// Checkout keeps the cart and purchase attached to the same reservation.
|
||||
if (Purchase::query()
|
||||
->where('stock_reservation_id', $cart->current_stock_reservation_id)
|
||||
->exists()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->reservations->releaseCurrentCartReservation(
|
||||
$cart,
|
||||
$reason,
|
||||
);
|
||||
|
||||
// Reuse the existing expired-cart flow: stale mutations receive the
|
||||
// expiration response and the next GET replaces the whole cart.
|
||||
$cart->update(['status' => Cart::STATUS_EXPIRED]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
38
app/Domains/Commerce/Cart/documentacion/README.md
Normal file
38
app/Domains/Commerce/Cart/documentacion/README.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# Dominio Cart
|
||||
|
||||
## Propósito
|
||||
|
||||
Gestiona el carrito activo de un tenant tanto para visitantes como para usuarios autenticados.
|
||||
|
||||
## Modelo
|
||||
|
||||
- `Cart`: pertenece a un tenant y opcionalmente a un usuario; calcula el total, permite agregar, actualizar o quitar ítems y apunta a su reserva de stock vigente mediante `current_stock_reservation_id`.
|
||||
- `CartItem`: referencia un `CatalogItem` y, opcionalmente, una `Variant`; sólo persiste la selección y cantidad, y expone siempre los datos vigentes del catálogo.
|
||||
|
||||
## Servicios
|
||||
|
||||
- `CartService`: obtiene el carrito, modifica ítems y administra la cookie del token invitado.
|
||||
- `GuestCartMergeService`: incorpora el carrito invitado al usuario cuando este se autentica.
|
||||
|
||||
## Endpoints
|
||||
|
||||
Bajo `/tenants/{tenant:codigo}`:
|
||||
|
||||
- `GET /cart`.
|
||||
- `POST /cart/items`.
|
||||
- `PATCH /cart/items/{cartItem}`.
|
||||
- `DELETE /cart/items/{cartItem}`.
|
||||
|
||||
## Contratos
|
||||
|
||||
`AddCartItemRequest` y `UpdateCartItemQuantityRequest` validan selección y cantidad. `CartResource` y `CartItemResource` estabilizan la respuesta pública. Cada ítem expone `nombre`, `imagen` y `precio_unitario` en la raíz, priorizando la variante seleccionada y usando el catálogo base como respaldo. La variante seleccionada se serializa en `variant`; las variantes alternativas no forman parte de la respuesta del carrito.
|
||||
|
||||
## Dependencias y reglas
|
||||
|
||||
Depende de `Catalog` para productos y variantes, de `Tenant` para aislar datos y de `Auth` cuando existe usuario. Toda operación debe comprobar que carrito e ítem pertenecen al tenant actual.
|
||||
|
||||
Un carrito puede pasar a `checkout`. Las compras directas usan un carrito técnico con `origin=direct_checkout`; los carritos normales conservan `origin=user` y pueden restaurarse al cancelar o vencer la compra.
|
||||
|
||||
Cada edición sincroniza una única reserva para el carrito completo. Si varios ítems o bundles consumen el mismo inventario, se persiste una sola línea con la cantidad agregada. Al editar durante checkout, la compra anterior queda `superseded`, se desvincula y el carrito conserva la misma reserva activa con sus líneas actualizadas.
|
||||
|
||||
El comando unificado `php artisan reservations:expire` recorre una sola vez las reservas activas cuyo `expires_at` haya vencido. Cuando pertenecen a un carrito, conserva la reserva y sus líneas como historial, libera el stock como conjunto y cambia el carrito asociado a `expired` sin eliminar sus ítems. Al volver a resolver ese carrito desde la API, el anterior pasa automáticamente a `abandoned` y se crea uno activo y vacío para la misma identidad. El cliente nunca necesita reiniciarlo explícitamente. La API también materializa este vencimiento al acceder al carrito aunque el comando programado todavía no haya corrido.
|
||||
@@ -1,10 +1,9 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Cart\Controllers\CartController;
|
||||
use App\Domains\Commerce\Cart\Controllers\CartController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('tenants/{tenant:codigo}')
|
||||
->middleware(\App\Domains\Cart\Middleware\MergeGuestCartMiddleware::class)
|
||||
->group(function (): void {
|
||||
Route::get('cart', [CartController::class, 'show']);
|
||||
Route::post('cart/items', [CartController::class, 'addItem']);
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Controllers\AdminApp;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Commerce\Catalog\Requests\AdminApp\UpsertOnTicketFeaturedGroupRequest;
|
||||
use App\Domains\Commerce\Catalog\Resources\AdminApp\OnTicketFeaturedGroupResource;
|
||||
use App\Domains\Commerce\Catalog\Services\OnTicketFeaturedGroupService;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
|
||||
class OnTicketFeaturedGroupController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly OnTicketFeaturedGroupService $featuredGroupService,
|
||||
) {}
|
||||
|
||||
public function index(Request $request): AnonymousResourceCollection
|
||||
{
|
||||
return OnTicketFeaturedGroupResource::collection(
|
||||
$this->featuredGroupService->forTenant($this->onTicketTenant($request))
|
||||
);
|
||||
}
|
||||
|
||||
public function store(UpsertOnTicketFeaturedGroupRequest $request): JsonResponse
|
||||
{
|
||||
$featuredGroup = $this->featuredGroupService->create(
|
||||
$this->onTicketTenant($request),
|
||||
$request->validated(),
|
||||
);
|
||||
|
||||
return OnTicketFeaturedGroupResource::make($featuredGroup)
|
||||
->response()
|
||||
->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function update(
|
||||
UpsertOnTicketFeaturedGroupRequest $request,
|
||||
FeaturedGroup $featuredGroup,
|
||||
): OnTicketFeaturedGroupResource {
|
||||
$tenant = $this->onTicketTenant($request);
|
||||
|
||||
abort_unless($featuredGroup->tenant_code === $tenant->codigo, 404);
|
||||
|
||||
return OnTicketFeaturedGroupResource::make(
|
||||
$this->featuredGroupService->update(
|
||||
$tenant,
|
||||
$featuredGroup,
|
||||
$request->validated(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private function onTicketTenant(Request $request): Tenant
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
abort_unless(in_array($tenant->storefront_website_type_code, ['onticket', 'onticket_multi_event'], true), 404);
|
||||
|
||||
return $tenant;
|
||||
}
|
||||
}
|
||||
173
app/Domains/Commerce/Catalog/Controllers/CatalogController.php
Normal file
173
app/Domains/Commerce/Catalog/Controllers/CatalogController.php
Normal file
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Controllers;
|
||||
|
||||
use App\Domains\Commerce\Cart\Services\CartService;
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Commerce\Catalog\Models\Category;
|
||||
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Commerce\Catalog\Requests\CatalogItemDetailRequest;
|
||||
use App\Domains\Commerce\Catalog\Requests\CatalogVariantOptionsRequest;
|
||||
use App\Domains\Commerce\Catalog\Requests\CategoryPageRequest;
|
||||
use App\Domains\Commerce\Catalog\Requests\FeaturedGroupPageRequest;
|
||||
use App\Domains\Commerce\Catalog\Requests\SearchCatalogItemsRequest;
|
||||
use App\Domains\Commerce\Catalog\Resources\CatalogFeaturedGroupResource;
|
||||
use App\Domains\Commerce\Catalog\Resources\CatalogItemDetailResource;
|
||||
use App\Domains\Commerce\Catalog\Resources\CatalogSearchItemResource;
|
||||
use App\Domains\Commerce\Catalog\Resources\CatalogVariantOptionsResource;
|
||||
use App\Domains\Commerce\Catalog\Services\CatalogItemAllowanceService;
|
||||
use App\Domains\Commerce\Catalog\Services\CatalogService;
|
||||
use App\Domains\Commerce\Catalog\Services\FeaturedGroupService;
|
||||
use App\Domains\Commerce\Catalog\Services\VariantSelectionService;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class CatalogController extends Controller
|
||||
{
|
||||
public function index(Request $request, Tenant $tenant, FeaturedGroupService $featuredGroupService): JsonResponse
|
||||
{
|
||||
$featuredGroups = FeaturedGroup::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->orderBy('group_order')
|
||||
->get();
|
||||
|
||||
return response()->json($featuredGroups->map(
|
||||
fn (FeaturedGroup $featuredGroup): array => (new CatalogFeaturedGroupResource(
|
||||
$featuredGroup,
|
||||
$featuredGroupService->itemsResponse($featuredGroup, $tenant, 1, $this->userId($request)),
|
||||
))->resolve()
|
||||
));
|
||||
}
|
||||
|
||||
public function search(
|
||||
SearchCatalogItemsRequest $request,
|
||||
Tenant $tenant,
|
||||
CatalogService $catalogService,
|
||||
CatalogItemAllowanceService $allowances,
|
||||
): AnonymousResourceCollection {
|
||||
$items = $catalogService->search(
|
||||
$tenant,
|
||||
$request->validated('q'),
|
||||
$tenant->search_items_per_page,
|
||||
(int) $request->validated('page', 1),
|
||||
);
|
||||
$allowances->attach($items->getCollection(), $this->userId($request));
|
||||
|
||||
return CatalogSearchItemResource::collection($items);
|
||||
}
|
||||
|
||||
public function category(
|
||||
CategoryPageRequest $request,
|
||||
Tenant $tenant,
|
||||
Category $category,
|
||||
CatalogService $catalogService,
|
||||
CatalogItemAllowanceService $allowances,
|
||||
): AnonymousResourceCollection {
|
||||
abort_unless($category->tenant_code === $tenant->codigo, 404);
|
||||
|
||||
$items = $catalogService->categoryItems(
|
||||
$tenant,
|
||||
$category,
|
||||
$tenant->search_items_per_page,
|
||||
(int) $request->validated('page', 1),
|
||||
);
|
||||
$allowances->attach($items->getCollection(), $this->userId($request));
|
||||
|
||||
return CatalogSearchItemResource::collection($items)->additional([
|
||||
'category' => [
|
||||
'id' => $category->id,
|
||||
'nombre' => $category->nombre,
|
||||
'categoria_id' => $category->categoria_id,
|
||||
],
|
||||
'layout' => $tenant->search_product_layout->value,
|
||||
'group_layout' => $tenant->search_group_layout->value,
|
||||
]);
|
||||
}
|
||||
|
||||
public function featuredGroupItems(
|
||||
FeaturedGroupPageRequest $request,
|
||||
Tenant $tenant,
|
||||
FeaturedGroup $featuredGroup,
|
||||
FeaturedGroupService $featuredGroupService,
|
||||
): JsonResponse {
|
||||
abort_unless($featuredGroup->tenant_code === $tenant->codigo, 404);
|
||||
|
||||
$page = (int) $request->validated('page', 1);
|
||||
|
||||
return response()->json($featuredGroupService->itemsResponse(
|
||||
$featuredGroup,
|
||||
$tenant,
|
||||
$page,
|
||||
$this->userId($request),
|
||||
));
|
||||
}
|
||||
|
||||
public function show(
|
||||
CatalogItemDetailRequest $request,
|
||||
Tenant $tenant,
|
||||
CatalogItem $catalogItem,
|
||||
CatalogService $catalogService,
|
||||
CatalogItemAllowanceService $allowances,
|
||||
): CatalogItemDetailResource {
|
||||
abort_unless($catalogItem->tenant_code === $tenant->codigo
|
||||
&& ($tenant->active_event_id === null || $catalogItem->event_id === $tenant->active_event_id), 404);
|
||||
|
||||
$variantId = $request->validated('variant_id');
|
||||
|
||||
$item = $catalogService->getDetail(
|
||||
$catalogItem,
|
||||
$variantId === null ? null : (int) $variantId,
|
||||
);
|
||||
$allowances->attach(collect([$item]), $this->userId($request));
|
||||
|
||||
return CatalogItemDetailResource::make($item);
|
||||
}
|
||||
|
||||
public function variantOptions(
|
||||
CatalogVariantOptionsRequest $request,
|
||||
Tenant $tenant,
|
||||
CatalogItem $catalogItem,
|
||||
VariantSelectionService $variantSelectionService,
|
||||
CartService $cartService,
|
||||
): CatalogVariantOptionsResource {
|
||||
abort_unless($catalogItem->tenant_code === $tenant->codigo
|
||||
&& ($tenant->active_event_id === null || $catalogItem->event_id === $tenant->active_event_id), 404);
|
||||
|
||||
$includedVariantId = null;
|
||||
$cartItemId = $request->validated('cart_item_id');
|
||||
$selectedValues = $request->validated('selected_values', []);
|
||||
|
||||
if ($cartItemId !== null) {
|
||||
$cartItem = $cartService->show($tenant, $request)
|
||||
->items
|
||||
->firstWhere('id', (int) $cartItemId);
|
||||
abort_unless($cartItem?->catalog_item_id === $catalogItem->id, 404);
|
||||
$includedVariantId = $cartItem->variant_id;
|
||||
|
||||
if ($selectedValues === [] && $cartItem->variant !== null) {
|
||||
$selectedValues = $cartItem->variant
|
||||
->selectorOptions($catalogItem->itemAttributes)
|
||||
->all();
|
||||
}
|
||||
}
|
||||
|
||||
return CatalogVariantOptionsResource::make(
|
||||
$variantSelectionService->options(
|
||||
$catalogItem,
|
||||
$selectedValues,
|
||||
$includedVariantId,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private function userId(Request $request): ?int
|
||||
{
|
||||
$userId = $request->user()?->getAuthIdentifier() ?? Auth::guard('sanctum')->id();
|
||||
|
||||
return $userId === null ? null : (int) $userId;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Enums;
|
||||
namespace App\Domains\Commerce\Catalog\Enums;
|
||||
|
||||
enum CatalogItemType: string
|
||||
{
|
||||
18
app/Domains/Commerce/Catalog/Enums/FeaturedGroupSource.php
Normal file
18
app/Domains/Commerce/Catalog/Enums/FeaturedGroupSource.php
Normal file
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Enums;
|
||||
|
||||
enum FeaturedGroupSource: string
|
||||
{
|
||||
case Manual = 'manual';
|
||||
case Category = 'category';
|
||||
case All = 'all';
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
}
|
||||
20
app/Domains/Commerce/Catalog/Enums/GroupLayout.php
Normal file
20
app/Domains/Commerce/Catalog/Enums/GroupLayout.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Enums;
|
||||
|
||||
enum GroupLayout: string
|
||||
{
|
||||
case Paginated = 'paginated';
|
||||
case Simple = 'simple';
|
||||
case SimpleVertical = 'simple_vertical';
|
||||
case Carousel = 'carousel';
|
||||
case Single = 'single';
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Enums;
|
||||
namespace App\Domains\Commerce\Catalog\Enums;
|
||||
|
||||
enum InventoryPolicy: string
|
||||
{
|
||||
16
app/Domains/Commerce/Catalog/Enums/InventorySubject.php
Normal file
16
app/Domains/Commerce/Catalog/Enums/InventorySubject.php
Normal file
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Enums;
|
||||
|
||||
enum InventorySubject: string
|
||||
{
|
||||
case Product = 'product';
|
||||
case Seat = 'seat';
|
||||
case Ticket = 'ticket';
|
||||
|
||||
/** @return array<int, string> */
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Enums;
|
||||
namespace App\Domains\Commerce\Catalog\Enums;
|
||||
|
||||
enum ProductLayout: string
|
||||
{
|
||||
case Row = 'row';
|
||||
case ColumnWithImage = 'column_with_image';
|
||||
case ColumnWithCart = 'column_with_cart';
|
||||
case TicketSelector = 'ticket_selector';
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Exceptions;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class StockReservationExpiredException extends RuntimeException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct(__('api.cart.reservation_expired'));
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
namespace App\Domains\Commerce\Catalog\Models;
|
||||
|
||||
use App\Domains\Shared\Enums\FieldType;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticketing\Event\Models\EventDate;
|
||||
use App\Shared\Enums\FieldType;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
@@ -51,4 +52,16 @@ class Attribute extends Model
|
||||
{
|
||||
return $this->hasMany(AttributeOption::class, 'attribute_id')->orderBy('sort_order');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<EventDate, $this>
|
||||
*/
|
||||
public function eventDates(): HasMany
|
||||
{
|
||||
return $this->hasMany(EventDate::class, 'tenant_code', 'tenant_codigo')
|
||||
->whereNull('rescheduled_to_event_date_id')
|
||||
->whereNull('suspended_at')
|
||||
->orderBy('date')
|
||||
->orderBy('time_start');
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
namespace App\Domains\Commerce\Catalog\Models;
|
||||
|
||||
use App\Domains\Ticketing\Ticket\Models\ValidityTime;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
@@ -9,6 +10,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'attribute_id',
|
||||
'validity_time_id',
|
||||
'value',
|
||||
'label',
|
||||
'sort_order',
|
||||
@@ -26,6 +28,7 @@ class AttributeOption extends Model
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'validity_time_id' => 'integer',
|
||||
'sort_order' => 'integer',
|
||||
'metadata' => 'array',
|
||||
];
|
||||
@@ -38,4 +41,10 @@ class AttributeOption extends Model
|
||||
{
|
||||
return $this->belongsTo(Attribute::class, 'attribute_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<ValidityTime, $this> */
|
||||
public function validityTime(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ValidityTime::class);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
namespace App\Domains\Commerce\Catalog\Models;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
namespace App\Domains\Commerce\Catalog\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
302
app/Domains/Commerce/Catalog/Models/CatalogItem.php
Normal file
302
app/Domains/Commerce/Catalog/Models/CatalogItem.php
Normal file
@@ -0,0 +1,302 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Models;
|
||||
|
||||
use App\Shared\Attachable\Models\Attachment;
|
||||
use App\Domains\Commerce\Catalog\Enums\CatalogItemType;
|
||||
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Commerce\Catalog\Enums\InventorySubject;
|
||||
use App\Domains\Commerce\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticketing\Event\Models\Event;
|
||||
use App\Domains\Ticketing\Ticket\Models\Ticket;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_code',
|
||||
'category_id',
|
||||
'brand_id',
|
||||
'inventory_id',
|
||||
'type',
|
||||
'slug',
|
||||
'nombre',
|
||||
'group_order',
|
||||
'descripcion',
|
||||
'precio',
|
||||
'sales_end_at',
|
||||
'inventory_policy',
|
||||
'inventory_subject',
|
||||
'max_units_per_user',
|
||||
'has_tickets',
|
||||
])]
|
||||
class CatalogItem extends Model
|
||||
{
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $table = 'catalog_items';
|
||||
|
||||
protected $attributes = [
|
||||
'type' => CatalogItemType::Standard->value,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'inventory_subject' => InventorySubject::Product->value,
|
||||
'has_tickets' => false,
|
||||
'group_order' => 0,
|
||||
];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (CatalogItem $item): void {
|
||||
if ($item->event_id !== null || $item->tenant_code === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$item->event_id = Tenant::query()
|
||||
->where('codigo', $item->tenant_code)
|
||||
->value('active_event_id');
|
||||
});
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'event_id' => 'integer',
|
||||
'category_id' => 'integer',
|
||||
'brand_id' => 'integer',
|
||||
'inventory_id' => 'integer',
|
||||
'type' => CatalogItemType::class,
|
||||
'group_order' => 'integer',
|
||||
'precio' => 'decimal:2',
|
||||
'sales_end_at' => 'datetime',
|
||||
'inventory_policy' => InventoryPolicy::class,
|
||||
'inventory_subject' => InventorySubject::class,
|
||||
'max_units_per_user' => 'integer',
|
||||
'has_tickets' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Tenant, $this> */
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Event, $this> */
|
||||
public function event(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Event::class);
|
||||
}
|
||||
|
||||
/** @param Builder<CatalogItem> $query */
|
||||
public function scopeForTenantCatalog(Builder $query, Tenant $tenant): Builder
|
||||
{
|
||||
return $query
|
||||
->where('catalog_items.tenant_code', $tenant->codigo)
|
||||
->when($tenant->active_event_id !== null, fn (Builder $query): Builder => $query
|
||||
->where('catalog_items.event_id', $tenant->active_event_id));
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Category, $this> */
|
||||
public function category(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Category::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Brand, $this> */
|
||||
public function brand(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Brand::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Inventory, $this> */
|
||||
public function inventory(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Inventory::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<BundleComponent, $this> */
|
||||
public function bundleComponents(): HasMany
|
||||
{
|
||||
return $this->hasMany(BundleComponent::class, 'bundle_catalog_item_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<BundleComponent, $this> */
|
||||
public function bundleComponentUsages(): HasMany
|
||||
{
|
||||
return $this->hasMany(BundleComponent::class, 'component_catalog_item_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<Variant, $this> */
|
||||
public function variants(): HasMany
|
||||
{
|
||||
return $this->hasMany(Variant::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<Ticket, $this> */
|
||||
public function sourceTickets(): HasMany
|
||||
{
|
||||
return $this->hasMany(Ticket::class, 'source_catalog_item_id');
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attribute, $this> */
|
||||
public function attributes(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Attribute::class, 'item_attributes')
|
||||
->withTimestamps();
|
||||
}
|
||||
|
||||
/** @return HasMany<ItemAttribute, $this> */
|
||||
public function itemAttributes(): HasMany
|
||||
{
|
||||
return $this->hasMany(ItemAttribute::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<FeaturedItem, $this> */
|
||||
public function featuredItems(): HasMany
|
||||
{
|
||||
return $this->hasMany(FeaturedItem::class);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function attachments(): BelongsToMany
|
||||
{
|
||||
return $this->allAttachments()->wherePivot('is_enabled', true);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function allAttachments(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
Attachment::class,
|
||||
'catalog_items_attachments',
|
||||
'catalog_item_id',
|
||||
'attachment_id'
|
||||
)
|
||||
->withPivot(['orden', 'is_enabled'])
|
||||
->wherePivotNull('variant_id')
|
||||
->orderByPivot('orden');
|
||||
}
|
||||
|
||||
public function availableStock(): ?int
|
||||
{
|
||||
return app(CatalogInventoryService::class)->availableQuantity($this);
|
||||
}
|
||||
|
||||
public function isAvailable(): bool
|
||||
{
|
||||
if (! $this->isSaleOpen()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->type === CatalogItemType::Bundle) {
|
||||
$availableStock = $this->availableStock();
|
||||
|
||||
return $availableStock === null || $availableStock > 0;
|
||||
}
|
||||
|
||||
if ($this->inventory_policy === InventoryPolicy::Unlimited) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return ($this->availableStock() ?? 0) > 0;
|
||||
}
|
||||
|
||||
/** @param Builder<CatalogItem> $query */
|
||||
public function scopeWhereAvailable(Builder $query): Builder
|
||||
{
|
||||
return $query->where(function (Builder $query): void {
|
||||
$query->whereNull('catalog_items.sales_end_at')
|
||||
->orWhere('catalog_items.sales_end_at', '>', now());
|
||||
})->where(function (Builder $query): void {
|
||||
$query
|
||||
->where(function (Builder $unlimitedQuery): void {
|
||||
$unlimitedQuery
|
||||
->where('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value)
|
||||
->where(function (Builder $selectionQuery): void {
|
||||
$selectionQuery
|
||||
->whereDoesntHave('variants')
|
||||
->orWhereHas('variants', fn (Builder $variantQuery): Builder => $variantQuery
|
||||
->whereNull('sales_disabled_at')
|
||||
->whereNull('replaced_by_variant_id'));
|
||||
});
|
||||
})
|
||||
->orWhereHas(
|
||||
'variants',
|
||||
fn (Builder $variantQuery): Builder => $variantQuery
|
||||
->whereNull('sales_disabled_at')
|
||||
->whereNull('replaced_by_variant_id')
|
||||
->whereHas(
|
||||
'inventory',
|
||||
fn (Builder $inventoryQuery): Builder => $inventoryQuery
|
||||
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
|
||||
)
|
||||
)
|
||||
->orWhere(function (Builder $directItemQuery): void {
|
||||
$directItemQuery
|
||||
->whereDoesntHave('variants')
|
||||
->where(function (Builder $inventoryQuery): void {
|
||||
$inventoryQuery
|
||||
->whereNull('catalog_items.inventory_id')
|
||||
->orWhereHas(
|
||||
'inventory',
|
||||
fn (Builder $availableInventoryQuery): Builder => $availableInventoryQuery
|
||||
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public function isSaleOpen(): bool
|
||||
{
|
||||
return $this->sales_end_at === null || now()->lt($this->sales_end_at);
|
||||
}
|
||||
|
||||
/** @return Collection<int, Variant> */
|
||||
public function visibleVariants(?int $includedVariantId = null): Collection
|
||||
{
|
||||
return $this->variants
|
||||
->each(fn (Variant $variant) => $variant->setRelation('catalogItem', $this))
|
||||
->filter(fn (Variant $variant): bool => $variant->hasOnlyActiveEventDates()
|
||||
&& (($includedVariantId !== null && $variant->id === $includedVariantId)
|
||||
|| ($variant->isSellable() && (
|
||||
$this->inventory_policy === InventoryPolicy::Unlimited
|
||||
|| ($variant->inventory?->availableStock() ?? 0) > 0
|
||||
))))
|
||||
->values();
|
||||
}
|
||||
|
||||
public function getPrice(): float
|
||||
{
|
||||
return (float) $this->precio;
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return $this->nombre;
|
||||
}
|
||||
|
||||
public function getSelectionLabel(): string
|
||||
{
|
||||
return $this->getName();
|
||||
}
|
||||
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->descripcion;
|
||||
}
|
||||
|
||||
public function isBundle(): bool
|
||||
{
|
||||
return $this->type === CatalogItemType::Bundle;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
namespace App\Domains\Commerce\Catalog\Models;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Core\Auth\Models\User;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_code',
|
||||
'categoria_id',
|
||||
'nombre',
|
||||
'is_enabled',
|
||||
])]
|
||||
class Category extends Model
|
||||
{
|
||||
@@ -20,6 +23,10 @@ class Category extends Model
|
||||
|
||||
protected $table = 'categorias';
|
||||
|
||||
protected $attributes = [
|
||||
'is_enabled' => true,
|
||||
];
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
@@ -27,6 +34,7 @@ class Category extends Model
|
||||
{
|
||||
return [
|
||||
'categoria_id' => 'integer',
|
||||
'is_enabled' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -64,4 +72,15 @@ class Category extends Model
|
||||
{
|
||||
return $this->hasMany(CatalogItem::class);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<User, $this> */
|
||||
public function scanners(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
User::class,
|
||||
'category_scanners',
|
||||
'categoria_id',
|
||||
'user_id',
|
||||
)->withTimestamps();
|
||||
}
|
||||
}
|
||||
89
app/Domains/Commerce/Catalog/Models/FeaturedGroup.php
Normal file
89
app/Domains/Commerce/Catalog/Models/FeaturedGroup.php
Normal file
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Models;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Enums\FeaturedGroupSource;
|
||||
use App\Domains\Commerce\Catalog\Enums\GroupLayout;
|
||||
use App\Domains\Commerce\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_code',
|
||||
'code',
|
||||
'source_type',
|
||||
'category_id',
|
||||
'product_layout',
|
||||
'group_layout',
|
||||
'group_name',
|
||||
'group_order',
|
||||
])]
|
||||
class FeaturedGroup extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $table = 'featured_groups';
|
||||
|
||||
protected $attributes = [
|
||||
'source_type' => FeaturedGroupSource::Manual->value,
|
||||
];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (FeaturedGroup $featuredGroup): void {
|
||||
if (filled($featuredGroup->code)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$baseCode = Str::slug($featuredGroup->group_name) ?: 'group';
|
||||
$code = $baseCode;
|
||||
$suffix = 2;
|
||||
|
||||
while (static::query()
|
||||
->where('tenant_code', $featuredGroup->tenant_code)
|
||||
->where('code', $code)
|
||||
->exists()) {
|
||||
$code = "{$baseCode}-{$suffix}";
|
||||
$suffix++;
|
||||
}
|
||||
|
||||
$featuredGroup->code = $code;
|
||||
});
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'source_type' => FeaturedGroupSource::class,
|
||||
'category_id' => 'integer',
|
||||
'product_layout' => ProductLayout::class,
|
||||
'group_layout' => GroupLayout::class,
|
||||
'group_order' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Tenant, $this> */
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Category, $this> */
|
||||
public function category(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Category::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<FeaturedItem, $this> */
|
||||
public function featuredItems(): HasMany
|
||||
{
|
||||
return $this->hasMany(FeaturedItem::class)->orderBy('order');
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
namespace App\Domains\Commerce\Catalog\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -1,14 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
namespace App\Domains\Commerce\Catalog\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
|
||||
#[Fillable([
|
||||
'sold_units',
|
||||
'refunded_units',
|
||||
'reserved_stock',
|
||||
'real_stock',
|
||||
])]
|
||||
@@ -22,6 +24,7 @@ class Inventory extends Model
|
||||
|
||||
protected $attributes = [
|
||||
'sold_units' => 0,
|
||||
'refunded_units' => 0,
|
||||
'reserved_stock' => 0,
|
||||
'real_stock' => 0,
|
||||
];
|
||||
@@ -30,6 +33,7 @@ class Inventory extends Model
|
||||
{
|
||||
return [
|
||||
'sold_units' => 'integer',
|
||||
'refunded_units' => 'integer',
|
||||
'reserved_stock' => 'integer',
|
||||
'real_stock' => 'integer',
|
||||
];
|
||||
@@ -41,10 +45,16 @@ class Inventory extends Model
|
||||
return $this->hasOne(CatalogItem::class);
|
||||
}
|
||||
|
||||
/** @return HasOne<Variant, $this> */
|
||||
public function variant(): HasOne
|
||||
/** @return HasMany<Variant, $this> */
|
||||
public function variants(): HasMany
|
||||
{
|
||||
return $this->hasOne(Variant::class);
|
||||
return $this->hasMany(Variant::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<StockReservationLine, $this> */
|
||||
public function stockReservationLines(): HasMany
|
||||
{
|
||||
return $this->hasMany(StockReservationLine::class);
|
||||
}
|
||||
|
||||
public function availableStock(): int
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
namespace App\Domains\Commerce\Catalog\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -11,6 +11,10 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
#[Fillable([
|
||||
'catalog_item_id',
|
||||
'attribute_id',
|
||||
'allow_multi_select',
|
||||
'sort_order',
|
||||
'show_in_selector',
|
||||
'ticket_label',
|
||||
])]
|
||||
class ItemAttribute extends Model
|
||||
{
|
||||
@@ -18,6 +22,21 @@ class ItemAttribute extends Model
|
||||
|
||||
protected $table = 'item_attributes';
|
||||
|
||||
protected $attributes = [
|
||||
'show_in_selector' => true,
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'catalog_item_id' => 'integer',
|
||||
'attribute_id' => 'integer',
|
||||
'allow_multi_select' => 'boolean',
|
||||
'sort_order' => 'integer',
|
||||
'show_in_selector' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<CatalogItem, $this> */
|
||||
public function catalogItem(): BelongsTo
|
||||
{
|
||||
57
app/Domains/Commerce/Catalog/Models/StockReservation.php
Normal file
57
app/Domains/Commerce/Catalog/Models/StockReservation.php
Normal file
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Models;
|
||||
|
||||
use App\Domains\Commerce\Cart\Models\Cart;
|
||||
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
|
||||
#[Fillable([
|
||||
'status',
|
||||
'expires_at',
|
||||
'committed_at',
|
||||
'released_at',
|
||||
'expired_at',
|
||||
'release_reason',
|
||||
])]
|
||||
class StockReservation extends Model
|
||||
{
|
||||
public const STATUS_ACTIVE = 'active';
|
||||
|
||||
public const STATUS_COMMITTED = 'committed';
|
||||
|
||||
public const STATUS_RELEASED = 'released';
|
||||
|
||||
public const STATUS_EXPIRED = 'expired';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'expires_at' => 'datetime',
|
||||
'committed_at' => 'datetime',
|
||||
'released_at' => 'datetime',
|
||||
'expired_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return HasMany<StockReservationLine, $this> */
|
||||
public function lines(): HasMany
|
||||
{
|
||||
return $this->hasMany(StockReservationLine::class);
|
||||
}
|
||||
|
||||
/** @return HasOne<Cart, $this> */
|
||||
public function currentCart(): HasOne
|
||||
{
|
||||
return $this->hasOne(Cart::class, 'current_stock_reservation_id');
|
||||
}
|
||||
|
||||
/** @return HasOne<Purchase, $this> */
|
||||
public function purchase(): HasOne
|
||||
{
|
||||
return $this->hasOne(Purchase::class);
|
||||
}
|
||||
}
|
||||
38
app/Domains/Commerce/Catalog/Models/StockReservationLine.php
Normal file
38
app/Domains/Commerce/Catalog/Models/StockReservationLine.php
Normal file
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'stock_reservation_id',
|
||||
'inventory_id',
|
||||
'quantity',
|
||||
'tracks_inventory',
|
||||
])]
|
||||
class StockReservationLine extends Model
|
||||
{
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'stock_reservation_id' => 'integer',
|
||||
'inventory_id' => 'integer',
|
||||
'quantity' => 'integer',
|
||||
'tracks_inventory' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<StockReservation, $this> */
|
||||
public function reservation(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(StockReservation::class, 'stock_reservation_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Inventory, $this> */
|
||||
public function inventory(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Inventory::class);
|
||||
}
|
||||
}
|
||||
346
app/Domains/Commerce/Catalog/Models/Variant.php
Normal file
346
app/Domains/Commerce/Catalog/Models/Variant.php
Normal file
@@ -0,0 +1,346 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Models;
|
||||
|
||||
use App\Shared\Attachable\Models\Attachment;
|
||||
use App\Domains\Ticketing\Event\Models\EventDate;
|
||||
use App\Domains\Ticketing\Ticket\Models\Ticket;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Lang;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
#[Fillable([
|
||||
'catalog_item_id',
|
||||
'event_date_id',
|
||||
'inventory_id',
|
||||
'replaced_by_variant_id',
|
||||
'sales_disabled_at',
|
||||
'descripcion',
|
||||
'precio',
|
||||
])]
|
||||
class Variant extends Model
|
||||
{
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $table = 'variantes';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'catalog_item_id' => 'integer',
|
||||
'event_date_id' => 'integer',
|
||||
'inventory_id' => 'integer',
|
||||
'replaced_by_variant_id' => 'integer',
|
||||
'sales_disabled_at' => 'datetime',
|
||||
'precio' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<CatalogItem, $this> */
|
||||
public function catalogItem(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CatalogItem::class)->withTrashed();
|
||||
}
|
||||
|
||||
/** @return BelongsTo<EventDate, $this> */
|
||||
public function eventDate(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(EventDate::class);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<EventDate, $this> */
|
||||
public function eventDates(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
EventDate::class,
|
||||
'variant_event_dates',
|
||||
'variant_id',
|
||||
'event_date_id',
|
||||
)->orderBy('date')->orderBy('time_start');
|
||||
}
|
||||
|
||||
/** @return HasMany<Ticket, $this> */
|
||||
public function sourceTickets(): HasMany
|
||||
{
|
||||
return $this->hasMany(Ticket::class, 'source_variant_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Inventory, $this> */
|
||||
public function inventory(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Inventory::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Variant, $this> */
|
||||
public function replacement(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(self::class, 'replaced_by_variant_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<Variant, $this> */
|
||||
public function replacedVariants(): HasMany
|
||||
{
|
||||
return $this->hasMany(self::class, 'replaced_by_variant_id');
|
||||
}
|
||||
|
||||
public function isSellable(): bool
|
||||
{
|
||||
return $this->sales_disabled_at === null
|
||||
&& $this->replaced_by_variant_id === null
|
||||
&& $this->catalogItem->isSaleOpen()
|
||||
&& $this->hasOnlyActiveEventDates();
|
||||
}
|
||||
|
||||
public function hasOnlyActiveEventDates(): bool
|
||||
{
|
||||
if (! $this->exists
|
||||
&& $this->event_date_id === null
|
||||
&& ! $this->relationLoaded('eventDates')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->selectedEventDates()->every(
|
||||
fn (EventDate $eventDate): bool => $eventDate->rescheduled_to_event_date_id === null
|
||||
&& $eventDate->suspended_at === null,
|
||||
);
|
||||
}
|
||||
|
||||
/** @return HasMany<VariantDefinition, $this> */
|
||||
public function definitions(): HasMany
|
||||
{
|
||||
return $this->hasMany(VariantDefinition::class);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function attachments(): BelongsToMany
|
||||
{
|
||||
return $this->allAttachments()->wherePivot('is_enabled', true);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function allAttachments(): BelongsToMany
|
||||
{
|
||||
$relation = $this->belongsToMany(
|
||||
Attachment::class,
|
||||
'catalog_items_attachments',
|
||||
'variant_id',
|
||||
'attachment_id'
|
||||
)
|
||||
->withPivot(['orden', 'is_enabled'])
|
||||
->orderByPivot('orden');
|
||||
|
||||
if ($this->catalog_item_id !== null) {
|
||||
$relation->withPivotValue('catalog_item_id', $this->catalog_item_id);
|
||||
}
|
||||
|
||||
return $relation;
|
||||
}
|
||||
|
||||
public function getPrice(): float
|
||||
{
|
||||
return (float) ($this->precio ?? $this->catalogItem->precio);
|
||||
}
|
||||
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->descripcion ?? $this->catalogItem->descripcion;
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return $this->catalogItem->nombre;
|
||||
}
|
||||
|
||||
public function getSelectionLabel(): string
|
||||
{
|
||||
$this->loadMissing([
|
||||
'catalogItem.itemAttributes.attribute.options',
|
||||
'definitions.itemAttribute.attribute.options',
|
||||
'eventDates',
|
||||
'eventDate',
|
||||
]);
|
||||
|
||||
$itemAttributes = $this->catalogItem->itemAttributes;
|
||||
|
||||
$label = $this->selectionOptions($itemAttributes)
|
||||
->map(function (array $option, string $attributeCode) use ($itemAttributes): ?string {
|
||||
$itemAttribute = $itemAttributes->first(
|
||||
fn (ItemAttribute $candidate): bool => $candidate->attribute?->codigo === $attributeCode,
|
||||
);
|
||||
$translationKey = "api.catalog.attribute_labels.{$attributeCode}";
|
||||
$attributeName = Lang::has($translationKey)
|
||||
? __($translationKey)
|
||||
: ($itemAttribute?->attribute?->nombre ?? Str::headline($attributeCode));
|
||||
$selectedOptions = array_is_list($option) ? $option : [$option];
|
||||
$selectedLabels = collect($selectedOptions)
|
||||
->pluck('label')
|
||||
->filter()
|
||||
->implode(', ');
|
||||
|
||||
return $selectedLabels === ''
|
||||
? null
|
||||
: "{$attributeName} {$selectedLabels}";
|
||||
})
|
||||
->filter()
|
||||
->implode(' · ');
|
||||
|
||||
return $label !== '' ? $label : $this->getName();
|
||||
}
|
||||
|
||||
/** @return Collection<string, string|array<int, string>> */
|
||||
public function selectionValues(): Collection
|
||||
{
|
||||
$values = $this->definitions
|
||||
->groupBy('item_attribute_id')
|
||||
->mapWithKeys(function (Collection $definitions): array {
|
||||
$itemAttribute = $definitions->first()?->itemAttribute;
|
||||
$attributeCode = $itemAttribute?->attribute?->codigo;
|
||||
|
||||
if ($attributeCode === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$definitionValues = $definitions->pluck('value')->values();
|
||||
|
||||
return [
|
||||
$attributeCode => $itemAttribute->allow_multi_select
|
||||
? $definitionValues->all()
|
||||
: $definitionValues->first(),
|
||||
];
|
||||
});
|
||||
|
||||
$eventDateIds = $this->selectedEventDates()
|
||||
->pluck('id')
|
||||
->map(fn ($id): string => (string) $id)
|
||||
->values();
|
||||
|
||||
if ($eventDateIds->count() === 1) {
|
||||
$values->put('event_date', $eventDateIds->first());
|
||||
} elseif ($eventDateIds->isNotEmpty()) {
|
||||
$values->put('event_date', $eventDateIds->all());
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<string, array{value: string, label: string}|array<int, array{value: string, label: string}>>
|
||||
*/
|
||||
public function selectionOptions(?Collection $itemAttributes = null): Collection
|
||||
{
|
||||
$options = $this->definitions
|
||||
->groupBy('item_attribute_id')
|
||||
->mapWithKeys(function (Collection $definitions): array {
|
||||
$itemAttribute = $definitions->first()?->itemAttribute;
|
||||
$attribute = $itemAttribute?->attribute;
|
||||
$attributeCode = $attribute?->codigo;
|
||||
|
||||
if ($attributeCode === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$values = $definitions
|
||||
->pluck('value')
|
||||
->values()
|
||||
->map(function (string $value) use ($attribute): array {
|
||||
$attributeOption = $attribute->options->firstWhere('value', $value);
|
||||
|
||||
return [
|
||||
'value' => $value,
|
||||
'label' => $attributeOption?->label ?? $value,
|
||||
];
|
||||
});
|
||||
|
||||
return [
|
||||
$attributeCode => $itemAttribute->allow_multi_select
|
||||
? $values->all()
|
||||
: $values->first(),
|
||||
];
|
||||
});
|
||||
|
||||
$eventDateOptions = $this->selectedEventDates()
|
||||
->map(fn (EventDate $eventDate): array => [
|
||||
'value' => (string) $eventDate->id,
|
||||
'label' => $eventDate->date->format('d/m/Y'),
|
||||
])
|
||||
->values();
|
||||
|
||||
if ($eventDateOptions->count() === 1) {
|
||||
$options->put('event_date', $eventDateOptions->first());
|
||||
} elseif ($eventDateOptions->isNotEmpty()) {
|
||||
$options->put('event_date', $eventDateOptions->all());
|
||||
}
|
||||
|
||||
if ($itemAttributes === null) {
|
||||
$itemAttributes = $this->definitions
|
||||
->map(fn (VariantDefinition $definition) => $definition->itemAttribute)
|
||||
->filter()
|
||||
->unique('id')
|
||||
->values();
|
||||
|
||||
if ($this->catalogItem !== null) {
|
||||
$itemAttributes = $itemAttributes
|
||||
->merge($this->catalogItem->itemAttributes)
|
||||
->unique('id')
|
||||
->values();
|
||||
}
|
||||
}
|
||||
|
||||
$ordering = $itemAttributes->mapWithKeys(function (ItemAttribute $itemAttribute): array {
|
||||
$attribute = $itemAttribute->attribute;
|
||||
|
||||
return $attribute === null
|
||||
? []
|
||||
: [$attribute->codigo => [$itemAttribute->sort_order, mb_strtolower($attribute->nombre)]];
|
||||
});
|
||||
|
||||
return $options->sortKeysUsing(function (string $left, string $right) use ($ordering): int {
|
||||
[$leftOrder, $leftLabel] = $ordering->get($left, [0, mb_strtolower($left)]);
|
||||
[$rightOrder, $rightLabel] = $ordering->get($right, [0, mb_strtolower($right)]);
|
||||
|
||||
return $leftOrder <=> $rightOrder
|
||||
?: $leftLabel <=> $rightLabel
|
||||
?: $left <=> $right;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, ItemAttribute> $itemAttributes
|
||||
* @return Collection<string, array{value: string, label: string}|array<int, array{value: string, label: string}>>
|
||||
*/
|
||||
public function selectorOptions(Collection $itemAttributes): Collection
|
||||
{
|
||||
$visibleAttributeCodes = $itemAttributes
|
||||
->filter(fn (ItemAttribute $itemAttribute): bool => $itemAttribute->show_in_selector)
|
||||
->map(fn (ItemAttribute $itemAttribute): ?string => $itemAttribute->attribute?->codigo)
|
||||
->filter()
|
||||
->values();
|
||||
|
||||
return $this->selectionOptions($itemAttributes)
|
||||
->filter(
|
||||
fn (array $option, string $attributeCode): bool => $visibleAttributeCodes
|
||||
->contains($attributeCode)
|
||||
);
|
||||
}
|
||||
|
||||
/** @return Collection<int, EventDate> */
|
||||
public function selectedEventDates(): Collection
|
||||
{
|
||||
$eventDates = $this->eventDates;
|
||||
|
||||
if ($eventDates->isEmpty() && $this->event_date_id !== null && $this->eventDate !== null) {
|
||||
return collect([$this->eventDate]);
|
||||
}
|
||||
|
||||
return $eventDates;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
namespace App\Domains\Commerce\Catalog\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Requests\AdminApp;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpsertOnTicketFeaturedGroupRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'category_name' => ['required', 'string', 'max:255'],
|
||||
'is_featured' => ['required', 'boolean'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Requests;
|
||||
namespace App\Domains\Commerce\Catalog\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class CatalogVariantOptionsRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<string>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'selected_values' => ['sometimes', 'array'],
|
||||
'selected_values.*' => ['nullable'],
|
||||
'cart_item_id' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class CategoryPageRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<string>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'page' => ['sometimes', 'integer', 'min:1'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Requests;
|
||||
namespace App\Domains\Commerce\Catalog\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class SearchCatalogItemsRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<string>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'q' => ['required', 'string', 'min:2', 'max:100'],
|
||||
'page' => ['sometimes', 'integer', 'min:1'],
|
||||
];
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
if ($this->has('q') && is_string($this->input('q'))) {
|
||||
$this->merge(['q' => trim($this->string('q')->toString())]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin FeaturedGroup */
|
||||
class OnTicketFeaturedGroupResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'code' => $this->code,
|
||||
'category_id' => $this->category_id,
|
||||
'category_name' => $this->category->nombre,
|
||||
'group_name' => $this->group_name,
|
||||
'is_featured' => $this->product_layout === ProductLayout::Row,
|
||||
'type' => $this->source_type->value,
|
||||
'product_layout' => $this->product_layout->value,
|
||||
'group_layout' => $this->group_layout->value,
|
||||
'order' => $this->group_order,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Resources;
|
||||
namespace App\Domains\Commerce\Catalog\Resources;
|
||||
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin FeaturedGroup */
|
||||
class CatalogFeaturedGroupResource extends JsonResource
|
||||
{
|
||||
/** @param array<string, mixed> $itemsPage */
|
||||
public function __construct($resource, private readonly array $itemsPage)
|
||||
/** @param array<array-key, mixed> $items */
|
||||
public function __construct($resource, private readonly array $items)
|
||||
{
|
||||
parent::__construct($resource);
|
||||
}
|
||||
@@ -20,10 +20,12 @@ class CatalogFeaturedGroupResource extends JsonResource
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'code' => $this->code,
|
||||
'title' => $this->group_name,
|
||||
'layout' => $this->product_layout->value,
|
||||
'group_layout' => $this->group_layout->value,
|
||||
'group_order' => $this->group_order,
|
||||
'items' => $this->itemsPage,
|
||||
'items' => $this->items,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Resources;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Commerce\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use App\Domains\Commerce\Catalog\Services\CatalogItemAllowanceService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin CatalogItem */
|
||||
class CatalogFeaturedItemResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$catalogItem = $this->resource;
|
||||
/** @var FeaturedGroup $featuredGroup */
|
||||
$featuredGroup = $catalogItem->getRelation('featuredGroup');
|
||||
|
||||
if ($featuredGroup->product_layout === ProductLayout::ColumnWithImage) {
|
||||
return $this->columnWithImageData($catalogItem);
|
||||
}
|
||||
|
||||
if ($featuredGroup->product_layout === ProductLayout::TicketSelector) {
|
||||
return $this->ticketSelectorData($catalogItem);
|
||||
}
|
||||
|
||||
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
|
||||
$availableStock = $catalogItem->availableStock();
|
||||
|
||||
$data = [
|
||||
'id' => $catalogItem->id,
|
||||
'type' => $catalogItem->type->value,
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'descripcion' => $catalogItem->descripcion,
|
||||
'precio' => $catalogItem->precio,
|
||||
'maximum_addable_quantity' => $this->maximumAddable(
|
||||
$availableStock,
|
||||
$remainingUserQuota,
|
||||
),
|
||||
'unavailable_message' => $this->unavailableMessage(
|
||||
$availableStock,
|
||||
$remainingUserQuota,
|
||||
),
|
||||
'variants' => $catalogItem->visibleVariants()
|
||||
->map(function (Variant $variant) use ($catalogItem, $remainingUserQuota): array {
|
||||
$variantStock = $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock();
|
||||
|
||||
return [
|
||||
'id' => $variant->id,
|
||||
'event_date_id' => $variant->event_date_id,
|
||||
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
|
||||
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'maximum_addable_quantity' => $this->maximumAddable(
|
||||
$variantStock,
|
||||
$remainingUserQuota,
|
||||
),
|
||||
'unavailable_message' => $this->unavailableMessage(
|
||||
$variantStock,
|
||||
$remainingUserQuota,
|
||||
),
|
||||
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
||||
];
|
||||
})
|
||||
->values(),
|
||||
];
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function ticketSelectorData(CatalogItem $catalogItem): array
|
||||
{
|
||||
$availableStock = $catalogItem->availableStock();
|
||||
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
|
||||
|
||||
return [
|
||||
'id' => $catalogItem->id,
|
||||
'type' => $catalogItem->type->value,
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'descripcion' => $catalogItem->descripcion,
|
||||
'precio' => $catalogItem->precio,
|
||||
'image' => $this->firstImageUrl($catalogItem),
|
||||
'maximum_addable_quantity' => $this->maximumAddable($availableStock, $remainingUserQuota),
|
||||
'unavailable_message' => $this->unavailableMessage($availableStock, $remainingUserQuota),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function columnWithImageData(CatalogItem $catalogItem): array
|
||||
{
|
||||
$availableStock = $catalogItem->availableStock();
|
||||
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
|
||||
|
||||
return [
|
||||
'id' => $catalogItem->id,
|
||||
'type' => $catalogItem->type->value,
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'precio' => $catalogItem->precio,
|
||||
'image' => $this->firstImageUrl($catalogItem),
|
||||
'maximum_addable_quantity' => $this->maximumAddable($availableStock, $remainingUserQuota),
|
||||
'unavailable_message' => $this->unavailableMessage($availableStock, $remainingUserQuota),
|
||||
];
|
||||
}
|
||||
|
||||
private function firstImageUrl(CatalogItem $catalogItem): ?string
|
||||
{
|
||||
$attachment = $catalogItem->attachments->first()
|
||||
?? $catalogItem->visibleVariants()
|
||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||
->first();
|
||||
|
||||
return $attachment?->getTemporaryUrl(1440);
|
||||
}
|
||||
|
||||
private function maximumAddable(?int $stock, ?int $remainingUserQuota): ?int
|
||||
{
|
||||
return app(CatalogItemAllowanceService::class)
|
||||
->maximumAddableQuantity($stock, $remainingUserQuota);
|
||||
}
|
||||
|
||||
private function unavailableMessage(?int $stock, ?int $remainingUserQuota): ?string
|
||||
{
|
||||
return app(CatalogItemAllowanceService::class)
|
||||
->unavailableMessage($stock, $remainingUserQuota);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Resources;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Commerce\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use App\Domains\Commerce\Catalog\Services\CatalogItemAllowanceService;
|
||||
use App\Domains\Ticketing\Ticket\Resources\ValidityTimeResource;
|
||||
use App\Shared\Enums\FieldType;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/** @mixin CatalogItem */
|
||||
class CatalogItemDetailResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
/** @var Variant|null $selectedVariant */
|
||||
$selectedVariant = $this->resource->getRelation('selectedVariant');
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'type' => $this->type->value,
|
||||
'category_id' => $this->category_id,
|
||||
'brand_id' => $this->brand_id,
|
||||
'slug' => $this->slug,
|
||||
'nombre' => $this->nombre,
|
||||
'descripcion' => $this->descripcion,
|
||||
'precio' => $this->precio,
|
||||
'category' => $this->category?->nombre,
|
||||
'brand' => $this->brand?->nombre,
|
||||
'inventory_policy' => $this->inventory_policy?->value,
|
||||
'inventory_subject' => $this->inventory_subject->value,
|
||||
'max_units_per_user' => $this->max_units_per_user,
|
||||
'has_tickets' => $this->has_tickets,
|
||||
'attributes' => $this->attributesData(),
|
||||
'maximum_addable_quantity' => $this->when(
|
||||
$selectedVariant === null,
|
||||
fn () => $this->maximumAddable($this->availableStock()),
|
||||
),
|
||||
'unavailable_message' => $this->when(
|
||||
$selectedVariant === null,
|
||||
fn () => $this->unavailableMessage($this->availableStock()),
|
||||
),
|
||||
'images' => $this->when(
|
||||
$selectedVariant === null,
|
||||
fn () => $this->imageUrls($this->attachments),
|
||||
),
|
||||
'variants' => $this->variants
|
||||
->map(fn (Variant $variant): array => $this->variantData($variant))
|
||||
->values(),
|
||||
'selected_variant' => $this->when(
|
||||
$selectedVariant !== null,
|
||||
fn (): array => [
|
||||
...$this->variantData($selectedVariant),
|
||||
'images' => $this->imageUrls($selectedVariant->attachments),
|
||||
],
|
||||
),
|
||||
'components' => $this->when(
|
||||
$this->isBundle(),
|
||||
fn () => $this->bundleComponents
|
||||
->map(function ($component): array {
|
||||
$selectedItem = $component->variant ?? $component->catalogItem;
|
||||
|
||||
return [
|
||||
'catalog_item_id' => $component->component_catalog_item_id,
|
||||
'variant_id' => $component->component_variant_id,
|
||||
'quantity' => $component->quantity,
|
||||
'nombre' => $component->catalogItem->nombre,
|
||||
'item_nombre' => $selectedItem->getName(),
|
||||
];
|
||||
})
|
||||
->values(),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function attributeData(ItemAttribute $itemAttribute): array
|
||||
{
|
||||
$attribute = $itemAttribute->attribute;
|
||||
|
||||
return [
|
||||
'id' => $attribute->id,
|
||||
'codigo' => $attribute->codigo,
|
||||
'nombre' => $attribute->nombre,
|
||||
'sort_order' => $itemAttribute->sort_order,
|
||||
'show_in_selector' => $itemAttribute->show_in_selector,
|
||||
'ticket_label' => $itemAttribute->ticket_label,
|
||||
'is_required' => $attribute->is_required,
|
||||
'allow_multi_select' => $itemAttribute->allow_multi_select,
|
||||
'metadata_schema' => $attribute->metadata_schema,
|
||||
'type' => $attribute->type->value,
|
||||
'options' => $attribute->type === FieldType::EventDate
|
||||
? $this->eventDateOptions($itemAttribute)
|
||||
: $this->catalogAttributeOptions($itemAttribute),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return Collection<int, array<string, mixed>> */
|
||||
private function eventDateOptions(ItemAttribute $itemAttribute): Collection
|
||||
{
|
||||
return $itemAttribute->attribute->eventDates
|
||||
->map(fn ($eventDate, int $index): array => [
|
||||
'id' => $eventDate->id,
|
||||
'value' => (string) $eventDate->id,
|
||||
'label' => $eventDate->date->format('d/m/Y'),
|
||||
'sort_order' => $index,
|
||||
'validity_time_id' => $eventDate->validity_time_id,
|
||||
'validity_time' => ValidityTimeResource::make($eventDate->validityTime),
|
||||
'metadata' => [
|
||||
'date' => $eventDate->date->format('Y-m-d'),
|
||||
'time_start' => $eventDate->time_start,
|
||||
'time_end' => $eventDate->time_end,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return Collection<int, array<string, mixed>> */
|
||||
private function catalogAttributeOptions(ItemAttribute $itemAttribute): Collection
|
||||
{
|
||||
$availableValues = $this->variants
|
||||
->flatMap->definitions
|
||||
->where('item_attribute_id', $itemAttribute->id)
|
||||
->pluck('value')
|
||||
->filter()
|
||||
->unique();
|
||||
|
||||
return $itemAttribute->attribute->options
|
||||
->whereIn('value', $availableValues)
|
||||
->map(fn ($option): array => [
|
||||
'id' => $option->id,
|
||||
'value' => $option->value,
|
||||
'label' => $option->label,
|
||||
'sort_order' => $option->sort_order,
|
||||
'validity_time_id' => $option->validity_time_id,
|
||||
'validity_time' => $option->validityTime === null
|
||||
? null
|
||||
: ValidityTimeResource::make($option->validityTime, $this->tenant->timezone),
|
||||
'metadata' => $option->metadata,
|
||||
])
|
||||
->values();
|
||||
}
|
||||
|
||||
/** @return Collection<int, array<string, mixed>> */
|
||||
private function attributesData(): Collection
|
||||
{
|
||||
return $this->itemAttributes
|
||||
->sort(function (ItemAttribute $left, ItemAttribute $right): int {
|
||||
return $left->sort_order <=> $right->sort_order
|
||||
?: mb_strtolower($left->attribute->nombre) <=> mb_strtolower($right->attribute->nombre);
|
||||
})
|
||||
->map(fn (ItemAttribute $itemAttribute): array => $this->attributeData($itemAttribute))
|
||||
->values();
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function variantData(Variant $variant): array
|
||||
{
|
||||
$values = $variant->selectionOptions($this->itemAttributes);
|
||||
$eventDates = $variant->selectedEventDates();
|
||||
$variantStock = $this->variantStock($variant);
|
||||
|
||||
return [
|
||||
'id' => $variant->id,
|
||||
'event_date_id' => $variant->event_date_id,
|
||||
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||
'event_date_ids' => $eventDates->pluck('id')->values(),
|
||||
'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'maximum_addable_quantity' => $this->maximumAddable($variantStock),
|
||||
'unavailable_message' => $this->unavailableMessage($variantStock),
|
||||
'values' => $values,
|
||||
];
|
||||
}
|
||||
|
||||
/** @return Collection<int, string> */
|
||||
private function imageUrls(Collection $attachments): Collection
|
||||
{
|
||||
return $attachments
|
||||
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
||||
->values();
|
||||
}
|
||||
|
||||
private function variantStock(Variant $variant): ?int
|
||||
{
|
||||
return $this->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock();
|
||||
}
|
||||
|
||||
private function maximumAddable(?int $stock): ?int
|
||||
{
|
||||
return app(CatalogItemAllowanceService::class)->maximumAddableQuantity(
|
||||
$stock,
|
||||
$this->getAttribute('remaining_user_quota'),
|
||||
);
|
||||
}
|
||||
|
||||
private function unavailableMessage(?int $stock): ?string
|
||||
{
|
||||
return app(CatalogItemAllowanceService::class)->unavailableMessage(
|
||||
$stock,
|
||||
$this->getAttribute('remaining_user_quota'),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Resources;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use App\Domains\Commerce\Catalog\Services\CatalogItemAllowanceService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin CatalogItem */
|
||||
class CatalogSearchItemResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$availableStock = $this->availableStock();
|
||||
$visibleVariants = $this->visibleVariants();
|
||||
$attachment = $this->attachments->first()
|
||||
?? $visibleVariants
|
||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||
->first();
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'type' => $this->type->value,
|
||||
'nombre' => $this->nombre,
|
||||
'descripcion' => $this->descripcion,
|
||||
'precio' => $this->precio,
|
||||
'image' => $attachment?->getTemporaryUrl(1440),
|
||||
'maximum_addable_quantity' => $this->maximumAddable($availableStock),
|
||||
'unavailable_message' => $this->unavailableMessage($availableStock),
|
||||
'variants' => $visibleVariants
|
||||
->map(function (Variant $variant): array {
|
||||
$variantStock = $this->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory?->availableStock();
|
||||
|
||||
return [
|
||||
'id' => $variant->id,
|
||||
'event_date_id' => $variant->event_date_id,
|
||||
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
|
||||
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'maximum_addable_quantity' => $this->maximumAddable($variantStock),
|
||||
'unavailable_message' => $this->unavailableMessage($variantStock),
|
||||
'values' => $variant->selectorOptions($this->itemAttributes),
|
||||
];
|
||||
})
|
||||
->values(),
|
||||
];
|
||||
}
|
||||
|
||||
private function maximumAddable(?int $stock): ?int
|
||||
{
|
||||
return app(CatalogItemAllowanceService::class)->maximumAddableQuantity(
|
||||
$stock,
|
||||
$this->getAttribute('remaining_user_quota'),
|
||||
);
|
||||
}
|
||||
|
||||
private function unavailableMessage(?int $stock): ?string
|
||||
{
|
||||
return app(CatalogItemAllowanceService::class)->unavailableMessage(
|
||||
$stock,
|
||||
$this->getAttribute('remaining_user_quota'),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class CatalogVariantOptionsResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return $this->resource;
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Services;
|
||||
namespace App\Domains\Commerce\Catalog\Services;
|
||||
|
||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\BundleComponent;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Commerce\Catalog\Enums\CatalogItemType;
|
||||
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Commerce\Catalog\Models\BundleComponent;
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Commerce\Catalog\Models\Inventory;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class CatalogInventoryService
|
||||
{
|
||||
/** @return array<int, int> */
|
||||
public function requirementsFor(CatalogItem|Variant $selection, int $quantity = 1): array
|
||||
{
|
||||
if ($quantity <= 0) {
|
||||
throw new \InvalidArgumentException('La cantidad debe ser mayor a cero.');
|
||||
}
|
||||
|
||||
return array_map(
|
||||
fn (array $requirement): int => $requirement['quantity'] * $quantity,
|
||||
$this->inventoryRequirements($selection),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{quantity: int, tracks_inventory: bool}>
|
||||
*/
|
||||
public function detailedRequirementsFor(CatalogItem|Variant $selection, int $quantity = 1): array
|
||||
{
|
||||
if ($quantity <= 0) {
|
||||
throw new \InvalidArgumentException('La cantidad debe ser mayor a cero.');
|
||||
}
|
||||
|
||||
return array_map(
|
||||
fn (array $requirement): array => [
|
||||
...$requirement,
|
||||
'quantity' => $requirement['quantity'] * $quantity,
|
||||
],
|
||||
$this->inventoryRequirements($selection),
|
||||
);
|
||||
}
|
||||
|
||||
public function availableQuantity(CatalogItem|Variant $selection): ?int
|
||||
{
|
||||
if ($selection instanceof CatalogItem
|
||||
@@ -32,9 +63,14 @@ class CatalogInventoryService
|
||||
|
||||
$selection->loadMissing('variants.inventory');
|
||||
|
||||
return $selection->variants->sum(
|
||||
fn (Variant $variant): int => $variant->inventory->availableStock(),
|
||||
);
|
||||
return $selection->variants
|
||||
->filter(fn (Variant $variant): bool => $variant->isSellable())
|
||||
->unique(fn (Variant $variant): string => $variant->inventory_id === null
|
||||
? 'object:'.spl_object_id($variant->inventory)
|
||||
: 'id:'.$variant->inventory_id)
|
||||
->sum(
|
||||
fn (Variant $variant): int => $variant->inventory->availableStock(),
|
||||
);
|
||||
}
|
||||
|
||||
$requirements = $this->inventoryRequirements($selection);
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Services;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Commerce\Purchase\Services\UserPurchaseLimitService;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class CatalogItemAllowanceService
|
||||
{
|
||||
private const USER_QUOTA_REACHED_MESSAGE = 'Alcanzaste el cupo máximo permitido para este producto.';
|
||||
|
||||
private const OUT_OF_STOCK_MESSAGE = 'Este producto no tiene stock disponible.';
|
||||
|
||||
public function __construct(
|
||||
private readonly UserPurchaseLimitService $purchaseLimits,
|
||||
) {}
|
||||
|
||||
/** @param Collection<int, CatalogItem> $catalogItems */
|
||||
public function attach(Collection $catalogItems, ?int $userId): void
|
||||
{
|
||||
$remaining = $this->purchaseLimits->remainingByCatalogItem($catalogItems, $userId);
|
||||
|
||||
foreach ($catalogItems as $catalogItem) {
|
||||
$catalogItem->setAttribute(
|
||||
'remaining_user_quota',
|
||||
$remaining->get($catalogItem->getKey()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function maximumAddableQuantity(?int $availableStock, ?int $remainingUserQuota): ?int
|
||||
{
|
||||
if ($availableStock === null) {
|
||||
return $remainingUserQuota;
|
||||
}
|
||||
|
||||
if ($remainingUserQuota === null) {
|
||||
return $availableStock;
|
||||
}
|
||||
|
||||
return min($availableStock, $remainingUserQuota);
|
||||
}
|
||||
|
||||
public function unavailableMessage(?int $availableStock, ?int $remainingUserQuota): ?string
|
||||
{
|
||||
if ($remainingUserQuota !== null && $remainingUserQuota <= 0) {
|
||||
return self::USER_QUOTA_REACHED_MESSAGE;
|
||||
}
|
||||
|
||||
if ($availableStock !== null && $availableStock <= 0) {
|
||||
return self::OUT_OF_STOCK_MESSAGE;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
780
app/Domains/Commerce/Catalog/Services/CatalogService.php
Normal file
780
app/Domains/Commerce/Catalog/Services/CatalogService.php
Normal file
@@ -0,0 +1,780 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Services;
|
||||
|
||||
use App\Shared\Attachable\Models\Attachment;
|
||||
use App\Shared\Attachable\Services\AttachmentService;
|
||||
use App\Domains\Commerce\Catalog\Enums\CatalogItemType;
|
||||
use App\Domains\Commerce\Catalog\Models\Attribute;
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Commerce\Catalog\Models\Category;
|
||||
use App\Domains\Commerce\Catalog\Models\Inventory;
|
||||
use App\Domains\Commerce\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use App\Domains\Ticketing\Event\Models\EventDate;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class CatalogService
|
||||
{
|
||||
public function __construct(protected AttachmentService $attachmentService) {}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public function create(array $data): CatalogItem
|
||||
{
|
||||
return DB::transaction(function () use ($data): CatalogItem {
|
||||
$type = CatalogItemType::from(
|
||||
$data['type'] ?? CatalogItemType::Standard->value,
|
||||
);
|
||||
$variants = $data['variants'] ?? [];
|
||||
$images = $data['images'] ?? [];
|
||||
$attributeCodes = $data['attribute_codes'] ?? [];
|
||||
$multiSelectAttributeCodes = $data['multi_select_attribute_codes'] ?? [];
|
||||
$hiddenAttributeCodes = $data['hidden_attribute_codes'] ?? [];
|
||||
$ticketAttributeLabels = $data['ticket_attribute_labels'] ?? [];
|
||||
$components = $data['components'] ?? [];
|
||||
$hasDirectStock = array_key_exists('real_stock', $data);
|
||||
$realStock = (int) ($data['real_stock'] ?? 0);
|
||||
|
||||
$hasEventDateVariants = $variants !== [] && collect($variants)->every(
|
||||
fn (array $variant): bool => ! empty($variant['event_date_id'])
|
||||
|| ! empty($variant['event_date_ids'])
|
||||
);
|
||||
|
||||
if ($hasEventDateVariants && ! in_array('event_date', $attributeCodes, true)) {
|
||||
throw ValidationException::withMessages([
|
||||
'attribute_codes' => [
|
||||
__('api.catalog.event_date_attribute_required'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$hasVariants = $attributeCodes !== [] || $hasEventDateVariants;
|
||||
|
||||
if (array_diff($multiSelectAttributeCodes, $attributeCodes) !== []) {
|
||||
throw ValidationException::withMessages([
|
||||
'multi_select_attribute_codes' => [
|
||||
__('api.catalog.multi_select_attribute_not_on_item'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if (array_diff($hiddenAttributeCodes, $attributeCodes) !== []) {
|
||||
throw ValidationException::withMessages([
|
||||
'hidden_attribute_codes' => [
|
||||
__('api.catalog.hidden_attribute_not_on_item'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if (array_diff(array_keys($ticketAttributeLabels), $attributeCodes) !== []) {
|
||||
throw ValidationException::withMessages([
|
||||
'ticket_attribute_labels' => [
|
||||
__('api.catalog.ticket_label_attribute_not_on_item'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$this->validateUniqueVariantCombinations($variants, $attributeCodes);
|
||||
|
||||
if ($type === CatalogItemType::Bundle) {
|
||||
$this->validateBundleData($data, $components);
|
||||
} else {
|
||||
if (array_key_exists('components', $data)) {
|
||||
throw ValidationException::withMessages([
|
||||
'components' => [__('api.catalog.standard_with_components')],
|
||||
]);
|
||||
}
|
||||
|
||||
$this->validateInventoryStrategy(
|
||||
$data,
|
||||
$variants,
|
||||
$hasVariants,
|
||||
$hasDirectStock,
|
||||
);
|
||||
}
|
||||
|
||||
unset(
|
||||
$data['variants'],
|
||||
$data['images'],
|
||||
$data['attribute_codes'],
|
||||
$data['multi_select_attribute_codes'],
|
||||
$data['hidden_attribute_codes'],
|
||||
$data['ticket_attribute_labels'],
|
||||
$data['components'],
|
||||
$data['real_stock'],
|
||||
$data['reserved_stock'],
|
||||
$data['sold_units'],
|
||||
$data['inventory_id'],
|
||||
);
|
||||
|
||||
$data['type'] = $type;
|
||||
|
||||
if ($type === CatalogItemType::Bundle) {
|
||||
$data['inventory_id'] = null;
|
||||
$data['inventory_policy'] = null;
|
||||
$data['has_tickets'] = false;
|
||||
} elseif ($hasVariants) {
|
||||
$data['inventory_id'] = null;
|
||||
} else {
|
||||
$data['inventory_id'] = $this->createInventory($realStock)->id;
|
||||
}
|
||||
|
||||
$catalogItem = CatalogItem::query()->create($data);
|
||||
$itemAttributes = $type === CatalogItemType::Standard
|
||||
? $this->createItemAttributes(
|
||||
$catalogItem,
|
||||
$attributeCodes,
|
||||
$multiSelectAttributeCodes,
|
||||
$hiddenAttributeCodes,
|
||||
$ticketAttributeLabels,
|
||||
)
|
||||
: [];
|
||||
|
||||
if ($type === CatalogItemType::Bundle) {
|
||||
$this->createBundleComponents($catalogItem, $components);
|
||||
}
|
||||
|
||||
$createdVariants = [];
|
||||
foreach ($variants as $index => $variantData) {
|
||||
$createdVariants[] = [
|
||||
'variant' => $this->createVariant(
|
||||
$catalogItem,
|
||||
$variantData,
|
||||
$itemAttributes,
|
||||
$index,
|
||||
),
|
||||
'images' => $variantData['images'] ?? [],
|
||||
'index' => $index,
|
||||
];
|
||||
}
|
||||
|
||||
$this->attachImages($catalogItem, $images, 'images');
|
||||
|
||||
foreach ($createdVariants as $createdVariant) {
|
||||
$this->attachImages(
|
||||
$createdVariant['variant'],
|
||||
$createdVariant['images'],
|
||||
"variants.{$createdVariant['index']}.images",
|
||||
);
|
||||
}
|
||||
|
||||
return $catalogItem->load([
|
||||
'attachments',
|
||||
'inventory',
|
||||
'category',
|
||||
'brand',
|
||||
'itemAttributes.attribute',
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
'variants.eventDate',
|
||||
'variants.eventDates',
|
||||
'variants.definitions.itemAttribute.attribute.options',
|
||||
'bundleComponents.catalogItem',
|
||||
'bundleComponents.variant.catalogItem',
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
public function getDetail(CatalogItem $catalogItem, ?int $variantId = null): CatalogItem
|
||||
{
|
||||
$catalogItem->load([
|
||||
'attachments',
|
||||
'inventory',
|
||||
'category',
|
||||
'brand',
|
||||
'itemAttributes.attribute.options.validityTime',
|
||||
'itemAttributes.attribute.eventDates.validityTime',
|
||||
'variants' => fn ($query) => $query->orderBy('id'),
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
'variants.eventDate',
|
||||
'variants.eventDates',
|
||||
'variants.definitions' => fn ($query) => $query->orderBy('id'),
|
||||
'variants.definitions.itemAttribute.attribute.options',
|
||||
'bundleComponents.catalogItem.inventory',
|
||||
'bundleComponents.variant.inventory',
|
||||
'bundleComponents.variant.definitions.itemAttribute.attribute',
|
||||
]);
|
||||
|
||||
$visibleVariants = $catalogItem->visibleVariants();
|
||||
if ($catalogItem->type === CatalogItemType::Standard
|
||||
&& ($catalogItem->inventory_id !== null || $catalogItem->variants->isNotEmpty())
|
||||
&& (($catalogItem->variants->isNotEmpty() && $visibleVariants->isEmpty())
|
||||
|| ! $catalogItem->isAvailable())) {
|
||||
throw new NotFoundHttpException('Catalog item is out of stock.');
|
||||
}
|
||||
|
||||
$catalogItem->setRelation('variants', $visibleVariants);
|
||||
$selectedVariant = $variantId === null
|
||||
? $visibleVariants->first()
|
||||
: $visibleVariants->firstWhere('id', $variantId);
|
||||
|
||||
if ($variantId !== null && $selectedVariant === null) {
|
||||
throw new NotFoundHttpException('Variant not found for catalog item.');
|
||||
}
|
||||
|
||||
$catalogItem->setRelation('selectedVariant', $selectedVariant);
|
||||
|
||||
return $catalogItem;
|
||||
}
|
||||
|
||||
/** @return LengthAwarePaginator<CatalogItem> */
|
||||
public function search(
|
||||
Tenant $tenant,
|
||||
string $term,
|
||||
int $perPage,
|
||||
int $page,
|
||||
): LengthAwarePaginator {
|
||||
$normalizedTerm = mb_strtolower($term);
|
||||
$containsPattern = "%{$normalizedTerm}%";
|
||||
$startsWithPattern = "{$normalizedTerm}%";
|
||||
|
||||
$paginator = CatalogItem::query()
|
||||
->forTenantCatalog($tenant)
|
||||
->whereAvailable()
|
||||
->where(function (Builder $query) use ($containsPattern): void {
|
||||
$query
|
||||
->whereRaw('LOWER(nombre) LIKE ?', [$containsPattern])
|
||||
->orWhereRaw('LOWER(descripcion) LIKE ?', [$containsPattern])
|
||||
->orWhereHas(
|
||||
'brand',
|
||||
fn (Builder $brandQuery) => $brandQuery
|
||||
->whereRaw('LOWER(nombre) LIKE ?', [$containsPattern])
|
||||
)
|
||||
->orWhereHas(
|
||||
'category',
|
||||
fn (Builder $categoryQuery) => $categoryQuery
|
||||
->whereRaw('LOWER(nombre) LIKE ?', [$containsPattern])
|
||||
);
|
||||
})
|
||||
->with([
|
||||
'attachments',
|
||||
'inventory',
|
||||
'itemAttributes.attribute',
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
'variants.eventDate',
|
||||
'variants.eventDates',
|
||||
'variants.definitions.itemAttribute.attribute.options',
|
||||
'bundleComponents.catalogItem',
|
||||
'bundleComponents.variant.catalogItem',
|
||||
])
|
||||
->orderByRaw(
|
||||
'CASE WHEN LOWER(nombre) = ? THEN 0 WHEN LOWER(nombre) LIKE ? THEN 1 ELSE 2 END',
|
||||
[$normalizedTerm, $startsWithPattern],
|
||||
)
|
||||
->orderBy('nombre')
|
||||
->paginate(perPage: $perPage, pageName: 'page', page: $page);
|
||||
|
||||
return $paginator->withPath(route('catalog-items.index', [
|
||||
'tenant' => $tenant->codigo,
|
||||
]));
|
||||
}
|
||||
|
||||
/** @return LengthAwarePaginator<CatalogItem> */
|
||||
public function categoryItems(
|
||||
Tenant $tenant,
|
||||
Category $category,
|
||||
int $perPage,
|
||||
int $page,
|
||||
): LengthAwarePaginator {
|
||||
return CatalogItem::query()
|
||||
->forTenantCatalog($tenant)
|
||||
->where('category_id', $category->id)
|
||||
->whereAvailable()
|
||||
->with([
|
||||
'attachments',
|
||||
'inventory',
|
||||
'itemAttributes.attribute',
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
'variants.eventDate',
|
||||
'variants.eventDates',
|
||||
'variants.definitions.itemAttribute.attribute.options',
|
||||
'bundleComponents.catalogItem',
|
||||
'bundleComponents.variant.catalogItem',
|
||||
])
|
||||
->orderBy('nombre')
|
||||
->paginate(perPage: $perPage, pageName: 'page', page: $page);
|
||||
}
|
||||
|
||||
public function delete(CatalogItem $catalogItem): void
|
||||
{
|
||||
DB::transaction(function () use ($catalogItem): void {
|
||||
$catalogItem->variants()->delete();
|
||||
$catalogItem->delete();
|
||||
});
|
||||
}
|
||||
|
||||
public function deleteVariant(Variant $variant): void
|
||||
{
|
||||
DB::transaction(function () use ($variant): void {
|
||||
$variant = Variant::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($variant->getKey());
|
||||
$catalogItem = CatalogItem::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($variant->catalog_item_id);
|
||||
$variant->delete();
|
||||
|
||||
$sellableVariants = $catalogItem->variants()
|
||||
->whereNull('sales_disabled_at')
|
||||
->whereNull('replaced_by_variant_id');
|
||||
|
||||
if (! (clone $sellableVariants)->exists()) {
|
||||
$this->delete($catalogItem);
|
||||
} elseif (($minimumPrice = (clone $sellableVariants)->min('precio')) !== null) {
|
||||
$catalogItem->update(['precio' => $minimumPrice]);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
private function createInventory(int $realStock): Inventory
|
||||
{
|
||||
return Inventory::query()->create([
|
||||
'real_stock' => $realStock,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $components
|
||||
*/
|
||||
private function createBundleComponents(CatalogItem $bundle, array $components): void
|
||||
{
|
||||
$seen = [];
|
||||
|
||||
foreach (array_values($components) as $index => $componentData) {
|
||||
$catalogItemId = (int) $componentData['catalog_item_id'];
|
||||
$variantId = isset($componentData['variant_id'])
|
||||
? (int) $componentData['variant_id']
|
||||
: null;
|
||||
$key = $catalogItemId.':'.($variantId ?? 'direct');
|
||||
|
||||
if (isset($seen[$key])) {
|
||||
throw ValidationException::withMessages([
|
||||
"components.{$index}" => [__('api.catalog.duplicate_component')],
|
||||
]);
|
||||
}
|
||||
$seen[$key] = true;
|
||||
|
||||
$componentItem = CatalogItem::query()
|
||||
->whereKey($catalogItemId)
|
||||
->where('tenant_code', $bundle->tenant_code)
|
||||
->when($bundle->event_id !== null, fn (Builder $query): Builder => $query
|
||||
->where('event_id', $bundle->event_id))
|
||||
->first();
|
||||
|
||||
if ($componentItem === null) {
|
||||
throw ValidationException::withMessages([
|
||||
"components.{$index}.catalog_item_id" => [
|
||||
__('api.catalog.component_wrong_tenant'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($componentItem->is($bundle) || $componentItem->type !== CatalogItemType::Standard) {
|
||||
throw ValidationException::withMessages([
|
||||
"components.{$index}.catalog_item_id" => [
|
||||
__('api.catalog.invalid_component'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$hasVariants = $componentItem->variants()->exists();
|
||||
if ($hasVariants && $variantId === null) {
|
||||
throw ValidationException::withMessages([
|
||||
"components.{$index}.variant_id" => [
|
||||
__('api.catalog.component_variant_required'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $hasVariants && $variantId !== null) {
|
||||
throw ValidationException::withMessages([
|
||||
"components.{$index}.variant_id" => [
|
||||
__('api.catalog.component_variant_forbidden'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($variantId !== null && ! $componentItem->variants()
|
||||
->whereKey($variantId)
|
||||
->whereNull('sales_disabled_at')
|
||||
->whereNull('replaced_by_variant_id')
|
||||
->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
"components.{$index}.variant_id" => [
|
||||
__('api.catalog.component_variant_invalid'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$bundle->bundleComponents()->create([
|
||||
'component_catalog_item_id' => $componentItem->id,
|
||||
'component_variant_id' => $variantId,
|
||||
'quantity' => (int) $componentData['quantity'],
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @param array<int, array<string, mixed>> $components
|
||||
*/
|
||||
private function validateBundleData(array $data, array $components): void
|
||||
{
|
||||
if ($components === []) {
|
||||
throw ValidationException::withMessages([
|
||||
'components' => [__('api.catalog.bundle_component_required')],
|
||||
]);
|
||||
}
|
||||
|
||||
foreach ([
|
||||
'real_stock',
|
||||
'inventory_policy',
|
||||
'attribute_codes',
|
||||
'variants',
|
||||
'has_tickets',
|
||||
] as $field) {
|
||||
if (array_key_exists($field, $data)) {
|
||||
throw ValidationException::withMessages([
|
||||
$field => [__('api.catalog.bundle_field_forbidden', ['field' => $field])],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, mixed> $images
|
||||
*/
|
||||
private function attachImages(
|
||||
CatalogItem|Variant $owner,
|
||||
array $images,
|
||||
string $validationKey,
|
||||
): void {
|
||||
foreach (array_values($images) as $order => $image) {
|
||||
$attachment = $this->resolveAttachment($image, "{$validationKey}.{$order}");
|
||||
|
||||
$owner->attachments()->attach($attachment->id, ['orden' => $order]);
|
||||
}
|
||||
}
|
||||
|
||||
private function resolveAttachment(mixed $image, string $validationKey): Attachment
|
||||
{
|
||||
if (is_string($image) && Str::isUuid($image)) {
|
||||
$attachment = Attachment::query()->where('key', $image)->first();
|
||||
|
||||
if ($attachment === null) {
|
||||
throw ValidationException::withMessages([
|
||||
$validationKey => [__('api.catalog.attachment_not_found')],
|
||||
]);
|
||||
}
|
||||
|
||||
return $attachment;
|
||||
}
|
||||
|
||||
return $this->attachmentService->store($image, 'catalog-items');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $attributeCodes
|
||||
* @param array<int, string> $multiSelectAttributeCodes
|
||||
* @param array<int, string> $hiddenAttributeCodes
|
||||
* @param array<string, string> $ticketAttributeLabels
|
||||
* @return array<string, ItemAttribute>
|
||||
*/
|
||||
private function createItemAttributes(
|
||||
CatalogItem $catalogItem,
|
||||
array $attributeCodes,
|
||||
array $multiSelectAttributeCodes = [],
|
||||
array $hiddenAttributeCodes = [],
|
||||
array $ticketAttributeLabels = [],
|
||||
): array {
|
||||
$itemAttributes = [];
|
||||
$attributeCodes = array_values(array_unique($attributeCodes));
|
||||
$attributes = Attribute::query()
|
||||
->where('tenant_codigo', $catalogItem->tenant_code)
|
||||
->whereIn('codigo', $attributeCodes)
|
||||
->get()
|
||||
->keyBy('codigo');
|
||||
|
||||
foreach ($attributeCodes as $attributeCode) {
|
||||
$attribute = $attributes->get($attributeCode);
|
||||
|
||||
if ($attribute === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'attribute_codes' => [
|
||||
__('api.catalog.attribute_not_found', ['attribute' => $attributeCode]),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$itemAttribute = $catalogItem->itemAttributes()->create([
|
||||
'attribute_id' => $attribute->id,
|
||||
'allow_multi_select' => in_array($attributeCode, $multiSelectAttributeCodes, true),
|
||||
'show_in_selector' => ! in_array($attributeCode, $hiddenAttributeCodes, true),
|
||||
'ticket_label' => $ticketAttributeLabels[$attributeCode] ?? null,
|
||||
]);
|
||||
|
||||
$itemAttributes[$attributeCode] = $itemAttribute;
|
||||
}
|
||||
|
||||
return $itemAttributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @param array<string, ItemAttribute> $itemAttributes
|
||||
*/
|
||||
private function createVariant(
|
||||
CatalogItem $catalogItem,
|
||||
array $data,
|
||||
array $itemAttributes,
|
||||
int $index,
|
||||
): Variant {
|
||||
unset($data['images']);
|
||||
|
||||
if (
|
||||
array_key_exists('inventory_id', $data)
|
||||
|| array_key_exists('reserved_stock', $data)
|
||||
|| array_key_exists('sold_units', $data)
|
||||
) {
|
||||
throw ValidationException::withMessages([
|
||||
"variants.{$index}.inventory" => [
|
||||
__('api.catalog.managed_inventory_fields'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$inventory = $this->createInventory((int) ($data['real_stock'] ?? 0));
|
||||
$eventDateIds = collect($data['event_date_ids'] ?? [])
|
||||
->when(
|
||||
isset($data['event_date_id']),
|
||||
fn ($ids) => $ids->push($data['event_date_id']),
|
||||
)
|
||||
->filter(fn ($id): bool => $id !== null)
|
||||
->map(fn ($id): int => (int) $id)
|
||||
->unique()
|
||||
->sort()
|
||||
->values();
|
||||
|
||||
$eventDateItemAttribute = $itemAttributes['event_date'] ?? null;
|
||||
if ($eventDateItemAttribute !== null && (
|
||||
$eventDateIds->isEmpty()
|
||||
|| (! $eventDateItemAttribute->allow_multi_select && $eventDateIds->count() !== 1)
|
||||
)) {
|
||||
throw ValidationException::withMessages([
|
||||
"variants.{$index}.event_date_ids" => [
|
||||
$eventDateItemAttribute->allow_multi_select
|
||||
? __('api.catalog.event_date_selection_required')
|
||||
: __('api.catalog.single_event_date_required'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$validEventDateCount = EventDate::query()
|
||||
->whereKey($eventDateIds)
|
||||
->where('tenant_code', $catalogItem->tenant_code)
|
||||
->count();
|
||||
|
||||
if ($validEventDateCount !== $eventDateIds->count()) {
|
||||
throw ValidationException::withMessages([
|
||||
"variants.{$index}.event_date_ids" => [
|
||||
__('api.catalog.event_date_wrong_tenant'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$variant = $catalogItem->variants()->create([
|
||||
'inventory_id' => $inventory->id,
|
||||
'event_date_id' => $eventDateIds->count() === 1 ? $eventDateIds->first() : null,
|
||||
'descripcion' => $data['descripcion'] ?? null,
|
||||
'precio' => $data['precio'] ?? null,
|
||||
]);
|
||||
$variant->eventDates()->sync($eventDateIds->all());
|
||||
$variant->setRelation('catalogItem', $catalogItem);
|
||||
|
||||
foreach ($data['values'] ?? [] as $attributeCode => $value) {
|
||||
$itemAttribute = $itemAttributes[$attributeCode] ?? null;
|
||||
|
||||
if ($itemAttribute === null) {
|
||||
throw ValidationException::withMessages([
|
||||
"variants.{$index}.values.{$attributeCode}" => [
|
||||
__('api.catalog.attribute_not_on_item'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
foreach ($this->validatedVariantValues(
|
||||
$itemAttribute,
|
||||
$value,
|
||||
"variants.{$index}.values.{$attributeCode}",
|
||||
) as $validatedValue) {
|
||||
$variant->definitions()->create([
|
||||
'item_attribute_id' => $itemAttribute->id,
|
||||
'value' => $validatedValue,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return $variant;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $variants
|
||||
* @param array<int, string> $attributeCodes
|
||||
*/
|
||||
private function validateUniqueVariantCombinations(array $variants, array $attributeCodes): void
|
||||
{
|
||||
$seen = [];
|
||||
$attributeCodes = array_values(array_unique($attributeCodes));
|
||||
sort($attributeCodes);
|
||||
|
||||
foreach (array_values($variants) as $index => $variant) {
|
||||
$eventDateIds = collect($variant['event_date_ids'] ?? [])
|
||||
->when(
|
||||
isset($variant['event_date_id']),
|
||||
fn ($ids) => $ids->push($variant['event_date_id']),
|
||||
)
|
||||
->map(fn ($id): int => (int) $id)
|
||||
->unique()
|
||||
->sort()
|
||||
->values()
|
||||
->implode(',');
|
||||
$combination = [$eventDateIds];
|
||||
|
||||
foreach ($attributeCodes as $attributeCode) {
|
||||
$values = $variant['values'][$attributeCode] ?? '';
|
||||
$normalizedValues = collect(is_array($values) ? $values : [$values])
|
||||
->map(fn ($value): string => $this->normalizeVariantValue((string) $value))
|
||||
->unique()
|
||||
->sort()
|
||||
->values()
|
||||
->implode(',');
|
||||
$combination[] = $normalizedValues;
|
||||
}
|
||||
|
||||
$key = implode('|', $combination);
|
||||
if (isset($seen[$key])) {
|
||||
throw ValidationException::withMessages([
|
||||
"variants.{$index}" => [__('api.catalog.duplicate_variant_combination')],
|
||||
]);
|
||||
}
|
||||
|
||||
$seen[$key] = true;
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<int, string> */
|
||||
private function validatedVariantValues(
|
||||
ItemAttribute $itemAttribute,
|
||||
mixed $value,
|
||||
string $validationKey,
|
||||
): array {
|
||||
$values = is_array($value) ? array_values($value) : [$value];
|
||||
|
||||
if ($values === [] || (! $itemAttribute->allow_multi_select && count($values) !== 1)) {
|
||||
throw ValidationException::withMessages([
|
||||
$validationKey => [
|
||||
$itemAttribute->allow_multi_select
|
||||
? __('api.catalog.multi_value_required')
|
||||
: __('api.catalog.single_value_required'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if (collect($values)->contains(fn ($item): bool => ! is_string($item) || trim($item) === '')) {
|
||||
throw ValidationException::withMessages([
|
||||
$validationKey => [__('api.catalog.selected_values_non_empty')],
|
||||
]);
|
||||
}
|
||||
|
||||
$normalizedValues = collect($values)
|
||||
->map(fn (string $item): string => $this->normalizeVariantValue($item));
|
||||
|
||||
if ($normalizedValues->unique()->count() !== count($values)) {
|
||||
throw ValidationException::withMessages([
|
||||
$validationKey => [__('api.catalog.selected_values_distinct')],
|
||||
]);
|
||||
}
|
||||
|
||||
$attribute = $itemAttribute->attribute;
|
||||
if ($attribute->type->supportsOptions() && ! $attribute->type->usesDynamicOptions()) {
|
||||
$optionsByNormalizedValue = $attribute->options
|
||||
->keyBy(fn ($option): string => $this->normalizeVariantValue($option->value));
|
||||
|
||||
$resolvedOptions = $normalizedValues->map(fn (string $normalizedValue) => $optionsByNormalizedValue->get($normalizedValue));
|
||||
if ($resolvedOptions->contains(null)) {
|
||||
throw ValidationException::withMessages([
|
||||
$validationKey => [__('api.catalog.invalid_attribute_options')],
|
||||
]);
|
||||
}
|
||||
|
||||
return $resolvedOptions->pluck('value')->all();
|
||||
}
|
||||
|
||||
return collect($values)->map(fn (string $item): string => trim($item))->all();
|
||||
}
|
||||
|
||||
private function normalizeVariantValue(string $value): string
|
||||
{
|
||||
return Str::ascii(mb_strtolower(trim($value)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @param array<int, array<string, mixed>> $variants
|
||||
*/
|
||||
private function validateInventoryStrategy(
|
||||
array $data,
|
||||
array $variants,
|
||||
bool $hasVariants,
|
||||
bool $hasDirectStock,
|
||||
): void {
|
||||
if ($hasVariants && $variants === []) {
|
||||
throw ValidationException::withMessages([
|
||||
'variants' => [
|
||||
__('api.catalog.variants_required'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $hasVariants && $variants !== []) {
|
||||
throw ValidationException::withMessages([
|
||||
'variants' => [
|
||||
__('api.catalog.variants_forbidden'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($hasVariants && $hasDirectStock) {
|
||||
throw ValidationException::withMessages([
|
||||
'real_stock' => [
|
||||
__('api.catalog.direct_inventory_forbidden'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if (
|
||||
array_key_exists('inventory_id', $data)
|
||||
|| array_key_exists('reserved_stock', $data)
|
||||
|| array_key_exists('sold_units', $data)
|
||||
) {
|
||||
throw ValidationException::withMessages([
|
||||
'inventory' => [
|
||||
__('api.catalog.managed_inventory_fields'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Services;
|
||||
|
||||
use App\Domains\Commerce\Cart\Models\Cart;
|
||||
use App\Domains\Commerce\Catalog\Models\StockReservation;
|
||||
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||
use App\Domains\Commerce\Purchase\Services\Checkout\ReleaseCheckoutService;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class ExpireStockReservationsService
|
||||
{
|
||||
private const BATCH_SIZE = 500;
|
||||
|
||||
public function __construct(
|
||||
private readonly ReleaseCheckoutService $purchases,
|
||||
private readonly StockReservationService $reservations,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{purchases: int, cart_reservations: int, orphan_reservations: int, failed: int}
|
||||
*/
|
||||
public function expireOverdue(): array
|
||||
{
|
||||
$summary = [
|
||||
'purchases' => 0,
|
||||
'cart_reservations' => 0,
|
||||
'orphan_reservations' => 0,
|
||||
'failed' => 0,
|
||||
];
|
||||
$lastReservationId = 0;
|
||||
|
||||
do {
|
||||
$reservationIds = StockReservation::query()
|
||||
->where('status', StockReservation::STATUS_ACTIVE)
|
||||
->whereNotNull('expires_at')
|
||||
->where('expires_at', '<=', now())
|
||||
->where('id', '>', $lastReservationId)
|
||||
->orderBy('id')
|
||||
->limit(self::BATCH_SIZE)
|
||||
->pluck('id');
|
||||
|
||||
foreach ($reservationIds as $reservationId) {
|
||||
$lastReservationId = (int) $reservationId;
|
||||
|
||||
try {
|
||||
$owner = $this->expireReservation($lastReservationId);
|
||||
if ($owner !== null) {
|
||||
$summary[$owner]++;
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
$summary['failed']++;
|
||||
Log::channel('commands')->error('Failed to expire overdue stock reservation.', [
|
||||
'command' => 'reservations:expire',
|
||||
'stock_reservation_id' => $lastReservationId,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
}
|
||||
}
|
||||
} while ($reservationIds->count() === self::BATCH_SIZE);
|
||||
|
||||
Log::channel('commands')->info('Stock reservation cleanup completed.', [
|
||||
'command' => 'reservations:expire',
|
||||
'expired_purchases' => $summary['purchases'],
|
||||
'expired_cart_reservations' => $summary['cart_reservations'],
|
||||
'expired_orphan_reservations' => $summary['orphan_reservations'],
|
||||
'failed_reservations' => $summary['failed'],
|
||||
'total_expired' => $summary['purchases']
|
||||
+ $summary['cart_reservations']
|
||||
+ $summary['orphan_reservations'],
|
||||
]);
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
public function expireIfOverdue(int $reservationId): bool
|
||||
{
|
||||
/** @var StockReservation|null $reservation */
|
||||
$reservation = StockReservation::query()->find($reservationId);
|
||||
if ($reservation?->status === StockReservation::STATUS_EXPIRED) {
|
||||
return true;
|
||||
}
|
||||
if (! $this->isOverdue($reservation)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->expireReservation($reservationId) !== null;
|
||||
}
|
||||
|
||||
/** @return 'purchases'|'cart_reservations'|'orphan_reservations'|null */
|
||||
private function expireReservation(int $reservationId): ?string
|
||||
{
|
||||
$purchaseId = Purchase::query()
|
||||
->where('stock_reservation_id', $reservationId)
|
||||
->value('id');
|
||||
if ($purchaseId !== null) {
|
||||
return $this->expirePurchase((int) $purchaseId);
|
||||
}
|
||||
|
||||
$cartId = Cart::query()
|
||||
->where('current_stock_reservation_id', $reservationId)
|
||||
->where('status', 'active')
|
||||
->value('id');
|
||||
if ($cartId !== null) {
|
||||
return $this->expireCart((int) $cartId, $reservationId);
|
||||
}
|
||||
|
||||
return $this->expireOrphan($reservationId);
|
||||
}
|
||||
|
||||
/** @return 'purchases'|null */
|
||||
private function expirePurchase(int $purchaseId): ?string
|
||||
{
|
||||
/** @var Purchase|null $purchase */
|
||||
$purchase = Purchase::query()->find($purchaseId);
|
||||
if ($purchase === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$purchase = $this->purchases->expire($purchase);
|
||||
if ($purchase->status === Purchase::STATUS_EXPIRED) {
|
||||
return 'purchases';
|
||||
}
|
||||
|
||||
$reservation = $purchase->stockReservation;
|
||||
if ($this->isOverdue($reservation)) {
|
||||
throw new RuntimeException('An overdue active reservation belongs to a purchase that cannot expire.');
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @return 'cart_reservations'|null */
|
||||
private function expireCart(int $cartId, int $reservationId): ?string
|
||||
{
|
||||
return DB::transaction(function () use ($cartId, $reservationId): ?string {
|
||||
/** @var Cart|null $cart */
|
||||
$cart = Cart::query()
|
||||
->whereKey($cartId)
|
||||
->where('current_stock_reservation_id', $reservationId)
|
||||
->where('status', Cart::STATUS_ACTIVE)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
if ($cart === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @var StockReservation|null $reservation */
|
||||
$reservation = StockReservation::query()->lockForUpdate()->find($reservationId);
|
||||
if (! $this->isOverdue($reservation)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->reservations->expire($reservation);
|
||||
$cart->update(['status' => Cart::STATUS_EXPIRED]);
|
||||
|
||||
return 'cart_reservations';
|
||||
});
|
||||
}
|
||||
|
||||
/** @return 'orphan_reservations'|null */
|
||||
private function expireOrphan(int $reservationId): ?string
|
||||
{
|
||||
/** @var StockReservation|null $reservation */
|
||||
$reservation = StockReservation::query()->find($reservationId);
|
||||
if (! $this->isOverdue($reservation)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->reservations->expire($reservation);
|
||||
|
||||
return 'orphan_reservations';
|
||||
}
|
||||
|
||||
private function isOverdue(?StockReservation $reservation): bool
|
||||
{
|
||||
return $reservation !== null
|
||||
&& $reservation->status === StockReservation::STATUS_ACTIVE
|
||||
&& $reservation->expires_at !== null
|
||||
&& ! $reservation->expires_at->isFuture();
|
||||
}
|
||||
}
|
||||
115
app/Domains/Commerce/Catalog/Services/FeaturedGroupService.php
Normal file
115
app/Domains/Commerce/Catalog/Services/FeaturedGroupService.php
Normal file
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Services;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Enums\FeaturedGroupSource;
|
||||
use App\Domains\Commerce\Catalog\Enums\GroupLayout;
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Commerce\Catalog\Resources\CatalogFeaturedItemResource;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
class FeaturedGroupService
|
||||
{
|
||||
private const ITEMS_PER_PAGE = 12;
|
||||
|
||||
/** @return array<array-key, mixed> */
|
||||
public function __construct(
|
||||
private readonly CatalogItemAllowanceService $allowances,
|
||||
) {}
|
||||
|
||||
public function itemsResponse(FeaturedGroup $featuredGroup, Tenant $tenant, int $page, ?int $userId = null): array
|
||||
{
|
||||
if ($featuredGroup->group_layout !== GroupLayout::Paginated) {
|
||||
$query = $this->itemsQuery($featuredGroup, $tenant);
|
||||
|
||||
if ($featuredGroup->group_layout === GroupLayout::Single) {
|
||||
$query->limit(1);
|
||||
}
|
||||
|
||||
$items = $query->get();
|
||||
$this->attachGroup($items, $featuredGroup);
|
||||
$this->allowances->attach($items, $userId);
|
||||
|
||||
return CatalogFeaturedItemResource::collection($items)->resolve();
|
||||
}
|
||||
|
||||
$paginator = $this->paginateItems($featuredGroup, $tenant, $page);
|
||||
$this->attachGroup($paginator->getCollection(), $featuredGroup);
|
||||
$this->allowances->attach($paginator->getCollection(), $userId);
|
||||
|
||||
return CatalogFeaturedItemResource::collection($paginator)
|
||||
->response()
|
||||
->getData(true);
|
||||
}
|
||||
|
||||
/** @return Builder<CatalogItem> */
|
||||
private function itemsQuery(FeaturedGroup $featuredGroup, Tenant $tenant): Builder
|
||||
{
|
||||
$query = CatalogItem::query()
|
||||
->forTenantCatalog($tenant)
|
||||
->whereAvailable()
|
||||
->where(function (Builder $query): void {
|
||||
$query
|
||||
->whereDoesntHave('category')
|
||||
->orWhereHas(
|
||||
'category',
|
||||
fn (Builder $categoryQuery): Builder => $categoryQuery
|
||||
->where('is_enabled', true),
|
||||
);
|
||||
})
|
||||
->with([
|
||||
'inventory',
|
||||
'attachments',
|
||||
'itemAttributes.attribute',
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
'variants.eventDate',
|
||||
'variants.eventDates',
|
||||
'variants.definitions.itemAttribute.attribute.options',
|
||||
'bundleComponents.catalogItem',
|
||||
'bundleComponents.variant.catalogItem',
|
||||
]);
|
||||
|
||||
return match ($featuredGroup->source_type) {
|
||||
FeaturedGroupSource::Manual => $query
|
||||
->select('catalog_items.*')
|
||||
->join('featured_items', 'featured_items.catalog_item_id', '=', 'catalog_items.id')
|
||||
->where('featured_items.featured_group_id', $featuredGroup->id)
|
||||
->orderBy('featured_items.order')
|
||||
->orderBy('featured_items.id'),
|
||||
FeaturedGroupSource::Category => $query
|
||||
->where('catalog_items.category_id', $featuredGroup->category_id)
|
||||
->orderBy('catalog_items.id'),
|
||||
FeaturedGroupSource::All => $query
|
||||
->orderBy('catalog_items.group_order')
|
||||
->orderBy('catalog_items.id'),
|
||||
};
|
||||
}
|
||||
|
||||
private function paginateItems(
|
||||
FeaturedGroup $featuredGroup,
|
||||
Tenant $tenant,
|
||||
int $page,
|
||||
): LengthAwarePaginator {
|
||||
$paginator = $this->itemsQuery($featuredGroup, $tenant)->paginate(
|
||||
perPage: self::ITEMS_PER_PAGE,
|
||||
pageName: 'page',
|
||||
page: $page,
|
||||
);
|
||||
|
||||
return $paginator->withPath(route('catalog.featured-groups.items.index', [
|
||||
'tenant' => $featuredGroup->tenant_code,
|
||||
'featuredGroup' => $featuredGroup->id,
|
||||
]));
|
||||
}
|
||||
|
||||
private function attachGroup(iterable $items, FeaturedGroup $featuredGroup): void
|
||||
{
|
||||
foreach ($items as $item) {
|
||||
$item->setRelation('featuredGroup', $featuredGroup);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Services;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Enums\FeaturedGroupSource;
|
||||
use App\Domains\Commerce\Catalog\Enums\GroupLayout;
|
||||
use App\Domains\Commerce\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Commerce\Catalog\Models\Category;
|
||||
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class OnTicketFeaturedGroupService
|
||||
{
|
||||
/** @return Collection<int, FeaturedGroup> */
|
||||
public function forTenant(Tenant $tenant): Collection
|
||||
{
|
||||
return FeaturedGroup::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('source_type', FeaturedGroupSource::Category)
|
||||
->whereHas('category', fn ($query) => $query->where('tenant_code', $tenant->codigo))
|
||||
->with('category')
|
||||
->orderBy('group_order')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
/** @param array{category_name: string, is_featured: bool} $data */
|
||||
public function create(Tenant $tenant, array $data): FeaturedGroup
|
||||
{
|
||||
return DB::transaction(function () use ($tenant, $data): FeaturedGroup {
|
||||
$category = $tenant->categories()->create([
|
||||
'nombre' => $data['category_name'],
|
||||
]);
|
||||
|
||||
$featuredGroup = FeaturedGroup::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'source_type' => FeaturedGroupSource::Category,
|
||||
'category_id' => $category->id,
|
||||
'product_layout' => $this->productLayout($data['is_featured']),
|
||||
'group_layout' => GroupLayout::Paginated,
|
||||
'group_name' => $data['category_name'],
|
||||
'group_order' => $this->nextOrder($tenant),
|
||||
]);
|
||||
|
||||
return $featuredGroup->setRelation('category', $category);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array{category_name: string, is_featured: bool} $data */
|
||||
public function update(
|
||||
Tenant $tenant,
|
||||
FeaturedGroup $featuredGroup,
|
||||
array $data,
|
||||
): FeaturedGroup {
|
||||
return DB::transaction(function () use ($tenant, $featuredGroup, $data): FeaturedGroup {
|
||||
$featuredGroup = FeaturedGroup::query()
|
||||
->whereKey($featuredGroup->getKey())
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('source_type', FeaturedGroupSource::Category)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$category = Category::query()
|
||||
->whereKey($featuredGroup->category_id)
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$category->update(['nombre' => $data['category_name']]);
|
||||
$featuredGroup->update([
|
||||
'group_name' => $data['category_name'],
|
||||
'product_layout' => $this->productLayout($data['is_featured']),
|
||||
'group_layout' => GroupLayout::Paginated,
|
||||
]);
|
||||
|
||||
return $featuredGroup->setRelation('category', $category);
|
||||
});
|
||||
}
|
||||
|
||||
private function productLayout(bool $isFeatured): ProductLayout
|
||||
{
|
||||
return $isFeatured ? ProductLayout::Row : ProductLayout::ColumnWithCart;
|
||||
}
|
||||
|
||||
private function nextOrder(Tenant $tenant): int
|
||||
{
|
||||
$maximumOrder = FeaturedGroup::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->max('group_order');
|
||||
|
||||
return $maximumOrder === null ? 0 : ((int) $maximumOrder) + 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Services;
|
||||
|
||||
use App\Domains\Commerce\Cart\Models\Cart;
|
||||
use App\Domains\Commerce\Cart\Models\CartItem;
|
||||
use App\Domains\Commerce\Catalog\Exceptions\StockReservationExpiredException;
|
||||
use App\Domains\Commerce\Catalog\Models\Inventory;
|
||||
use App\Domains\Commerce\Catalog\Models\StockReservation;
|
||||
use App\Domains\Commerce\Catalog\Models\StockReservationLine;
|
||||
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class StockReservationService
|
||||
{
|
||||
public const REASON_CART_EMPTY = 'cart_empty';
|
||||
|
||||
public const REASON_CART_CHANGED = 'cart_changed';
|
||||
|
||||
public const REASON_EVENT_DATE_RESCHEDULED = 'event_date_rescheduled';
|
||||
|
||||
public const REASON_EVENT_DATE_SUSPENDED = 'event_date_suspended';
|
||||
|
||||
public const REASON_PURCHASE_SUPERSEDED = 'purchase_superseded';
|
||||
|
||||
public const REASON_PURCHASE_CANCELLED = 'purchase_cancelled';
|
||||
|
||||
public const REASON_PAYMENT_REJECTED = 'payment_rejected';
|
||||
|
||||
public const REASON_MANUAL_RELEASE = 'manual_release';
|
||||
|
||||
public function __construct(
|
||||
private readonly CatalogInventoryService $inventory,
|
||||
) {}
|
||||
|
||||
public function syncCart(Cart $cart): ?StockReservation
|
||||
{
|
||||
return DB::transaction(function () use ($cart): ?StockReservation {
|
||||
/** @var Cart $lockedCart */
|
||||
$lockedCart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
|
||||
$items = $lockedCart->items()->orderBy('id')->lockForUpdate()->get();
|
||||
$this->loadSelections($items);
|
||||
$requirements = $this->requirementsForItems($items);
|
||||
|
||||
$reservation = $lockedCart->current_stock_reservation_id === null
|
||||
? null
|
||||
: StockReservation::query()->lockForUpdate()->find($lockedCart->current_stock_reservation_id);
|
||||
|
||||
if ($reservation !== null) {
|
||||
$this->assertUsableCartReservation($reservation);
|
||||
}
|
||||
|
||||
if ($requirements === []) {
|
||||
if ($reservation !== null && $reservation->status === StockReservation::STATUS_ACTIVE) {
|
||||
$this->finalizeLocked(
|
||||
$reservation,
|
||||
StockReservation::STATUS_RELEASED,
|
||||
self::REASON_CART_EMPTY,
|
||||
);
|
||||
}
|
||||
|
||||
$lockedCart->update(['current_stock_reservation_id' => null]);
|
||||
$cart->current_stock_reservation_id = null;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($reservation === null) {
|
||||
$reservation = StockReservation::query()->create([
|
||||
'status' => StockReservation::STATUS_ACTIVE,
|
||||
'expires_at' => $this->expiration(),
|
||||
]);
|
||||
$lockedCart->update(['current_stock_reservation_id' => $reservation->getKey()]);
|
||||
}
|
||||
|
||||
if (Purchase::query()->where('stock_reservation_id', $reservation->getKey())->exists()) {
|
||||
throw new \InvalidArgumentException('La reserva vinculada a una compra no se puede modificar.');
|
||||
}
|
||||
|
||||
$currentLines = StockReservationLine::query()
|
||||
->where('stock_reservation_id', $reservation->getKey())
|
||||
->orderBy('inventory_id')
|
||||
->lockForUpdate()
|
||||
->get()
|
||||
->keyBy('inventory_id');
|
||||
$inventoryIds = collect(array_keys($requirements))
|
||||
->merge($currentLines->keys())
|
||||
->map(fn ($id): int => (int) $id)
|
||||
->unique()
|
||||
->sort()
|
||||
->values();
|
||||
$inventories = Inventory::query()
|
||||
->whereKey($inventoryIds)
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
foreach ($inventoryIds as $inventoryId) {
|
||||
$inventory = $inventories->get($inventoryId)
|
||||
?? throw new \InvalidArgumentException('No se encontró el inventario requerido.');
|
||||
$previous = (int) ($currentLines->get($inventoryId)?->quantity ?? 0);
|
||||
$required = (int) ($requirements[$inventoryId]['quantity'] ?? 0);
|
||||
$delta = $required - $previous;
|
||||
|
||||
if ($delta > 0
|
||||
&& $requirements[$inventoryId]['tracks_inventory']
|
||||
&& $inventory->availableStock() < $delta) {
|
||||
throw new \InvalidArgumentException('No hay suficiente stock disponible para reservar el carrito.');
|
||||
}
|
||||
|
||||
if ($delta < 0 && $inventory->reserved_stock < abs($delta)) {
|
||||
throw new \InvalidArgumentException('La reserva de stock del carrito es inconsistente.');
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($inventoryIds as $inventoryId) {
|
||||
/** @var Inventory $inventory */
|
||||
$inventory = $inventories->get($inventoryId);
|
||||
$line = $currentLines->get($inventoryId);
|
||||
$previous = (int) ($line?->quantity ?? 0);
|
||||
$required = (int) ($requirements[$inventoryId]['quantity'] ?? 0);
|
||||
$delta = $required - $previous;
|
||||
|
||||
if ($delta > 0) {
|
||||
$inventory->reserve($delta, $requirements[$inventoryId]['tracks_inventory']);
|
||||
} elseif ($delta < 0) {
|
||||
$inventory->release(abs($delta));
|
||||
}
|
||||
|
||||
if ($required === 0) {
|
||||
$line?->delete();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
StockReservationLine::query()->updateOrCreate(
|
||||
[
|
||||
'stock_reservation_id' => $reservation->getKey(),
|
||||
'inventory_id' => $inventoryId,
|
||||
],
|
||||
[
|
||||
'quantity' => $required,
|
||||
'tracks_inventory' => $requirements[$inventoryId]['tracks_inventory'],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
$reservation->update([
|
||||
'expires_at' => $this->expiration(),
|
||||
'release_reason' => null,
|
||||
]);
|
||||
$cart->current_stock_reservation_id = $reservation->getKey();
|
||||
|
||||
return $reservation->fresh('lines');
|
||||
});
|
||||
}
|
||||
|
||||
public function attachToPurchase(
|
||||
Cart $cart,
|
||||
Purchase $purchase,
|
||||
Carbon $expiresAt,
|
||||
): StockReservation {
|
||||
return DB::transaction(function () use ($cart, $purchase, $expiresAt): StockReservation {
|
||||
/** @var Cart $lockedCart */
|
||||
$lockedCart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
|
||||
/** @var Purchase $lockedPurchase */
|
||||
$lockedPurchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||
|
||||
if ($lockedCart->current_stock_reservation_id === null) {
|
||||
throw new \InvalidArgumentException('El carrito no tiene una reserva de stock activa.');
|
||||
}
|
||||
|
||||
/** @var StockReservation $reservation */
|
||||
$reservation = StockReservation::query()->lockForUpdate()->findOrFail($lockedCart->current_stock_reservation_id);
|
||||
$this->assertUsableCartReservation($reservation);
|
||||
|
||||
$linkedPurchase = Purchase::query()
|
||||
->where('stock_reservation_id', $reservation->getKey())
|
||||
->whereKeyNot($lockedPurchase->getKey())
|
||||
->exists();
|
||||
if ($linkedPurchase) {
|
||||
throw new \InvalidArgumentException('La reserva de stock ya pertenece a otra compra.');
|
||||
}
|
||||
|
||||
$lockedPurchase->update(['stock_reservation_id' => $reservation->getKey()]);
|
||||
$reservation->update(['expires_at' => $expiresAt]);
|
||||
$purchase->stock_reservation_id = $reservation->getKey();
|
||||
$cart->current_stock_reservation_id = $reservation->getKey();
|
||||
|
||||
return $reservation->fresh('lines');
|
||||
});
|
||||
}
|
||||
|
||||
public function commit(Purchase $purchase): void
|
||||
{
|
||||
DB::transaction(function () use ($purchase): void {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||
if ($purchase->stock_reservation_id === null) {
|
||||
throw new \InvalidArgumentException('La compra no tiene una reserva de stock.');
|
||||
}
|
||||
|
||||
/** @var StockReservation $reservation */
|
||||
$reservation = StockReservation::query()->lockForUpdate()->findOrFail($purchase->stock_reservation_id);
|
||||
if ($reservation->status === StockReservation::STATUS_COMMITTED) {
|
||||
return;
|
||||
}
|
||||
if ($reservation->status !== StockReservation::STATUS_ACTIVE) {
|
||||
throw new \InvalidArgumentException('La reserva de stock no está activa.');
|
||||
}
|
||||
if ($reservation->expires_at !== null && ! $reservation->expires_at->isFuture()) {
|
||||
throw new StockReservationExpiredException;
|
||||
}
|
||||
|
||||
$lines = $this->lockLines($reservation);
|
||||
if ($lines->isEmpty()) {
|
||||
throw new \InvalidArgumentException('La reserva de stock no tiene inventarios.');
|
||||
}
|
||||
|
||||
$inventories = $this->lockInventories($lines);
|
||||
foreach ($lines as $line) {
|
||||
$inventory = $inventories->get($line->inventory_id)
|
||||
?? throw new \InvalidArgumentException('No se encontró el inventario reservado.');
|
||||
if ($inventory->reserved_stock < $line->quantity
|
||||
|| ($line->tracks_inventory && $inventory->real_stock < $line->quantity)) {
|
||||
throw new \InvalidArgumentException('La reserva de stock no alcanza para confirmar la compra.');
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($lines as $line) {
|
||||
$inventories->get($line->inventory_id)->buy(
|
||||
(int) $line->quantity,
|
||||
(bool) $line->tracks_inventory,
|
||||
);
|
||||
}
|
||||
|
||||
$reservation->update([
|
||||
'status' => StockReservation::STATUS_COMMITTED,
|
||||
'expires_at' => null,
|
||||
'committed_at' => now(),
|
||||
'released_at' => null,
|
||||
'expired_at' => null,
|
||||
'release_reason' => null,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
public function releaseForPurchase(
|
||||
Purchase $purchase,
|
||||
string $status = StockReservation::STATUS_RELEASED,
|
||||
?string $reason = null,
|
||||
): void {
|
||||
DB::transaction(function () use ($purchase, $status, $reason): void {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||
if ($purchase->stock_reservation_id === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var StockReservation|null $reservation */
|
||||
$reservation = StockReservation::query()->lockForUpdate()->find($purchase->stock_reservation_id);
|
||||
if ($reservation !== null) {
|
||||
$this->finalizeLocked($reservation, $status, $reason);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function returnToCart(Purchase $purchase, Cart $cart): StockReservation
|
||||
{
|
||||
return DB::transaction(function () use ($purchase, $cart): StockReservation {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||
/** @var Cart $cart */
|
||||
$cart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
|
||||
|
||||
if ($purchase->stock_reservation_id === null
|
||||
|| $cart->current_stock_reservation_id !== $purchase->stock_reservation_id) {
|
||||
throw new \InvalidArgumentException('La compra y el carrito no comparten la reserva activa.');
|
||||
}
|
||||
|
||||
/** @var StockReservation $reservation */
|
||||
$reservation = StockReservation::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($purchase->stock_reservation_id);
|
||||
$this->assertUsableCartReservation($reservation);
|
||||
|
||||
$purchase->update(['stock_reservation_id' => null]);
|
||||
$cart->update(['current_purchase_id' => null]);
|
||||
$reservation->update(['expires_at' => $this->expiration()]);
|
||||
|
||||
return $reservation->fresh('lines');
|
||||
});
|
||||
}
|
||||
|
||||
public function assertCartReservationUsable(Cart $cart): void
|
||||
{
|
||||
DB::transaction(function () use ($cart): void {
|
||||
/** @var Cart $cart */
|
||||
$cart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
|
||||
if ($cart->current_stock_reservation_id === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var StockReservation $reservation */
|
||||
$reservation = StockReservation::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($cart->current_stock_reservation_id);
|
||||
$this->assertUsableCartReservation($reservation);
|
||||
});
|
||||
}
|
||||
|
||||
public function releaseCurrentCartReservation(
|
||||
Cart $cart,
|
||||
string $reason = self::REASON_CART_CHANGED,
|
||||
): void {
|
||||
DB::transaction(function () use ($cart, $reason): void {
|
||||
/** @var Cart $cart */
|
||||
$cart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
|
||||
if ($cart->current_stock_reservation_id === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var StockReservation|null $reservation */
|
||||
$reservation = StockReservation::query()->lockForUpdate()->find($cart->current_stock_reservation_id);
|
||||
if ($reservation !== null) {
|
||||
$this->finalizeLocked($reservation, StockReservation::STATUS_RELEASED, $reason);
|
||||
}
|
||||
$cart->update(['current_stock_reservation_id' => null]);
|
||||
});
|
||||
}
|
||||
|
||||
public function expire(StockReservation $reservation): void
|
||||
{
|
||||
DB::transaction(function () use ($reservation): void {
|
||||
/** @var StockReservation $reservation */
|
||||
$reservation = StockReservation::query()->lockForUpdate()->findOrFail($reservation->getKey());
|
||||
if ($reservation->status !== StockReservation::STATUS_ACTIVE
|
||||
|| $reservation->expires_at === null
|
||||
|| $reservation->expires_at->isFuture()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->finalizeLocked($reservation, StockReservation::STATUS_EXPIRED, null);
|
||||
});
|
||||
}
|
||||
|
||||
public function clearExpirationForReview(Purchase $purchase): void
|
||||
{
|
||||
DB::transaction(function () use ($purchase): void {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||
if ($purchase->stock_reservation_id === null) {
|
||||
throw new \InvalidArgumentException('La compra no tiene una reserva de stock.');
|
||||
}
|
||||
|
||||
/** @var StockReservation $reservation */
|
||||
$reservation = StockReservation::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($purchase->stock_reservation_id);
|
||||
if ($reservation->status !== StockReservation::STATUS_ACTIVE) {
|
||||
throw new \InvalidArgumentException('La reserva de stock no está activa.');
|
||||
}
|
||||
if ($reservation->expires_at !== null && ! $reservation->expires_at->isFuture()) {
|
||||
throw new StockReservationExpiredException;
|
||||
}
|
||||
|
||||
$reservation->update(['expires_at' => null]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, CartItem> $items
|
||||
* @return array<int, array{quantity: int, tracks_inventory: bool}>
|
||||
*/
|
||||
private function requirementsForItems(Collection $items): array
|
||||
{
|
||||
$requirements = [];
|
||||
foreach ($items as $item) {
|
||||
$selection = $item->selectedItem();
|
||||
if ($selection === null) {
|
||||
throw new \InvalidArgumentException('El carrito contiene un item de catálogo inexistente.');
|
||||
}
|
||||
|
||||
foreach ($this->inventory->detailedRequirementsFor($selection, (int) $item->cantidad) as $inventoryId => $requirement) {
|
||||
if (isset($requirements[$inventoryId])) {
|
||||
$requirements[$inventoryId]['quantity'] += $requirement['quantity'];
|
||||
$requirements[$inventoryId]['tracks_inventory'] =
|
||||
$requirements[$inventoryId]['tracks_inventory'] || $requirement['tracks_inventory'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$requirements[$inventoryId] = $requirement;
|
||||
}
|
||||
}
|
||||
|
||||
ksort($requirements);
|
||||
|
||||
return $requirements;
|
||||
}
|
||||
|
||||
/** @param Collection<int, CartItem> $items */
|
||||
private function loadSelections(Collection $items): void
|
||||
{
|
||||
$items->load([
|
||||
'catalogItem.inventory',
|
||||
'catalogItem.bundleComponents.catalogItem.inventory',
|
||||
'catalogItem.bundleComponents.variant.inventory',
|
||||
'catalogItem.bundleComponents.variant.catalogItem',
|
||||
'variant.inventory',
|
||||
'variant.catalogItem',
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return Collection<int, StockReservationLine> */
|
||||
private function lockLines(StockReservation $reservation): Collection
|
||||
{
|
||||
return StockReservationLine::query()
|
||||
->where('stock_reservation_id', $reservation->getKey())
|
||||
->orderBy('inventory_id')
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, StockReservationLine> $lines
|
||||
* @return Collection<int, Inventory>
|
||||
*/
|
||||
private function lockInventories(Collection $lines): Collection
|
||||
{
|
||||
return Inventory::query()
|
||||
->whereKey($lines->pluck('inventory_id'))
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get()
|
||||
->keyBy('id');
|
||||
}
|
||||
|
||||
private function finalizeLocked(
|
||||
StockReservation $reservation,
|
||||
string $status,
|
||||
?string $reason,
|
||||
): void {
|
||||
if ($reservation->status !== StockReservation::STATUS_ACTIVE) {
|
||||
return;
|
||||
}
|
||||
if (! in_array($status, [StockReservation::STATUS_RELEASED, StockReservation::STATUS_EXPIRED], true)) {
|
||||
throw new \InvalidArgumentException('El estado final de la reserva no es válido.');
|
||||
}
|
||||
|
||||
$lines = $this->lockLines($reservation);
|
||||
$inventories = $this->lockInventories($lines);
|
||||
foreach ($lines as $line) {
|
||||
$inventory = $inventories->get($line->inventory_id)
|
||||
?? throw new \InvalidArgumentException('No se encontró el inventario reservado.');
|
||||
$inventory->release((int) $line->quantity);
|
||||
}
|
||||
|
||||
$now = now();
|
||||
$reservation->update([
|
||||
'status' => $status,
|
||||
'expires_at' => null,
|
||||
'released_at' => $status === StockReservation::STATUS_RELEASED ? $now : null,
|
||||
'expired_at' => $status === StockReservation::STATUS_EXPIRED ? $now : null,
|
||||
'release_reason' => $status === StockReservation::STATUS_RELEASED ? $reason : null,
|
||||
]);
|
||||
|
||||
if ($status === StockReservation::STATUS_RELEASED) {
|
||||
Cart::query()
|
||||
->where('current_stock_reservation_id', $reservation->getKey())
|
||||
->update(['current_stock_reservation_id' => null]);
|
||||
}
|
||||
}
|
||||
|
||||
private function assertUsableCartReservation(StockReservation $reservation): void
|
||||
{
|
||||
if ($reservation->status === StockReservation::STATUS_EXPIRED
|
||||
|| ($reservation->expires_at !== null && ! $reservation->expires_at->isFuture())) {
|
||||
throw new StockReservationExpiredException;
|
||||
}
|
||||
|
||||
if ($reservation->status !== StockReservation::STATUS_ACTIVE
|
||||
|| $reservation->expires_at === null) {
|
||||
throw new \InvalidArgumentException('La reserva de stock no está disponible para operar el carrito.');
|
||||
}
|
||||
}
|
||||
|
||||
private function expiration(): Carbon
|
||||
{
|
||||
return now()->addMinutes(
|
||||
max(1, (int) config('catalog.stock_reservation_expiration_minutes', 30)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Services;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Models\BundleComponent;
|
||||
use App\Domains\Commerce\Catalog\Models\Inventory;
|
||||
use App\Domains\Commerce\Catalog\Models\StockReservation;
|
||||
use App\Domains\Commerce\Catalog\Models\StockReservationLine;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use App\Domains\Ticketing\Event\Models\EventDate;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class VariantReplacementService
|
||||
{
|
||||
/** @return Collection<int, Variant> */
|
||||
public function replaceEventDate(EventDate $source, EventDate $destination): Collection
|
||||
{
|
||||
$variants = Variant::query()
|
||||
->whereNull('sales_disabled_at')
|
||||
->whereNull('replaced_by_variant_id')
|
||||
->where(function ($query) use ($source): void {
|
||||
$query->where('event_date_id', $source->getKey())
|
||||
->orWhereHas('eventDates', fn ($eventDates) => $eventDates
|
||||
->where('event_dates.id', $source->getKey()));
|
||||
})
|
||||
->with(['eventDates', 'eventDate', 'definitions', 'allAttachments'])
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
return $variants->map(function (Variant $variant) use ($source, $destination): Variant {
|
||||
$destinationDateIds = $variant->selectedEventDates()
|
||||
->pluck('id')
|
||||
->map(fn ($id): int => (int) $id === (int) $source->getKey()
|
||||
? (int) $destination->getKey()
|
||||
: (int) $id)
|
||||
->unique()
|
||||
->sort()
|
||||
->values();
|
||||
|
||||
$replacement = $this->findEquivalent($variant, $destinationDateIds)
|
||||
?? $this->cloneWithDates($variant, $destinationDateIds);
|
||||
|
||||
$variant->update([
|
||||
'replaced_by_variant_id' => $replacement->getKey(),
|
||||
'sales_disabled_at' => now(),
|
||||
]);
|
||||
|
||||
BundleComponent::query()
|
||||
->where('component_variant_id', $variant->getKey())
|
||||
->update(['component_variant_id' => $replacement->getKey()]);
|
||||
|
||||
return $replacement;
|
||||
})->values();
|
||||
}
|
||||
|
||||
public function disableForSuspension(EventDate $eventDate): void
|
||||
{
|
||||
$variants = Variant::query()
|
||||
->whereNull('sales_disabled_at')
|
||||
->whereNull('replaced_by_variant_id')
|
||||
->where(function ($query) use ($eventDate): void {
|
||||
$query->where('event_date_id', $eventDate->getKey())
|
||||
->orWhereHas('eventDates', fn ($eventDates) => $eventDates
|
||||
->where('event_dates.id', $eventDate->getKey()));
|
||||
})
|
||||
->with(['eventDates', 'eventDate', 'definitions', 'allAttachments'])
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
foreach ($variants as $variant) {
|
||||
$remainingDateIds = $variant->selectedEventDates()
|
||||
->filter(fn (EventDate $date): bool => $date->suspended_at === null
|
||||
&& $date->rescheduled_to_event_date_id === null)
|
||||
->pluck('id')
|
||||
->map(fn ($id): int => (int) $id)
|
||||
->unique()
|
||||
->sort()
|
||||
->values();
|
||||
|
||||
if ($remainingDateIds->isEmpty()) {
|
||||
$variant->update(['sales_disabled_at' => now()]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$replacement = $this->findEquivalent($variant, $remainingDateIds);
|
||||
if ($replacement === null) {
|
||||
$replacement = $this->cloneWithDates($variant, $remainingDateIds);
|
||||
} else {
|
||||
$this->mergeInventoryInto($variant, $replacement);
|
||||
}
|
||||
|
||||
$variant->update([
|
||||
'replaced_by_variant_id' => $replacement->getKey(),
|
||||
'sales_disabled_at' => now(),
|
||||
]);
|
||||
|
||||
BundleComponent::query()
|
||||
->where('component_variant_id', $variant->getKey())
|
||||
->update(['component_variant_id' => $replacement->getKey()]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param Collection<int, int> $eventDateIds */
|
||||
private function findEquivalent(Variant $source, Collection $eventDateIds): ?Variant
|
||||
{
|
||||
$definitionSignature = $this->definitionSignature($source);
|
||||
$dateSignature = $eventDateIds->map(fn ($id): int => (int) $id)->sort()->values()->all();
|
||||
|
||||
return Variant::query()
|
||||
->where('catalog_item_id', $source->catalog_item_id)
|
||||
->whereKeyNot($source->getKey())
|
||||
->whereNull('sales_disabled_at')
|
||||
->whereNull('replaced_by_variant_id')
|
||||
->with(['eventDates', 'eventDate', 'definitions'])
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get()
|
||||
->first(fn (Variant $candidate): bool => $this->definitionSignature($candidate) === $definitionSignature
|
||||
&& $candidate->selectedEventDates()
|
||||
->pluck('id')
|
||||
->map(fn ($id): int => (int) $id)
|
||||
->sort()
|
||||
->values()
|
||||
->all() === $dateSignature
|
||||
);
|
||||
}
|
||||
|
||||
/** @param Collection<int, int> $eventDateIds */
|
||||
private function cloneWithDates(Variant $source, Collection $eventDateIds): Variant
|
||||
{
|
||||
$replacementInventory = $this->cloneInventory($source);
|
||||
$replacement = $source->replicate([
|
||||
'event_date_id',
|
||||
'inventory_id',
|
||||
'replaced_by_variant_id',
|
||||
'sales_disabled_at',
|
||||
]);
|
||||
$replacement->inventory_id = $replacementInventory->getKey();
|
||||
$replacement->event_date_id = $eventDateIds->count() === 1
|
||||
? $eventDateIds->first()
|
||||
: null;
|
||||
$replacement->save();
|
||||
$replacement->eventDates()->sync($eventDateIds->all());
|
||||
|
||||
$replacement->definitions()->createMany(
|
||||
$source->definitions
|
||||
->map(fn ($definition): array => [
|
||||
'item_attribute_id' => $definition->item_attribute_id,
|
||||
'value' => $definition->value,
|
||||
])
|
||||
->all(),
|
||||
);
|
||||
|
||||
$attachments = $source->allAttachments
|
||||
->mapWithKeys(fn ($attachment): array => [
|
||||
$attachment->getKey() => [
|
||||
'orden' => $attachment->pivot->orden,
|
||||
'is_enabled' => $attachment->pivot->is_enabled,
|
||||
],
|
||||
])
|
||||
->all();
|
||||
$replacement->allAttachments()->sync($attachments);
|
||||
|
||||
return $replacement->load(['eventDates', 'eventDate', 'definitions', 'allAttachments']);
|
||||
}
|
||||
|
||||
private function cloneInventory(Variant $source): Inventory
|
||||
{
|
||||
$activeLines = StockReservationLine::query()
|
||||
->where('inventory_id', $source->inventory_id)
|
||||
->whereHas('reservation', fn ($reservation) => $reservation
|
||||
->where('status', StockReservation::STATUS_ACTIVE))
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
$sourceInventory = Inventory::query()
|
||||
->whereKey($source->inventory_id)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
$reservedStock = (int) $activeLines->sum('quantity');
|
||||
|
||||
if ($sourceInventory->reserved_stock !== $reservedStock) {
|
||||
throw new \LogicException('El inventario reservado de la variante es inconsistente.');
|
||||
}
|
||||
|
||||
$replacementInventory = Inventory::query()->create([
|
||||
'sold_units' => $sourceInventory->sold_units,
|
||||
'refunded_units' => $sourceInventory->refunded_units,
|
||||
'reserved_stock' => $reservedStock,
|
||||
'real_stock' => $sourceInventory->real_stock,
|
||||
]);
|
||||
|
||||
if ($activeLines->isNotEmpty()) {
|
||||
StockReservationLine::query()
|
||||
->whereKey($activeLines->modelKeys())
|
||||
->update(['inventory_id' => $replacementInventory->getKey()]);
|
||||
}
|
||||
$sourceInventory->update(['reserved_stock' => 0]);
|
||||
|
||||
return $replacementInventory;
|
||||
}
|
||||
|
||||
private function mergeInventoryInto(Variant $source, Variant $destination): void
|
||||
{
|
||||
if ($source->inventory_id === $destination->inventory_id) {
|
||||
return;
|
||||
}
|
||||
|
||||
$inventories = Inventory::query()
|
||||
->whereKey([$source->inventory_id, $destination->inventory_id])
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get()
|
||||
->keyBy('id');
|
||||
$sourceInventory = $inventories->get($source->inventory_id);
|
||||
$destinationInventory = $inventories->get($destination->inventory_id);
|
||||
if ($sourceInventory === null || $destinationInventory === null) {
|
||||
throw new \LogicException('No se encontró el inventario de una variante.');
|
||||
}
|
||||
|
||||
$activeLines = StockReservationLine::query()
|
||||
->where('inventory_id', $source->inventory_id)
|
||||
->whereHas('reservation', fn ($reservation) => $reservation
|
||||
->where('status', StockReservation::STATUS_ACTIVE))
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
if ($sourceInventory->reserved_stock !== (int) $activeLines->sum('quantity')) {
|
||||
throw new \LogicException('El inventario reservado de la variante es inconsistente.');
|
||||
}
|
||||
|
||||
$destinationInventory->update([
|
||||
'real_stock' => $destinationInventory->real_stock + $sourceInventory->real_stock,
|
||||
'reserved_stock' => $destinationInventory->reserved_stock + $sourceInventory->reserved_stock,
|
||||
'sold_units' => $destinationInventory->sold_units + $sourceInventory->sold_units,
|
||||
'refunded_units' => $destinationInventory->refunded_units + $sourceInventory->refunded_units,
|
||||
]);
|
||||
if ($activeLines->isNotEmpty()) {
|
||||
StockReservationLine::query()
|
||||
->whereKey($activeLines->modelKeys())
|
||||
->update(['inventory_id' => $destinationInventory->getKey()]);
|
||||
}
|
||||
$sourceInventory->update([
|
||||
'real_stock' => 0,
|
||||
'reserved_stock' => 0,
|
||||
'sold_units' => 0,
|
||||
'refunded_units' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function definitionSignature(Variant $variant): array
|
||||
{
|
||||
return $variant->definitions
|
||||
->map(fn ($definition): string => $definition->item_attribute_id.'\0'.$definition->value)
|
||||
->sort()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Catalog\Services;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Commerce\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class VariantSelectionService
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $selectedValues
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function options(
|
||||
CatalogItem $catalogItem,
|
||||
array $selectedValues,
|
||||
?int $includedVariantId = null,
|
||||
): array {
|
||||
$catalogItem->load([
|
||||
'itemAttributes.attribute',
|
||||
'variants' => fn ($query) => $query->orderBy('id'),
|
||||
'variants.inventory',
|
||||
'variants.eventDate',
|
||||
'variants.eventDates',
|
||||
'variants.definitions' => fn ($query) => $query->orderBy('id'),
|
||||
'variants.definitions.itemAttribute.attribute.options',
|
||||
]);
|
||||
|
||||
$variants = $catalogItem->visibleVariants($includedVariantId)
|
||||
->values();
|
||||
$normalizedSelections = collect($selectedValues)
|
||||
->mapWithKeys(fn ($value, string $key): array => [$key => $this->normalizeValue($value)])
|
||||
->filter(fn ($value): bool => $value !== null && $value !== '' && $value !== [])
|
||||
->all();
|
||||
$matchingVariants = $variants
|
||||
->filter(fn (Variant $variant): bool => $this->matches($variant, $normalizedSelections))
|
||||
->values();
|
||||
$attributeKeys = $this->attributeKeys($catalogItem, $catalogItem->variants->values());
|
||||
$isComplete = $attributeKeys->isNotEmpty()
|
||||
&& $attributeKeys->every(fn (string $key): bool => array_key_exists($key, $normalizedSelections));
|
||||
$resolvedVariant = $isComplete && $matchingVariants->count() === 1
|
||||
? $matchingVariants->first()
|
||||
: null;
|
||||
|
||||
return [
|
||||
'variants' => $variants
|
||||
->map(fn (Variant $variant): array => $this->variantData($catalogItem, $variant))
|
||||
->values()
|
||||
->all(),
|
||||
'selectors' => $this->selectors(
|
||||
$catalogItem,
|
||||
$variants,
|
||||
$attributeKeys,
|
||||
$matchingVariants->isEmpty() ? [] : $normalizedSelections,
|
||||
),
|
||||
'selected_values' => (object) ($matchingVariants->isEmpty() ? [] : $normalizedSelections),
|
||||
'resolved_variant' => $resolvedVariant === null
|
||||
? null
|
||||
: $this->variantData($catalogItem, $resolvedVariant),
|
||||
'valid' => $matchingVariants->isNotEmpty(),
|
||||
'available_variant_count' => $variants->count(),
|
||||
'matching_variant_count' => $matchingVariants->count(),
|
||||
'price_range' => $this->priceRange($catalogItem, $variants),
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $selectedValues */
|
||||
private function matches(Variant $variant, array $selectedValues): bool
|
||||
{
|
||||
$variantValues = $variant->selectionValues();
|
||||
|
||||
foreach ($selectedValues as $key => $selectedValue) {
|
||||
if (! $variantValues->has($key)
|
||||
|| $this->valueKey($variantValues->get($key)) !== $this->valueKey($selectedValue)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @param Collection<int, Variant> $variants */
|
||||
private function attributeKeys(CatalogItem $catalogItem, Collection $variants): Collection
|
||||
{
|
||||
return $variants
|
||||
->flatMap(fn (Variant $variant): array => $variant
|
||||
->selectorOptions($catalogItem->itemAttributes)
|
||||
->keys()
|
||||
->all())
|
||||
->unique()
|
||||
->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Variant> $variants
|
||||
* @param Collection<int, string> $attributeKeys
|
||||
* @param array<string, mixed> $selectedValues
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private function selectors(
|
||||
CatalogItem $catalogItem,
|
||||
Collection $variants,
|
||||
Collection $attributeKeys,
|
||||
array $selectedValues,
|
||||
): array {
|
||||
return $attributeKeys
|
||||
->map(function (string $key, int $index) use (
|
||||
$catalogItem,
|
||||
$variants,
|
||||
$attributeKeys,
|
||||
$selectedValues,
|
||||
): array {
|
||||
$previousKeys = $attributeKeys->take($index);
|
||||
$previousSelections = collect($selectedValues)
|
||||
->only($previousKeys->all())
|
||||
->all();
|
||||
$compatibleVariants = $variants
|
||||
->filter(fn (Variant $variant): bool => $this->matches($variant, $previousSelections));
|
||||
|
||||
return [
|
||||
'key' => $key,
|
||||
'label' => $this->attributeLabel($catalogItem, $key),
|
||||
'options' => $this->optionsFor($catalogItem, $compatibleVariants, $key),
|
||||
'enabled' => $index === 0 || $previousKeys->every(
|
||||
fn (string $previousKey): bool => array_key_exists($previousKey, $selectedValues),
|
||||
),
|
||||
];
|
||||
})
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Variant> $variants
|
||||
* @return list<mixed>
|
||||
*/
|
||||
private function optionsFor(CatalogItem $catalogItem, Collection $variants, string $key): array
|
||||
{
|
||||
$options = [];
|
||||
$seen = [];
|
||||
|
||||
foreach ($variants as $variant) {
|
||||
$option = $variant->selectorOptions($catalogItem->itemAttributes)->get($key);
|
||||
if ($option === null || $option === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$optionKey = $this->valueKey($option);
|
||||
if (isset($seen[$optionKey])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$seen[$optionKey] = true;
|
||||
$options[] = $option;
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
private function attributeLabel(CatalogItem $catalogItem, string $key): string
|
||||
{
|
||||
if ($key === 'event_date') {
|
||||
return 'Fecha';
|
||||
}
|
||||
|
||||
return $catalogItem->itemAttributes
|
||||
->first(fn (ItemAttribute $itemAttribute): bool => $itemAttribute->attribute?->codigo === $key)
|
||||
?->attribute
|
||||
?->nombre ?? str($key)->headline()->toString();
|
||||
}
|
||||
|
||||
/** @param Collection<int, Variant> $variants */
|
||||
private function priceRange(CatalogItem $catalogItem, Collection $variants): array
|
||||
{
|
||||
$prices = $variants
|
||||
->map(fn (Variant $variant): float => $variant->getPrice())
|
||||
->whenEmpty(fn (Collection $prices): Collection => $prices->push($catalogItem->getPrice()));
|
||||
|
||||
return [
|
||||
'minimum' => number_format((float) $prices->min(), 2, '.', ''),
|
||||
'maximum' => number_format((float) $prices->max(), 2, '.', ''),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function variantData(CatalogItem $catalogItem, Variant $variant): array
|
||||
{
|
||||
return [
|
||||
'id' => $variant->id,
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory?->availableStock(),
|
||||
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
||||
];
|
||||
}
|
||||
|
||||
private function normalizeValue(mixed $value): mixed
|
||||
{
|
||||
if (is_array($value) && array_key_exists('value', $value)) {
|
||||
return (string) $value['value'];
|
||||
}
|
||||
|
||||
if (is_array($value)) {
|
||||
return array_map(fn ($item) => $this->normalizeValue($item), $value);
|
||||
}
|
||||
|
||||
return is_scalar($value) ? (string) $value : null;
|
||||
}
|
||||
|
||||
private function valueKey(mixed $value): string
|
||||
{
|
||||
$normalized = $this->normalizeValue($value);
|
||||
|
||||
if (is_array($normalized)) {
|
||||
sort($normalized);
|
||||
}
|
||||
|
||||
return json_encode($normalized, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
}
|
||||
36
app/Domains/Commerce/Catalog/documentacion/README.md
Normal file
36
app/Domains/Commerce/Catalog/documentacion/README.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Dominio Catalog
|
||||
|
||||
## Propósito
|
||||
|
||||
Modela y publica la oferta comercial del tenant: productos, variantes, categorías, marcas, atributos, inventario, bundles y grupos destacados.
|
||||
|
||||
## Modelo
|
||||
|
||||
- `CatalogItem` es la raíz del producto y se relaciona con tenant, categoría, marca, inventario, variantes, atributos, adjuntos y grupos destacados.
|
||||
- `Variant`, `ItemAttribute`, `Attribute`, `AttributeOption` y `VariantDefinition` describen opciones comercializables.
|
||||
- `Inventory` administra stock disponible, reservado y comprado.
|
||||
- `StockReservation` representa la reserva completa de un carrito o checkout, con estados `active`, `committed`, `released` y `expired`. Su `expires_at` es el único reloj del bloqueo. Al expirar, también pasan a `expired` la compra pagable y el carrito asociados dentro de la misma transacción. Sus estados terminales nunca se reactivan ni se reemplazan implícitamente. Sus `StockReservationLine` agregan la cantidad requerida por inventario, incluso cuando varios ítems o bundles consumen el mismo stock.
|
||||
- `Category` soporta jerarquía y categorías globales o propias del tenant.
|
||||
- `FeaturedGroup` y `FeaturedItem` organizan secciones destacadas.
|
||||
- `BundleComponent` representa los componentes de un paquete.
|
||||
|
||||
## Servicios
|
||||
|
||||
- `CatalogService`: alta, búsqueda, detalle, listado por categoría y eliminación.
|
||||
- `CatalogInventoryService`: consulta, reserva, libera y confirma inventario.
|
||||
- `StockReservationService`: sincroniza el carrito como conjunto, bloquea todos sus inventarios en orden estable y mantiene el ledger agregado consistente con `Inventory.reserved_stock`.
|
||||
- `ExpireStockReservationsService`: detecta en un único recorrido reservas vencidas de compras, carritos y huérfanas, y delega los efectos comerciales sin mezclar esas reglas con la liberación física del inventario.
|
||||
- `FeaturedGroupService`: pagina los ítems destacados para la tienda.
|
||||
- `OnTicketFeaturedGroupService`: administra grupos destacados del panel para sitios de tickets.
|
||||
|
||||
## Endpoints de tienda
|
||||
|
||||
Bajo `/tenants/{tenant:codigo}` se publican catálogo, búsqueda, categoría, detalle, alta de ítems y paginación de grupos destacados.
|
||||
|
||||
## Endpoints administrativos
|
||||
|
||||
Bajo `/v1/adminapp/tenant/featured-groups`, con `auth:sanctum` y `adminapp.tenant`, se listan, crean y actualizan grupos destacados.
|
||||
|
||||
## Dependencias y reglas
|
||||
|
||||
Usa `Attachable` para imágenes/archivos, `Tenant` para aislamiento y `Ticket`/`Event` para vigencia y fechas. `Cart` y `Purchase` consumen sus precios, variantes e inventario. Los cambios de stock deben pasar por `CatalogInventoryService` para conservar reservas y disponibilidad.
|
||||
15
app/Domains/Commerce/Catalog/routes/adminapp.php
Normal file
15
app/Domains/Commerce/Catalog/routes/adminapp.php
Normal file
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Commerce\Catalog\Controllers\AdminApp\OnTicketFeaturedGroupController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/adminapp/tenant')
|
||||
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||
->group(function (): void {
|
||||
Route::get('featured-groups', [OnTicketFeaturedGroupController::class, 'index'])
|
||||
->name('adminapp.featured-groups.index');
|
||||
Route::post('featured-groups', [OnTicketFeaturedGroupController::class, 'store'])
|
||||
->name('adminapp.featured-groups.store');
|
||||
Route::put('featured-groups/{featuredGroup}', [OnTicketFeaturedGroupController::class, 'update'])
|
||||
->name('adminapp.featured-groups.update');
|
||||
});
|
||||
@@ -1,12 +1,18 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Catalog\Controllers\CatalogController;
|
||||
use App\Domains\Commerce\Catalog\Controllers\CatalogController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
||||
Route::get('catalog', [CatalogController::class, 'index']);
|
||||
Route::get('catalog/featured-groups/{featuredGroup}/items', [CatalogController::class, 'featuredGroupItems'])
|
||||
->name('catalog.featured-groups.items.index');
|
||||
Route::get('catalog-items', [CatalogController::class, 'search'])
|
||||
->name('catalog-items.index');
|
||||
Route::get('categories/{category}', [CatalogController::class, 'category'])
|
||||
->name('categories.show');
|
||||
Route::get('catalog-items/{catalogItem}', [CatalogController::class, 'show']);
|
||||
Route::post('catalog-items', [CatalogController::class, 'store']);
|
||||
Route::post('catalog-items/{catalogItem}/variant-options', [CatalogController::class, 'variantOptions']);
|
||||
});
|
||||
|
||||
require __DIR__.'/adminapp.php';
|
||||
285
app/Domains/Commerce/Purchase/Controllers/PurchaseController.php
Normal file
285
app/Domains/Commerce/Purchase/Controllers/PurchaseController.php
Normal file
@@ -0,0 +1,285 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Purchase\Controllers;
|
||||
|
||||
use App\Shared\Integration\Services\TelepagosIntegrationService;
|
||||
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||
use App\Domains\Commerce\Purchase\Requests\PaymentIntentRequest;
|
||||
use App\Domains\Commerce\Purchase\Requests\StartCheckoutRequest;
|
||||
use App\Domains\Commerce\Purchase\Requests\UpdatePurchaseCustomerRequest;
|
||||
use App\Domains\Commerce\Purchase\Resources\PurchaseResource;
|
||||
use App\Domains\Commerce\Purchase\Services\Checkout\PurchaseResponseLoader;
|
||||
use App\Domains\Commerce\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Commerce\Purchase\Services\PurchaseStateGuard;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class PurchaseController extends Controller
|
||||
{
|
||||
public function index(Request $request, Tenant $tenant): JsonResponse
|
||||
{
|
||||
$statusParam = $request->query('status');
|
||||
$statuses = is_string($statusParam)
|
||||
? collect(explode(',', $statusParam))
|
||||
->map(fn (string $status): string => trim($status))
|
||||
->filter()
|
||||
->unique()
|
||||
->values()
|
||||
->all()
|
||||
: [];
|
||||
|
||||
return PurchaseResource::collection(
|
||||
Purchase::query()
|
||||
->with('stockReservation')
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('user_id', $request->user()->id)
|
||||
->when($statuses !== [], fn ($query) => $query->whereIn('status', $statuses))
|
||||
->orderBy('status')
|
||||
->latest()
|
||||
->paginateFromRequest()
|
||||
)->response();
|
||||
}
|
||||
|
||||
public function startCheckout(
|
||||
StartCheckoutRequest $request,
|
||||
Tenant $tenant,
|
||||
CheckoutService $checkoutService,
|
||||
): JsonResponse {
|
||||
$data = $request->validated();
|
||||
|
||||
$purchase = $checkoutService->startCheckout(
|
||||
$tenant,
|
||||
$request->user()->id,
|
||||
$data
|
||||
);
|
||||
|
||||
return PurchaseResource::make($purchase)->response()->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function show(
|
||||
Request $request,
|
||||
Tenant $tenant,
|
||||
Purchase $compra,
|
||||
PurchaseResponseLoader $responses,
|
||||
): PurchaseResource {
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
$compra->loadMissing('items')->loadCount('tickets');
|
||||
$responses->load($compra);
|
||||
|
||||
return PurchaseResource::make($compra);
|
||||
}
|
||||
|
||||
public function updateCustomerData(
|
||||
UpdatePurchaseCustomerRequest $request,
|
||||
Tenant $tenant,
|
||||
Purchase $compra,
|
||||
CheckoutService $checkoutService,
|
||||
): PurchaseResource {
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$checkoutService->updateCustomerData($compra, $request->validated()),
|
||||
);
|
||||
}
|
||||
|
||||
public function paymentIntent(
|
||||
PaymentIntentRequest $request,
|
||||
Tenant $tenant,
|
||||
Purchase $compra,
|
||||
PurchaseStateGuard $purchaseState,
|
||||
): JsonResponse {
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
$method = $request->validated('method');
|
||||
$transferPayerDni = $method === 'transfer'
|
||||
? preg_replace('/\D+/', '', (string) $request->validated('transfer_payer_dni'))
|
||||
: null;
|
||||
|
||||
$updated = DB::transaction(function () use (
|
||||
$compra,
|
||||
$method,
|
||||
$purchaseState,
|
||||
$transferPayerDni,
|
||||
): bool {
|
||||
/** @var Purchase|null $purchase */
|
||||
$purchase = Purchase::query()
|
||||
->whereKey($compra->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($purchase === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$purchaseState->assertNotExpired($purchase);
|
||||
|
||||
if (
|
||||
! in_array($purchase->status, [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$purchaseState->lockCurrentCart($purchase);
|
||||
|
||||
$purchaseUpdate = [
|
||||
'payment_method' => $method,
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'total' => $purchase->calculateCurrentTotalAmount(),
|
||||
];
|
||||
|
||||
if ($transferPayerDni !== null) {
|
||||
$purchaseUpdate['transfer_payer_dni'] = $transferPayerDni;
|
||||
}
|
||||
$purchase->update($purchaseUpdate);
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
if (! $updated) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => __('api.purchase.not_available_for_payment'),
|
||||
]);
|
||||
}
|
||||
|
||||
$compra->refresh();
|
||||
$totalAmount = (float) $compra->total;
|
||||
|
||||
if ($method === 'transfer') {
|
||||
$telepagosService = new TelepagosIntegrationService;
|
||||
$telepagosService->forTenant($tenant->codigo);
|
||||
|
||||
try {
|
||||
$accountInfo = $telepagosService->getAccountInfo();
|
||||
|
||||
Log::channel('telepagos')->info('Telepagos account information retrieved.', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'purchase_id' => $compra->id,
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'payment_method' => 'transfer',
|
||||
'transfer_data' => [
|
||||
'titular' => $accountInfo['holder'] ?? null,
|
||||
'cvu' => $accountInfo['cvu'] ?? null,
|
||||
'alias' => $accountInfo['alias'] ?? null,
|
||||
'cuit' => $accountInfo['cuit'] ?? null,
|
||||
'entidad' => $accountInfo['entity'] ?? 'Telepagos S.A.',
|
||||
],
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
Log::channel('telepagos')->error('Unable to retrieve TelePagos account information.', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'purchase_id' => $compra->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'code' => 'integration.account_info_failed',
|
||||
'message' => __('api.integration.account_info_failed'),
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
if ($method === 'qr') {
|
||||
$telepagosService = new TelepagosIntegrationService;
|
||||
$telepagosService->forTenant($tenant->codigo);
|
||||
|
||||
try {
|
||||
Log::channel('telepagos')->info('Generating Telepagos QR.', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'purchase_id' => $compra->id,
|
||||
'amount' => $totalAmount,
|
||||
]);
|
||||
$qrResponse = $telepagosService->generateQr(
|
||||
$totalAmount,
|
||||
'Compra',
|
||||
"Compra #{$compra->id}"
|
||||
);
|
||||
|
||||
$telepagosQr = $compra->telepagosQr()->create([
|
||||
'qr_order_id' => (string) ($qrResponse['qr_order_id'] ?? ''),
|
||||
'qr_code' => $qrResponse['qr_code'] ?? '',
|
||||
]);
|
||||
|
||||
Log::channel('telepagos')->info('Telepagos QR generated successfully.', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'purchase_id' => $compra->id,
|
||||
'qr_order_id' => $telepagosQr->qr_order_id,
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
Log::channel('telepagos')->error('Unable to generate TelePagos QR code.', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'purchase_id' => $compra->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'code' => 'integration.qr_generation_failed',
|
||||
'message' => __('api.integration.qr_generation_failed'),
|
||||
], 500);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'payment_method' => 'qr',
|
||||
'qr_data' => [
|
||||
'qr_code' => $telepagosQr->qr_code,
|
||||
'qr_order_id' => $telepagosQr->qr_order_id,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'code' => 'integration.invalid_payment_method',
|
||||
'message' => __('api.integration.invalid_payment_method'),
|
||||
], 400);
|
||||
}
|
||||
|
||||
public function complete(Request $request, Tenant $tenant, Purchase $compra, CheckoutService $checkoutService): PurchaseResource
|
||||
{
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$checkoutService->completePurchase($compra)
|
||||
);
|
||||
}
|
||||
|
||||
public function submitForReview(
|
||||
Request $request,
|
||||
Tenant $tenant,
|
||||
Purchase $compra,
|
||||
CheckoutService $checkoutService,
|
||||
): PurchaseResource {
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$checkoutService->submitForReview($compra),
|
||||
);
|
||||
}
|
||||
|
||||
public function cancel(Request $request, Tenant $tenant, Purchase $compra, CheckoutService $checkoutService): PurchaseResource
|
||||
{
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$checkoutService->cancelPurchase($compra)
|
||||
);
|
||||
}
|
||||
|
||||
protected function resolveScopedPurchase(Tenant $tenant, int $userId, Purchase $purchase): Purchase
|
||||
{
|
||||
if ($purchase->tenant_codigo !== $tenant->codigo || $purchase->user_id !== $userId) {
|
||||
throw new NotFoundHttpException(__('api.errors.not_found'));
|
||||
}
|
||||
|
||||
return $purchase;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Events;
|
||||
namespace App\Domains\Commerce\Purchase\Events;
|
||||
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
@@ -10,5 +9,5 @@ class PurchasePaid
|
||||
{
|
||||
use Dispatchable, SerializesModels;
|
||||
|
||||
public function __construct(public readonly Purchase $purchase) {}
|
||||
public function __construct(public readonly int $purchaseId) {}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Purchase\Exceptions;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class InsufficientStockException extends RuntimeException
|
||||
{
|
||||
/**
|
||||
* @param array<int, array{
|
||||
* index: int,
|
||||
* catalog_item_id: int,
|
||||
* variant_id: int|null,
|
||||
* requested_quantity: int,
|
||||
* available_quantity: int,
|
||||
* message: string
|
||||
* }> $unavailableItems
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly array $unavailableItems,
|
||||
) {
|
||||
parent::__construct(
|
||||
collect($unavailableItems)->pluck('message')->unique()->implode(' '),
|
||||
);
|
||||
}
|
||||
|
||||
/** @return array<string, array<int, string>> */
|
||||
public function errors(): array
|
||||
{
|
||||
return collect($this->unavailableItems)
|
||||
->mapWithKeys(fn (array $item): array => [
|
||||
"direct_items.{$item['index']}.cantidad" => [$item['message']],
|
||||
])
|
||||
->all();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Purchase\Exceptions;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class PurchaseExpiredException extends RuntimeException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct(__('api.purchase.expired'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Purchase\Exceptions;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class PurchaseLimitExceededException extends ValidationException
|
||||
{
|
||||
public readonly int $catalogItemId;
|
||||
|
||||
public readonly string $catalogItemName;
|
||||
|
||||
public readonly int $maximumAddableQuantity;
|
||||
|
||||
public function __construct(CatalogItem $catalogItem, int $maximumAddableQuantity, string $field)
|
||||
{
|
||||
$this->catalogItemId = (int) $catalogItem->getKey();
|
||||
$this->catalogItemName = $catalogItem->nombre;
|
||||
$this->maximumAddableQuantity = $maximumAddableQuantity;
|
||||
|
||||
parent::__construct(validator([], []));
|
||||
|
||||
$message = trans_choice('api.purchase_limit.exceeded', $maximumAddableQuantity, [
|
||||
'max' => $maximumAddableQuantity,
|
||||
'product' => $this->catalogItemName,
|
||||
]);
|
||||
$this->message = $message;
|
||||
$this->validator->errors()->add($field, $message);
|
||||
}
|
||||
}
|
||||
279
app/Domains/Commerce/Purchase/Models/Purchase.php
Normal file
279
app/Domains/Commerce/Purchase/Models/Purchase.php
Normal file
@@ -0,0 +1,279 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Purchase\Models;
|
||||
|
||||
use App\Domains\Core\Auth\Models\User;
|
||||
use App\Domains\Commerce\Cart\Models\Cart;
|
||||
use App\Domains\Commerce\Catalog\Models\StockReservation;
|
||||
use App\Shared\Logging\Models\Concerns\LogsValueChanges;
|
||||
use App\Domains\Commerce\Purchase\Events\PurchasePaid;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticketing\Ticket\Models\Ticket;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
#[Fillable([
|
||||
'cart_id',
|
||||
'stock_reservation_id',
|
||||
'tenant_codigo',
|
||||
'user_id',
|
||||
'status',
|
||||
'payment_method',
|
||||
'total',
|
||||
'dni',
|
||||
'transfer_payer_dni',
|
||||
'telefono',
|
||||
'nombre_apellido',
|
||||
'email',
|
||||
])]
|
||||
class Purchase extends Model
|
||||
{
|
||||
use HasFactory, LogsValueChanges;
|
||||
|
||||
public const STATUS_CREATED = 'created';
|
||||
|
||||
public const STATUS_PENDING_PAYMENT = 'pending_payment';
|
||||
|
||||
public const STATUS_IN_REVIEW = 'in_review';
|
||||
|
||||
public const STATUS_PAID = 'paid';
|
||||
|
||||
public const STATUS_CANCELLED = 'cancelled';
|
||||
|
||||
public const STATUS_REJECTED = 'rejected';
|
||||
|
||||
public const STATUS_EXPIRED = 'expired';
|
||||
|
||||
public const STATUS_SUPERSEDED = 'superseded';
|
||||
|
||||
public const ADMIN_STATUS_INCOMPLETE = 'incomplete';
|
||||
|
||||
public const ADMIN_STATUS_AWAITING_PAYMENT = 'awaiting_payment';
|
||||
|
||||
public const ADMIN_STATUS_CONFIRMED = 'confirmed';
|
||||
|
||||
public const ADMIN_STATUS_CANCELLED = 'cancelled';
|
||||
|
||||
/** @return list<string> */
|
||||
public static function statuses(): array
|
||||
{
|
||||
return [
|
||||
self::STATUS_CREATED,
|
||||
self::STATUS_PENDING_PAYMENT,
|
||||
self::STATUS_IN_REVIEW,
|
||||
self::STATUS_PAID,
|
||||
self::STATUS_CANCELLED,
|
||||
self::STATUS_REJECTED,
|
||||
self::STATUS_EXPIRED,
|
||||
self::STATUS_SUPERSEDED,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{name: string, statuses: list<string>}>
|
||||
*/
|
||||
public static function adminStatuses(): array
|
||||
{
|
||||
return [
|
||||
self::ADMIN_STATUS_INCOMPLETE => [
|
||||
'name' => 'Por completar datos',
|
||||
'statuses' => [self::STATUS_CREATED],
|
||||
],
|
||||
self::ADMIN_STATUS_AWAITING_PAYMENT => [
|
||||
'name' => 'Esperando pago',
|
||||
'statuses' => [self::STATUS_PENDING_PAYMENT, self::STATUS_IN_REVIEW],
|
||||
],
|
||||
self::ADMIN_STATUS_CONFIRMED => [
|
||||
'name' => 'Confirmado',
|
||||
'statuses' => [self::STATUS_PAID],
|
||||
],
|
||||
self::ADMIN_STATUS_CANCELLED => [
|
||||
'name' => 'Anulado',
|
||||
'statuses' => [
|
||||
self::STATUS_CANCELLED,
|
||||
self::STATUS_REJECTED,
|
||||
self::STATUS_EXPIRED,
|
||||
self::STATUS_SUPERSEDED,
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public static function adminStatusCodes(): array
|
||||
{
|
||||
return array_keys(self::adminStatuses());
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public static function realStatusesForAdminStatus(string $adminStatus): array
|
||||
{
|
||||
return self::adminStatuses()[$adminStatus]['statuses'] ?? [];
|
||||
}
|
||||
|
||||
public static function adminStatusFor(string $realStatus): ?string
|
||||
{
|
||||
foreach (self::adminStatuses() as $adminStatus => $definition) {
|
||||
if (in_array($realStatus, $definition['statuses'], true)) {
|
||||
return $adminStatus;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static function adminStatusNameFor(string $realStatus): ?string
|
||||
{
|
||||
$adminStatus = self::adminStatusFor($realStatus);
|
||||
|
||||
return $adminStatus === null
|
||||
? null
|
||||
: self::adminStatuses()[$adminStatus]['name'];
|
||||
}
|
||||
|
||||
protected $table = 'compras';
|
||||
|
||||
/** @var array<int, string> */
|
||||
protected array $loggedAttributes = [
|
||||
'status',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'cart_id' => 'integer',
|
||||
'stock_reservation_id' => 'integer',
|
||||
'user_id' => 'integer',
|
||||
'total' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Tenant, $this>
|
||||
*/
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_codigo', 'codigo');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Cart, $this>
|
||||
*/
|
||||
public function cart(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Cart::class, 'cart_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<PurchaseItem, $this>
|
||||
*/
|
||||
public function items(): HasMany
|
||||
{
|
||||
return $this->hasMany(PurchaseItem::class, 'compra_id');
|
||||
}
|
||||
|
||||
/** @return HasManyThrough<Ticket, PurchaseItem, $this> */
|
||||
public function tickets(): HasManyThrough
|
||||
{
|
||||
return $this->hasManyThrough(
|
||||
Ticket::class,
|
||||
PurchaseItem::class,
|
||||
'compra_id',
|
||||
'source_purchase_item_id',
|
||||
);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<StockReservation, $this> */
|
||||
public function stockReservation(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(StockReservation::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasOne<TelepagosQr, $this>
|
||||
*/
|
||||
public function telepagosQr()
|
||||
{
|
||||
return $this->hasOne(TelepagosQr::class, 'compra_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<TelepagosPayment, $this>
|
||||
*/
|
||||
public function telepagosPayments(): HasMany
|
||||
{
|
||||
return $this->hasMany(TelepagosPayment::class, 'compra_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<TelepagosPaymentCandidate, $this> */
|
||||
public function telepagosPaymentCandidates(): HasMany
|
||||
{
|
||||
return $this->hasMany(TelepagosPaymentCandidate::class, 'compra_id');
|
||||
}
|
||||
|
||||
public function getTotalAmount(): float
|
||||
{
|
||||
if ($this->total !== null) {
|
||||
return (float) $this->total;
|
||||
}
|
||||
|
||||
return $this->calculateCurrentTotalAmount();
|
||||
}
|
||||
|
||||
public function calculateCurrentTotalAmount(): float
|
||||
{
|
||||
if ($this->relationLoaded('items') && $this->getRelation('items')->isNotEmpty()) {
|
||||
return (float) $this->getRelation('items')->sum('total');
|
||||
}
|
||||
|
||||
return (float) $this->items()->sum('total');
|
||||
}
|
||||
|
||||
protected function valueChangeTenantCode(): string
|
||||
{
|
||||
return $this->tenant_codigo;
|
||||
}
|
||||
|
||||
public function markAsPendingPayment(): void
|
||||
{
|
||||
$this->update([
|
||||
'status' => self::STATUS_PENDING_PAYMENT,
|
||||
]);
|
||||
}
|
||||
|
||||
public function markAsPaid(): void
|
||||
{
|
||||
DB::transaction(function (): void {
|
||||
$currentStatus = self::query()
|
||||
->whereKey($this->getKey())
|
||||
->lockForUpdate()
|
||||
->value('status');
|
||||
|
||||
if ($currentStatus === self::STATUS_PAID) {
|
||||
$this->status = self::STATUS_PAID;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->update([
|
||||
'status' => self::STATUS_PAID,
|
||||
]);
|
||||
|
||||
PurchasePaid::dispatch($this->getKey());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Models;
|
||||
namespace App\Domains\Commerce\Purchase\Models;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Shared\Attachable\Models\Attachment;
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use App\Domains\Ticketing\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticketing\Ticket\Models\TicketRefund;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
'compra_id',
|
||||
@@ -54,9 +59,33 @@ class PurchaseItem extends Model
|
||||
return $this->belongsTo(Purchase::class, 'compra_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<Ticket, $this> */
|
||||
public function tickets(): HasMany
|
||||
{
|
||||
return $this->hasMany(Ticket::class, 'source_purchase_item_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<TicketRefund, $this> */
|
||||
public function ticketRefunds(): HasMany
|
||||
{
|
||||
return $this->hasMany(TicketRefund::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Attachment, $this> */
|
||||
public function imageAttachment(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Attachment::class, 'image_attachment_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<CatalogItem, $this> */
|
||||
public function sourceCatalogItem(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CatalogItem::class, 'source_catalog_item_id')->withTrashed();
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Variant, $this> */
|
||||
public function sourceVariant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Variant::class, 'source_variant_id')->withTrashed();
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Models;
|
||||
namespace App\Domains\Commerce\Purchase\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
'compra_id',
|
||||
@@ -40,4 +41,10 @@ class TelepagosPayment extends Model
|
||||
{
|
||||
return $this->belongsTo(Purchase::class, 'compra_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<TelepagosPaymentCandidate, $this> */
|
||||
public function candidates(): HasMany
|
||||
{
|
||||
return $this->hasMany(TelepagosPaymentCandidate::class, 'telepagos_payment_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Purchase\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'telepagos_payment_id',
|
||||
'compra_id',
|
||||
'dni_matches',
|
||||
'dni_distance',
|
||||
'payment_dni',
|
||||
'purchase_dni',
|
||||
'amount_matches',
|
||||
'payment_amount',
|
||||
'purchase_amount',
|
||||
'amount_difference',
|
||||
'match_reason',
|
||||
'confidence',
|
||||
])]
|
||||
class TelepagosPaymentCandidate extends Model
|
||||
{
|
||||
protected $table = 'telepagos_payment_candidates';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'telepagos_payment_id' => 'integer',
|
||||
'compra_id' => 'integer',
|
||||
'dni_matches' => 'boolean',
|
||||
'dni_distance' => 'integer',
|
||||
'amount_matches' => 'boolean',
|
||||
'payment_amount' => 'decimal:2',
|
||||
'purchase_amount' => 'decimal:2',
|
||||
'amount_difference' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
public function payment(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(TelepagosPayment::class, 'telepagos_payment_id');
|
||||
}
|
||||
|
||||
public function purchase(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Purchase::class, 'compra_id');
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Models;
|
||||
namespace App\Domains\Commerce\Purchase\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Requests;
|
||||
namespace App\Domains\Commerce\Purchase\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Purchase\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class StartCheckoutRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'cart_id' => [
|
||||
'required_without:direct_items',
|
||||
Rule::prohibitedIf(fn (): bool => $this->has('direct_items')),
|
||||
'integer',
|
||||
'exists:carritos,id',
|
||||
],
|
||||
'direct_items' => [
|
||||
'required_without:cart_id',
|
||||
Rule::prohibitedIf(fn (): bool => $this->has('cart_id')),
|
||||
'array',
|
||||
'min:1',
|
||||
],
|
||||
'direct_items.*' => ['required', 'array'],
|
||||
'direct_items.*.catalog_item_id' => ['required', 'integer'],
|
||||
'direct_items.*.variant_id' => ['nullable', 'integer'],
|
||||
'direct_items.*.cantidad' => ['required', 'integer', 'min:1'],
|
||||
'dni' => ['prohibited'],
|
||||
'telefono' => ['prohibited'],
|
||||
'nombre_apellido' => ['prohibited'],
|
||||
'email' => ['prohibited'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Requests;
|
||||
namespace App\Domains\Commerce\Purchase\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class StorePurchaseRequest extends FormRequest
|
||||
class UpdatePurchaseCustomerRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -17,7 +17,6 @@ class StorePurchaseRequest extends FormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'cart_id' => ['required', 'integer', 'exists:carritos,id'],
|
||||
'dni' => ['required', 'string'],
|
||||
'telefono' => ['required', 'string'],
|
||||
'nombre_apellido' => ['required', 'string'],
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Purchase\Resources;
|
||||
|
||||
use App\Domains\Commerce\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Core\Tenant\Models\StorefrontWebsiteType;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin PurchaseItem */
|
||||
class PurchaseItemResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$tenant = $request->route('tenant');
|
||||
$usesEventSummary = $tenant instanceof Tenant
|
||||
&& $tenant->storefrontWebsiteType?->checkout_summary_type
|
||||
=== StorefrontWebsiteType::CHECKOUT_SUMMARY_EVENT;
|
||||
$displayImage = ! $tenant instanceof Tenant
|
||||
|| (! $usesEventSummary && $tenant->display_cart_item_images);
|
||||
|
||||
$imageUrl = $displayImage
|
||||
? $this->imageAttachment?->getTemporaryUrl(1440)
|
||||
: null;
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'quantity' => (int) $this->cantidad,
|
||||
'unit_price' => $this->formatMoney($this->precio_unitario),
|
||||
'line_total' => $this->formatMoney($this->total),
|
||||
'source_catalog_item_id' => $this->source_catalog_item_id,
|
||||
'source_variant_id' => $this->source_variant_id,
|
||||
'item_details' => [
|
||||
'nombre' => $this->item_nombre,
|
||||
'descripcion' => $this->descripcion,
|
||||
'slug' => $this->slug,
|
||||
'imagen' => $this->when(! $usesEventSummary, $imageUrl),
|
||||
'attributes' => $this->variant_attributes ?? [],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private function formatMoney(float|int|string|null $amount): string
|
||||
{
|
||||
return number_format((float) ($amount ?? 0), 2, '.', '');
|
||||
}
|
||||
}
|
||||
182
app/Domains/Commerce/Purchase/Resources/PurchaseResource.php
Normal file
182
app/Domains/Commerce/Purchase/Resources/PurchaseResource.php
Normal file
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Purchase\Resources;
|
||||
|
||||
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||
use App\Domains\Commerce\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Commerce\Purchase\Models\TelepagosPaymentCandidate;
|
||||
use App\Domains\Core\Tenant\Models\StorefrontWebsiteType;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticketing\Event\Models\Event;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin Purchase
|
||||
*/
|
||||
class PurchaseResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$serverTime = now();
|
||||
$expiresAt = $this->stockReservation?->expires_at;
|
||||
$items = $this->resource->relationLoaded('items')
|
||||
? $this->resource->getRelation('items')
|
||||
: collect();
|
||||
$ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes())
|
||||
? (int) $this->resource->getAttribute('tickets_count')
|
||||
: null;
|
||||
$paymentVerification = $this->resolvePaymentVerification();
|
||||
$tenant = $request->route('tenant');
|
||||
$usesEventSummary = $tenant instanceof Tenant
|
||||
&& $tenant->storefrontWebsiteType?->checkout_summary_type
|
||||
=== StorefrontWebsiteType::CHECKOUT_SUMMARY_EVENT;
|
||||
/** @var Event|null $checkoutEvent */
|
||||
$checkoutEvent = $usesEventSummary
|
||||
? $items
|
||||
->map(fn (PurchaseItem $item) => $item->sourceCatalogItem?->event)
|
||||
->filter()
|
||||
->unique('id')
|
||||
->first()
|
||||
: null;
|
||||
|
||||
$subtotal = $items->isNotEmpty()
|
||||
? $items->reduce(
|
||||
fn (float $carry, PurchaseItem $item): float => $carry + $this->resolveItemSubtotal($item),
|
||||
0.0,
|
||||
)
|
||||
: (float) ($this->total ?? 0);
|
||||
|
||||
$total = $this->status === Purchase::STATUS_PAID && $this->total !== null
|
||||
? (float) $this->total
|
||||
: ($items->isNotEmpty()
|
||||
? $items->reduce(
|
||||
fn (float $carry, PurchaseItem $item): float => $carry + $this->resolveItemTotal($item),
|
||||
0.0,
|
||||
)
|
||||
: (float) ($this->total ?? 0));
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'cart_id' => $this->cart_id,
|
||||
'tenant_codigo' => $this->tenant_codigo,
|
||||
'user_id' => $this->user_id,
|
||||
'created_at' => $this->created_at,
|
||||
'status' => $this->status,
|
||||
'payment_method' => $this->payment_method,
|
||||
'expires_at' => $expiresAt,
|
||||
'expires_in_seconds' => $expiresAt === null
|
||||
? null
|
||||
: max(0, $expiresAt->getTimestamp() - $serverTime->getTimestamp()),
|
||||
'server_time' => $serverTime,
|
||||
'dni' => $this->dni,
|
||||
'transfer_payer_dni' => $this->transfer_payer_dni,
|
||||
'telefono' => $this->telefono,
|
||||
'nombre_apellido' => $this->nombre_apellido,
|
||||
'email' => $this->email,
|
||||
'items_source' => $items->isNotEmpty() ? 'purchase' : null,
|
||||
'items' => PurchaseItemResource::collection($items),
|
||||
'event' => $this->when($usesEventSummary, fn () => $checkoutEvent === null
|
||||
? null
|
||||
: [
|
||||
'id' => $checkoutEvent->id,
|
||||
'title' => $checkoutEvent->title,
|
||||
'image' => $checkoutEvent->attachment?->getTemporaryUrl(1440),
|
||||
]),
|
||||
'tickets_count' => $this->when($ticketsCount !== null, $ticketsCount),
|
||||
'has_generated_tickets' => $this->when($ticketsCount !== null, $ticketsCount > 0),
|
||||
'payment_verification' => $this->when($paymentVerification !== null, $paymentVerification),
|
||||
'subtotal' => $this->formatMoney($subtotal),
|
||||
'total' => $this->formatMoney($total),
|
||||
];
|
||||
}
|
||||
|
||||
protected function resolveItemSubtotal(PurchaseItem $item): float
|
||||
{
|
||||
return (float) $item->precio_unitario * $item->cantidad;
|
||||
}
|
||||
|
||||
protected function resolveItemTotal(PurchaseItem $item): float
|
||||
{
|
||||
return (float) ($item->total ?? 0);
|
||||
}
|
||||
|
||||
protected function formatMoney(float|int|string|null $amount): string
|
||||
{
|
||||
return number_format((float) ($amount ?? 0), 2, '.', '');
|
||||
}
|
||||
|
||||
/** @return array<string, mixed>|null */
|
||||
private function resolvePaymentVerification(): ?array
|
||||
{
|
||||
if (
|
||||
$this->status !== Purchase::STATUS_IN_REVIEW
|
||||
|| $this->payment_method !== 'transfer'
|
||||
|| ! $this->resource->relationLoaded('telepagosPaymentCandidates')
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$candidates = $this->resource
|
||||
->getRelation('telepagosPaymentCandidates')
|
||||
->sort(fn (TelepagosPaymentCandidate $left, TelepagosPaymentCandidate $right): int => $this->comparePaymentCandidates($left, $right))
|
||||
->values();
|
||||
/** @var TelepagosPaymentCandidate|null $primary */
|
||||
$primary = $candidates->first();
|
||||
|
||||
return [
|
||||
'status' => $primary === null ? 'pending' : 'candidate',
|
||||
'candidate_count' => $candidates->count(),
|
||||
'primary' => $primary === null ? null : [
|
||||
'reason' => $primary->match_reason,
|
||||
'dni_distance' => $primary->dni_distance,
|
||||
'payment_amount' => $this->formatMoney($primary->payment_amount),
|
||||
'purchase_amount' => $this->formatMoney($primary->purchase_amount),
|
||||
'amount_difference' => $this->formatMoney($primary->amount_difference),
|
||||
'confidence' => $primary->confidence,
|
||||
'detected_at' => $primary->payment?->created_at?->toIso8601String(),
|
||||
],
|
||||
'reasons' => $candidates
|
||||
->pluck('match_reason')
|
||||
->unique()
|
||||
->values()
|
||||
->all(),
|
||||
];
|
||||
}
|
||||
|
||||
private function comparePaymentCandidates(
|
||||
TelepagosPaymentCandidate $left,
|
||||
TelepagosPaymentCandidate $right,
|
||||
): int {
|
||||
$reasonComparison = $this->paymentCandidateRank($left->match_reason)
|
||||
<=> $this->paymentCandidateRank($right->match_reason);
|
||||
|
||||
if ($reasonComparison !== 0) {
|
||||
return $reasonComparison;
|
||||
}
|
||||
|
||||
$differenceComparison = (float) $left->amount_difference <=> (float) $right->amount_difference;
|
||||
|
||||
if ($differenceComparison !== 0) {
|
||||
return $differenceComparison;
|
||||
}
|
||||
|
||||
$leftTimestamp = $left->payment?->created_at?->getTimestamp() ?? 0;
|
||||
$rightTimestamp = $right->payment?->created_at?->getTimestamp() ?? 0;
|
||||
|
||||
return ($rightTimestamp <=> $leftTimestamp) ?: ($right->id <=> $left->id);
|
||||
}
|
||||
|
||||
private function paymentCandidateRank(string $reason): int
|
||||
{
|
||||
return match ($reason) {
|
||||
'ambiguous_exact_match' => 0,
|
||||
'exact_dni_near_amount' => 1,
|
||||
'exact_amount_near_dni' => 2,
|
||||
default => 3,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Purchase\Services\Checkout;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Commerce\Catalog\Models\Inventory;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use App\Domains\Core\Tenant\Models\Tenant;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class CatalogSelectionResolver
|
||||
{
|
||||
public function resolve(
|
||||
Tenant $tenant,
|
||||
int $catalogItemId,
|
||||
?int $variantId,
|
||||
string $fieldPrefix = 'direct_items',
|
||||
): CatalogItem|Variant {
|
||||
/** @var CatalogItem|null $catalogItem */
|
||||
$catalogItem = CatalogItem::query()
|
||||
->whereKey($catalogItemId)
|
||||
->forTenantCatalog($tenant)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($catalogItem === null) {
|
||||
throw new NotFoundHttpException('Catalog item not found for tenant.');
|
||||
}
|
||||
|
||||
if (! $catalogItem->isSaleOpen()) {
|
||||
throw ValidationException::withMessages([
|
||||
"{$fieldPrefix}.catalog_item_id" => ['La venta de este producto finalizó.'],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($catalogItem->isBundle()) {
|
||||
if ($variantId !== null) {
|
||||
throw ValidationException::withMessages([
|
||||
"{$fieldPrefix}.variant_id" => __('api.cart.bundle_variant_forbidden'),
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $catalogItem->bundleComponents()->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
"{$fieldPrefix}.catalog_item_id" => __('api.cart.empty_bundle'),
|
||||
]);
|
||||
}
|
||||
|
||||
if ($catalogItem->bundleComponents()
|
||||
->whereNotNull('component_variant_id')
|
||||
->whereHas('variant', fn ($query) => $query
|
||||
->whereNotNull('sales_disabled_at')
|
||||
->orWhereNotNull('replaced_by_variant_id'))
|
||||
->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
"{$fieldPrefix}.catalog_item_id" => [__('api.cart.bundle_component_unavailable')],
|
||||
]);
|
||||
}
|
||||
|
||||
return $catalogItem;
|
||||
}
|
||||
|
||||
if ($variantId === null) {
|
||||
if ($catalogItem->inventory_id === null) {
|
||||
throw ValidationException::withMessages([
|
||||
"{$fieldPrefix}.variant_id" => __('api.cart.variant_required'),
|
||||
]);
|
||||
}
|
||||
|
||||
$catalogItem->setRelation(
|
||||
'inventory',
|
||||
Inventory::query()->whereKey($catalogItem->inventory_id)->lockForUpdate()->firstOrFail(),
|
||||
);
|
||||
|
||||
return $catalogItem;
|
||||
}
|
||||
|
||||
/** @var Variant|null $variant */
|
||||
$variant = Variant::query()
|
||||
->whereKey($variantId)
|
||||
->where('catalog_item_id', $catalogItem->id)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($variant === null) {
|
||||
throw new NotFoundHttpException('Variant not found for catalog item.');
|
||||
}
|
||||
|
||||
if (! $variant->isSellable()) {
|
||||
throw ValidationException::withMessages([
|
||||
"{$fieldPrefix}.variant_id" => [__('api.cart.variant_unavailable')],
|
||||
]);
|
||||
}
|
||||
|
||||
$variant->setRelation('catalogItem', $catalogItem);
|
||||
$variant->setRelation(
|
||||
'inventory',
|
||||
Inventory::query()->whereKey($variant->inventory_id)->lockForUpdate()->firstOrFail(),
|
||||
);
|
||||
|
||||
return $variant;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Purchase\Services\Checkout;
|
||||
|
||||
use App\Domains\Commerce\Cart\Models\CartItem;
|
||||
use App\Domains\Commerce\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||
use App\Domains\Commerce\Purchase\Services\PurchaseStateGuard;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class CompleteCheckoutService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly StockReservationService $reservations,
|
||||
private readonly SourceCartService $sourceCart,
|
||||
private readonly PurchaseStateGuard $purchaseState,
|
||||
) {}
|
||||
|
||||
public function complete(Purchase $purchase): Purchase
|
||||
{
|
||||
return DB::transaction(function () use ($purchase): Purchase {
|
||||
$purchase = $this->lockPurchase($purchase);
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
|
||||
if ($purchase->payment_method === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'payment_method' => __('api.purchase.payment_method_required'),
|
||||
]);
|
||||
}
|
||||
|
||||
if ($this->isTerminal($purchase)) {
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
|
||||
$this->purchaseState->lockCurrentCart($purchase);
|
||||
|
||||
$purchase->update([
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'total' => $purchase->calculateCurrentTotalAmount(),
|
||||
]);
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
});
|
||||
}
|
||||
|
||||
public function submitForReview(Purchase $purchase): Purchase
|
||||
{
|
||||
return DB::transaction(function () use ($purchase): Purchase {
|
||||
$purchase = $this->lockPurchase($purchase);
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
|
||||
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
|
||||
if ($purchase->status === Purchase::STATUS_IN_REVIEW) {
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
|
||||
$this->purchaseState->lockCurrentCart($purchase);
|
||||
|
||||
if ($purchase->status !== Purchase::STATUS_PENDING_PAYMENT) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => __('api.purchase.not_available_for_review'),
|
||||
]);
|
||||
}
|
||||
|
||||
$purchase->update([
|
||||
'status' => Purchase::STATUS_IN_REVIEW,
|
||||
]);
|
||||
$this->reservations->clearExpirationForReview($purchase);
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
});
|
||||
}
|
||||
|
||||
public function confirm(Purchase $purchase): void
|
||||
{
|
||||
DB::transaction(function () use ($purchase): void {
|
||||
$purchase = $this->lockPurchase($purchase);
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
|
||||
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (in_array($purchase->status, [
|
||||
Purchase::STATUS_CANCELLED,
|
||||
Purchase::STATUS_REJECTED,
|
||||
Purchase::STATUS_EXPIRED,
|
||||
Purchase::STATUS_SUPERSEDED,
|
||||
], true)) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => __('api.purchase.cannot_confirm'),
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $purchase->items()->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
}
|
||||
|
||||
$cart = $this->purchaseState->lockCurrentCart($purchase);
|
||||
|
||||
if ($cart->status === 'converted' && $cart->trashed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! in_array($cart->status, ['active', 'checkout'], true)) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
}
|
||||
|
||||
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
|
||||
if ($cartItems->isEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
}
|
||||
|
||||
$snapshotQuantities = $purchase->items()
|
||||
->lockForUpdate()
|
||||
->get(['source_catalog_item_id', 'source_variant_id', 'cantidad'])
|
||||
->groupBy(fn ($item): string => $this->itemKey(
|
||||
(int) $item->source_catalog_item_id,
|
||||
$item->source_variant_id === null ? null : (int) $item->source_variant_id,
|
||||
))
|
||||
->map(fn (Collection $items): int => (int) $items->sum('cantidad'))
|
||||
->sortKeys()
|
||||
->all();
|
||||
$cartQuantities = $cartItems
|
||||
->groupBy(fn (CartItem $item): string => $this->itemKey(
|
||||
(int) $item->catalog_item_id,
|
||||
$item->variant_id === null ? null : (int) $item->variant_id,
|
||||
))
|
||||
->map(fn (Collection $items): int => (int) $items->sum('cantidad'))
|
||||
->sortKeys()
|
||||
->all();
|
||||
|
||||
if ($snapshotQuantities !== $cartQuantities) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
}
|
||||
|
||||
$this->loadCartItems($cartItems);
|
||||
|
||||
foreach ($cartItems as $cartItem) {
|
||||
$selection = $cartItem->selectedItem();
|
||||
if ($selection === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
try {
|
||||
$this->reservations->commit($purchase);
|
||||
} catch (\InvalidArgumentException) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
}
|
||||
|
||||
$this->sourceCart->finalize($purchase);
|
||||
});
|
||||
}
|
||||
|
||||
private function isTerminal(Purchase $purchase): bool
|
||||
{
|
||||
return in_array($purchase->status, [
|
||||
Purchase::STATUS_PAID,
|
||||
Purchase::STATUS_IN_REVIEW,
|
||||
Purchase::STATUS_CANCELLED,
|
||||
Purchase::STATUS_REJECTED,
|
||||
Purchase::STATUS_EXPIRED,
|
||||
Purchase::STATUS_SUPERSEDED,
|
||||
], true);
|
||||
}
|
||||
|
||||
private function lockPurchase(Purchase $purchase): Purchase
|
||||
{
|
||||
/** @var Purchase */
|
||||
return Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||
}
|
||||
|
||||
private function loadPurchase(Purchase $purchase): Purchase
|
||||
{
|
||||
return $purchase->load(['items.imageAttachment', 'stockReservation']);
|
||||
}
|
||||
|
||||
private function itemKey(int $catalogItemId, ?int $variantId): string
|
||||
{
|
||||
return $catalogItemId.':'.($variantId ?? 'none');
|
||||
}
|
||||
|
||||
/** @param Collection<int, CartItem> $cartItems */
|
||||
private function loadCartItems(Collection $cartItems): void
|
||||
{
|
||||
$cartItems->load([
|
||||
'catalogItem.inventory',
|
||||
'catalogItem.attachments',
|
||||
'variant.inventory',
|
||||
'variant.attachments',
|
||||
'variant.catalogItem',
|
||||
'variant.definitions.itemAttribute.attribute',
|
||||
'variant.eventDates',
|
||||
'variant.eventDate',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Commerce\Purchase\Services\Checkout;
|
||||
|
||||
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||
use App\Domains\Commerce\Purchase\Services\PurchaseStateGuard;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class EditCheckoutService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly PurchaseResponseLoader $responses,
|
||||
private readonly PurchaseStateGuard $purchaseState,
|
||||
) {}
|
||||
|
||||
/** @param array<string, string> $customerData */
|
||||
public function updateCustomer(Purchase $purchase, array $customerData): Purchase
|
||||
{
|
||||
return DB::transaction(function () use ($purchase, $customerData): Purchase {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
|
||||
if (! in_array($purchase->status, [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => __('api.purchase.not_editable'),
|
||||
]);
|
||||
}
|
||||
|
||||
$this->purchaseState->lockCurrentCart($purchase);
|
||||
|
||||
$purchase->update($customerData);
|
||||
|
||||
return $this->responses->load($purchase);
|
||||
});
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user