Compare commits
247 Commits
feature/al
...
v1.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 |
@@ -8,6 +8,7 @@ PURCHASE_CHECKOUT_EXPIRATION_MINUTES=30
|
|||||||
PURCHASE_QR_EXPIRATION_MINUTES=15
|
PURCHASE_QR_EXPIRATION_MINUTES=15
|
||||||
PURCHASE_TELEPAGOS_EXPIRATION_MINUTES=30
|
PURCHASE_TELEPAGOS_EXPIRATION_MINUTES=30
|
||||||
PURCHASE_TRANSFER_EXPIRATION_MINUTES=1440
|
PURCHASE_TRANSFER_EXPIRATION_MINUTES=1440
|
||||||
|
PURCHASE_TRANSFER_CANDIDATE_AMOUNT_TOLERANCE_PERCENTAGE=5
|
||||||
STOCK_RESERVATION_EXPIRATION_MINUTES=30
|
STOCK_RESERVATION_EXPIRATION_MINUTES=30
|
||||||
FRONTEND_URLS=http://localhost:4200
|
FRONTEND_URLS=http://localhost:4200
|
||||||
|
|
||||||
@@ -31,6 +32,7 @@ AUTH_LOGIN_ATTEMPT_WINDOW_MINUTES=30
|
|||||||
AUTH_LOGIN_LOCK_MINUTES=15
|
AUTH_LOGIN_LOCK_MINUTES=15
|
||||||
AUTH_LOGIN_RATE_LIMIT_PER_MINUTE=10
|
AUTH_LOGIN_RATE_LIMIT_PER_MINUTE=10
|
||||||
AUTH_LOGIN_IP_RATE_LIMIT_PER_MINUTE=30
|
AUTH_LOGIN_IP_RATE_LIMIT_PER_MINUTE=30
|
||||||
|
AUTH_PASSWORD_RESET_EXPIRATION_MINUTES=60
|
||||||
|
|
||||||
LOG_CHANNEL=daily
|
LOG_CHANNEL=daily
|
||||||
LOG_STACK=single
|
LOG_STACK=single
|
||||||
@@ -41,6 +43,9 @@ TELEPAGOS_LOG_LEVEL=info
|
|||||||
TELEPAGOS_LOG_DAYS=30
|
TELEPAGOS_LOG_DAYS=30
|
||||||
COMMANDS_LOG_LEVEL=info
|
COMMANDS_LOG_LEVEL=info
|
||||||
COMMANDS_LOG_DAYS=30
|
COMMANDS_LOG_DAYS=30
|
||||||
|
EMAILS_LOG_LEVEL=info
|
||||||
|
EMAILS_LOG_DAYS=30
|
||||||
|
EMAIL_DELIVERY_LEASE_SECONDS=300
|
||||||
|
|
||||||
DB_CONNECTION=mysql
|
DB_CONNECTION=mysql
|
||||||
DB_HOST=127.0.0.1
|
DB_HOST=127.0.0.1
|
||||||
|
|||||||
54
AGENTS.md
54
AGENTS.md
@@ -1,19 +1,29 @@
|
|||||||
# Project Conventions
|
# 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
|
## 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
|
```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:
|
Supported folders inside each domain:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
app/Domains/<DomainName>/
|
app/Domains/<Area>/<DomainName>/
|
||||||
├── Models/
|
├── Models/
|
||||||
├── Controllers/
|
├── Controllers/
|
||||||
├── Requests/
|
├── Requests/
|
||||||
@@ -28,22 +38,28 @@ app/Domains/<DomainName>/
|
|||||||
|
|
||||||
- Root API routes live in `routes/api.php`.
|
- Root API routes live in `routes/api.php`.
|
||||||
- `routes/api.php` should act as an aggregator only.
|
- `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
|
## Namespaces
|
||||||
|
|
||||||
Use this namespace pattern:
|
Use this namespace pattern:
|
||||||
|
|
||||||
```php
|
```php
|
||||||
App\Domains\<DomainName>\Models
|
App\Domains\<Area>\<DomainName>\Models
|
||||||
App\Domains\<DomainName>\Controllers
|
App\Domains\<Area>\<DomainName>\Controllers
|
||||||
App\Domains\<DomainName>\Requests
|
App\Domains\<Area>\<DomainName>\Requests
|
||||||
App\Domains\<DomainName>\Resources
|
App\Domains\<Area>\<DomainName>\Resources
|
||||||
App\Domains\<DomainName>\Services
|
App\Domains\<Area>\<DomainName>\Services
|
||||||
App\Domains\<DomainName>\Policies
|
App\Domains\<Area>\<DomainName>\Policies
|
||||||
App\Domains\<DomainName>\Exceptions
|
App\Domains\<Area>\<DomainName>\Exceptions
|
||||||
```
|
```
|
||||||
|
|
||||||
|
For cross-cutting modules, use `App\Shared\<ModuleName>\...`. Reusable enums
|
||||||
|
and rules live directly under `App\Shared`.
|
||||||
|
|
||||||
## Responsibilities
|
## Responsibilities
|
||||||
|
|
||||||
- `Models/`: Eloquent models and model relationships.
|
- `Models/`: Eloquent models and model relationships.
|
||||||
@@ -74,13 +90,19 @@ App\Domains\<DomainName>\Exceptions
|
|||||||
- Namespace, folder, and class names must stay aligned.
|
- Namespace, folder, and class names must stay aligned.
|
||||||
- Route files should be named `api.php`.
|
- Route files should be named `api.php`.
|
||||||
|
|
||||||
## Current Domains
|
## Current Areas and Modules
|
||||||
|
|
||||||
- `Tenant`
|
- `Core`: `Administrator`, `Auth`, `Authorization`, `Bootstrap`, `Client`,
|
||||||
- `Product`
|
`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
|
## Notes For Future Changes
|
||||||
|
|
||||||
- New features should be added inside the corresponding domain first.
|
- 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`.
|
- Avoid placing new business code in `app/Http/Controllers` or `app/Models`.
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Bootstrap\Services;
|
|
||||||
|
|
||||||
use App\Domains\Tenant\Models\WebsiteType;
|
|
||||||
|
|
||||||
class AdminAppBootstrapService
|
|
||||||
{
|
|
||||||
/** @return array{website_type: WebsiteType} */
|
|
||||||
public function get(string $domain): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'website_type' => WebsiteType::query()
|
|
||||||
->with(['siteLogo', 'footerLogo'])
|
|
||||||
->where('dominio', $domain)
|
|
||||||
->firstOrFail(),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Bootstrap\Services;
|
|
||||||
|
|
||||||
use App\Domains\Tenant\Models\WebsiteType;
|
|
||||||
|
|
||||||
class ScannerBootstrapService
|
|
||||||
{
|
|
||||||
/** @return array{website_type: WebsiteType} */
|
|
||||||
public function get(string $domain): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'website_type' => WebsiteType::query()
|
|
||||||
->with(['siteLogo', 'footerLogo'])
|
|
||||||
->where('scanner_domain', $domain)
|
|
||||||
->firstOrFail(),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,123 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Cart\Services;
|
|
||||||
|
|
||||||
use App\Domains\Cart\Models\Cart;
|
|
||||||
use App\Domains\Cart\Models\CartItem;
|
|
||||||
use App\Domains\Catalog\Models\Inventory;
|
|
||||||
use App\Domains\Catalog\Models\StockReservation;
|
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
|
|
||||||
class ExpireCartReservationsService
|
|
||||||
{
|
|
||||||
public function expireOverdue(): int
|
|
||||||
{
|
|
||||||
$expiredItems = 0;
|
|
||||||
$lastCartItemId = 0;
|
|
||||||
|
|
||||||
do {
|
|
||||||
$cartItemIds = StockReservation::query()
|
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
|
||||||
->whereNull('purchase_id')
|
|
||||||
->whereNotNull('cart_item_id')
|
|
||||||
->whereNotNull('expires_at')
|
|
||||||
->where('expires_at', '<=', now())
|
|
||||||
->where('cart_item_id', '>', $lastCartItemId)
|
|
||||||
->whereHas('cartItem.cart', fn ($query) => $query->where('status', 'active'))
|
|
||||||
->select('cart_item_id')
|
|
||||||
->distinct()
|
|
||||||
->orderBy('cart_item_id')
|
|
||||||
->limit(500)
|
|
||||||
->pluck('cart_item_id');
|
|
||||||
|
|
||||||
foreach ($cartItemIds as $cartItemId) {
|
|
||||||
$lastCartItemId = (int) $cartItemId;
|
|
||||||
|
|
||||||
if ($this->expireCartItem($lastCartItemId)) {
|
|
||||||
$expiredItems++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} while ($cartItemIds->count() === 500);
|
|
||||||
|
|
||||||
return $expiredItems;
|
|
||||||
}
|
|
||||||
|
|
||||||
private function expireCartItem(int $cartItemId): bool
|
|
||||||
{
|
|
||||||
/** @var CartItem|null $candidate */
|
|
||||||
$candidate = CartItem::query()->select(['id', 'cart_id'])->find($cartItemId);
|
|
||||||
if ($candidate === null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return DB::transaction(function () use ($candidate, $cartItemId): bool {
|
|
||||||
/** @var Cart|null $cart */
|
|
||||||
$cart = Cart::query()
|
|
||||||
->whereKey($candidate->cart_id)
|
|
||||||
->where('status', 'active')
|
|
||||||
->lockForUpdate()
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if ($cart === null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @var CartItem|null $cartItem */
|
|
||||||
$cartItem = $cart->items()
|
|
||||||
->whereKey($cartItemId)
|
|
||||||
->lockForUpdate()
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if ($cartItem === null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$reservations = StockReservation::query()
|
|
||||||
->where('cart_item_id', $cartItem->getKey())
|
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
|
||||||
->orderBy('inventory_id')
|
|
||||||
->lockForUpdate()
|
|
||||||
->get();
|
|
||||||
|
|
||||||
if (
|
|
||||||
$reservations->isEmpty()
|
|
||||||
|| $reservations->contains(
|
|
||||||
fn (StockReservation $reservation): bool => $reservation->purchase_id !== null
|
|
||||||
|| $reservation->expires_at === null
|
|
||||||
|| $reservation->expires_at->isFuture(),
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$inventories = Inventory::query()
|
|
||||||
->whereKey($reservations->pluck('inventory_id'))
|
|
||||||
->orderBy('id')
|
|
||||||
->lockForUpdate()
|
|
||||||
->get()
|
|
||||||
->keyBy('id');
|
|
||||||
|
|
||||||
foreach ($reservations as $reservation) {
|
|
||||||
$inventory = $inventories->get($reservation->inventory_id)
|
|
||||||
?? throw new \InvalidArgumentException('No se encontro el inventario reservado.');
|
|
||||||
|
|
||||||
$inventory->release((int) $reservation->quantity);
|
|
||||||
$reservation->update([
|
|
||||||
'quantity' => 0,
|
|
||||||
'status' => StockReservation::STATUS_EXPIRED,
|
|
||||||
'expires_at' => null,
|
|
||||||
'released_at' => now(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$cartItem->delete();
|
|
||||||
|
|
||||||
if (! $cart->items()->exists()) {
|
|
||||||
$cart->update(['status' => 'expired']);
|
|
||||||
$cart->delete();
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
|
||||||
|
|
||||||
use App\Domains\Cart\Models\CartItem;
|
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
||||||
|
|
||||||
#[Fillable([
|
|
||||||
'inventory_id',
|
|
||||||
'cart_item_id',
|
|
||||||
'purchase_id',
|
|
||||||
'quantity',
|
|
||||||
'status',
|
|
||||||
'expires_at',
|
|
||||||
'committed_at',
|
|
||||||
'released_at',
|
|
||||||
])]
|
|
||||||
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 [
|
|
||||||
'inventory_id' => 'integer',
|
|
||||||
'cart_item_id' => 'integer',
|
|
||||||
'purchase_id' => 'integer',
|
|
||||||
'quantity' => 'integer',
|
|
||||||
'expires_at' => 'datetime',
|
|
||||||
'committed_at' => 'datetime',
|
|
||||||
'released_at' => 'datetime',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return BelongsTo<Inventory, $this> */
|
|
||||||
public function inventory(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(Inventory::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return BelongsTo<CartItem, $this> */
|
|
||||||
public function cartItem(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(CartItem::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return BelongsTo<Purchase, $this> */
|
|
||||||
public function purchase(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(Purchase::class);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,144 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Requests;
|
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
|
||||||
use App\Domains\Catalog\Enums\InventorySubject;
|
|
||||||
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)],
|
|
||||||
'inventory_subject' => ['sometimes', Rule::enum(InventorySubject::class)],
|
|
||||||
'max_units_per_user' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
|
||||||
'has_tickets' => [Rule::prohibitedIf($isBundle), 'sometimes', 'boolean'],
|
|
||||||
'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)
|
|
||||||
),
|
|
||||||
],
|
|
||||||
'multi_select_attribute_codes' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
|
|
||||||
'multi_select_attribute_codes.*' => [
|
|
||||||
'required',
|
|
||||||
'string',
|
|
||||||
'distinct',
|
|
||||||
Rule::exists('attribute', 'codigo')->where(
|
|
||||||
fn ($query) => $query->where('tenant_codigo', $tenantCode)
|
|
||||||
),
|
|
||||||
],
|
|
||||||
'hidden_attribute_codes' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
|
|
||||||
'hidden_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.*.descripcion' => ['sometimes', 'nullable', 'string'],
|
|
||||||
'variants.*.precio' => ['sometimes', 'nullable', 'numeric', 'min:0', 'max:99999999.99'],
|
|
||||||
'variants.*.event_date_id' => [
|
|
||||||
'sometimes',
|
|
||||||
'nullable',
|
|
||||||
'integer',
|
|
||||||
Rule::exists('event_dates', 'id')->where(
|
|
||||||
fn ($query) => $query->where('tenant_code', $tenantCode)
|
|
||||||
),
|
|
||||||
],
|
|
||||||
'variants.*.event_date_ids' => ['sometimes', 'array', 'min:1'],
|
|
||||||
'variants.*.event_date_ids.*' => [
|
|
||||||
'required',
|
|
||||||
'integer',
|
|
||||||
'distinct',
|
|
||||||
Rule::exists('event_dates', 'id')->where(
|
|
||||||
fn ($query) => $query->where('tenant_code', $tenantCode)
|
|
||||||
),
|
|
||||||
],
|
|
||||||
'variants.*.inventory_id' => ['prohibited'],
|
|
||||||
'variants.*.reserved_stock' => ['prohibited'],
|
|
||||||
'variants.*.sold_units' => ['prohibited'],
|
|
||||||
'variants.*.values' => ['sometimes', 'array'],
|
|
||||||
'variants.*.values.*' => ['nullable'],
|
|
||||||
'variants.*.values.*.*' => ['required', '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,50 +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,
|
|
||||||
'inventory_subject' => $this->inventory_subject->value,
|
|
||||||
'max_units_per_user' => $this->max_units_per_user,
|
|
||||||
'has_tickets' => $this->has_tickets,
|
|
||||||
'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,
|
|
||||||
'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, '.', ''),
|
|
||||||
'real_stock' => $variant->inventory?->real_stock,
|
|
||||||
'values' => $variant->selectorOptions($this->itemAttributes),
|
|
||||||
'images' => $variant->attachments
|
|
||||||
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
|
||||||
->values(),
|
|
||||||
])
|
|
||||||
->values()),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Services;
|
|
||||||
|
|
||||||
use App\Domains\Cart\Services\ExpireCartReservationsService;
|
|
||||||
use App\Domains\Purchase\Services\CheckoutService;
|
|
||||||
use Illuminate\Support\Facades\Log;
|
|
||||||
use Throwable;
|
|
||||||
|
|
||||||
class ExpireStockReservationsService
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
private readonly CheckoutService $checkout,
|
|
||||||
private readonly ExpireCartReservationsService $carts,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return array{purchases: int, cart_items: int}
|
|
||||||
*/
|
|
||||||
public function expireOverdue(): array
|
|
||||||
{
|
|
||||||
$expiredPurchases = null;
|
|
||||||
$expiredCartItems = null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
$expiredPurchases = $this->checkout->expireOverduePurchases();
|
|
||||||
$expiredCartItems = $this->carts->expireOverdue();
|
|
||||||
|
|
||||||
Log::channel('commands')->info('Stock reservation cleanup completed.', [
|
|
||||||
'command' => 'reservations:expire',
|
|
||||||
'expired_purchases' => $expiredPurchases,
|
|
||||||
'expired_cart_items' => $expiredCartItems,
|
|
||||||
'total_expired' => $expiredPurchases + $expiredCartItems,
|
|
||||||
]);
|
|
||||||
|
|
||||||
return [
|
|
||||||
'purchases' => $expiredPurchases,
|
|
||||||
'cart_items' => $expiredCartItems,
|
|
||||||
];
|
|
||||||
} catch (Throwable $exception) {
|
|
||||||
Log::channel('commands')->error('Stock reservation cleanup failed.', [
|
|
||||||
'command' => 'reservations:expire',
|
|
||||||
'expired_purchases' => $expiredPurchases,
|
|
||||||
'expired_cart_items' => $expiredCartItems,
|
|
||||||
'exception' => $exception,
|
|
||||||
]);
|
|
||||||
|
|
||||||
throw $exception;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,269 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Services;
|
|
||||||
|
|
||||||
use App\Domains\Cart\Models\CartItem;
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
|
||||||
use App\Domains\Catalog\Models\StockReservation;
|
|
||||||
use App\Domains\Catalog\Models\Variant;
|
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
|
||||||
use Illuminate\Support\Carbon;
|
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
|
|
||||||
class StockReservationService
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
private readonly CatalogInventoryService $inventory,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function reserve(CartItem $cartItem, CatalogItem|Variant $selection, int $quantity): void
|
|
||||||
{
|
|
||||||
DB::transaction(function () use ($cartItem, $selection, $quantity): void {
|
|
||||||
$this->inventory->reserve($selection, $quantity);
|
|
||||||
$this->recordIncrease($cartItem, $selection, $quantity);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public function release(
|
|
||||||
CartItem $cartItem,
|
|
||||||
CatalogItem|Variant $selection,
|
|
||||||
int $quantity,
|
|
||||||
string $releasedStatus = StockReservation::STATUS_RELEASED,
|
|
||||||
): void {
|
|
||||||
DB::transaction(function () use ($cartItem, $selection, $quantity, $releasedStatus): void {
|
|
||||||
$this->ensure($cartItem, $selection);
|
|
||||||
$this->inventory->release($selection, $quantity);
|
|
||||||
$this->recordDecrease($cartItem, $selection, $quantity, $releasedStatus);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public function commit(
|
|
||||||
CartItem $cartItem,
|
|
||||||
CatalogItem|Variant $selection,
|
|
||||||
Purchase $purchase,
|
|
||||||
): void {
|
|
||||||
DB::transaction(function () use ($cartItem, $selection, $purchase): void {
|
|
||||||
$this->ensure($cartItem, $selection);
|
|
||||||
$this->inventory->commit($selection, (int) $cartItem->cantidad);
|
|
||||||
|
|
||||||
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
|
|
||||||
foreach ($requirements as $inventoryId => $quantity) {
|
|
||||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
|
||||||
if (
|
|
||||||
$reservation === null
|
|
||||||
|| $reservation->status !== StockReservation::STATUS_ACTIVE
|
|
||||||
|| $reservation->purchase_id !== $purchase->getKey()
|
|
||||||
|| $reservation->quantity !== $quantity
|
|
||||||
) {
|
|
||||||
throw new \InvalidArgumentException('La reserva de stock no coincide con el item del carrito.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$reservation->update([
|
|
||||||
'status' => StockReservation::STATUS_COMMITTED,
|
|
||||||
'committed_at' => now(),
|
|
||||||
'expires_at' => null,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public function ensure(CartItem $cartItem, CatalogItem|Variant $selection): void
|
|
||||||
{
|
|
||||||
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
|
|
||||||
|
|
||||||
foreach ($requirements as $inventoryId => $quantity) {
|
|
||||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
|
||||||
|
|
||||||
if ($reservation === null) {
|
|
||||||
StockReservation::query()->create([
|
|
||||||
'inventory_id' => $inventoryId,
|
|
||||||
'cart_item_id' => $cartItem->getKey(),
|
|
||||||
'quantity' => $quantity,
|
|
||||||
'status' => StockReservation::STATUS_ACTIVE,
|
|
||||||
'expires_at' => $this->expiration(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity !== $quantity) {
|
|
||||||
$reservation->update([
|
|
||||||
'quantity' => $quantity,
|
|
||||||
'status' => StockReservation::STATUS_ACTIVE,
|
|
||||||
'committed_at' => null,
|
|
||||||
'released_at' => null,
|
|
||||||
'expires_at' => $this->expiration(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function attachToPurchase(
|
|
||||||
CartItem $cartItem,
|
|
||||||
CatalogItem|Variant $selection,
|
|
||||||
Purchase $purchase,
|
|
||||||
): void {
|
|
||||||
DB::transaction(function () use ($cartItem, $selection, $purchase): void {
|
|
||||||
$this->ensure($cartItem, $selection);
|
|
||||||
StockReservation::query()
|
|
||||||
->where('cart_item_id', $cartItem->getKey())
|
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
|
||||||
->update([
|
|
||||||
'purchase_id' => $purchase->getKey(),
|
|
||||||
'expires_at' => $purchase->expires_at,
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public function detachFromPurchase(Purchase $purchase): void
|
|
||||||
{
|
|
||||||
StockReservation::query()
|
|
||||||
->where('purchase_id', $purchase->getKey())
|
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
|
||||||
->update([
|
|
||||||
'purchase_id' => null,
|
|
||||||
'expires_at' => $this->expiration(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function restore(CartItem $cartItem, CatalogItem|Variant $selection): void
|
|
||||||
{
|
|
||||||
DB::transaction(function () use ($cartItem, $selection): void {
|
|
||||||
$requirements = $this->inventory->requirementsFor(
|
|
||||||
$selection,
|
|
||||||
(int) $cartItem->cantidad,
|
|
||||||
);
|
|
||||||
$activeReservations = StockReservation::query()
|
|
||||||
->where('cart_item_id', $cartItem->getKey())
|
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
|
||||||
->lockForUpdate()
|
|
||||||
->get()
|
|
||||||
->keyBy('inventory_id');
|
|
||||||
|
|
||||||
$hasCompleteReservation = collect($requirements)->every(
|
|
||||||
fn (int $quantity, int $inventoryId): bool => (int) ($activeReservations->get($inventoryId)?->quantity ?? 0) === $quantity,
|
|
||||||
);
|
|
||||||
|
|
||||||
if ($hasCompleteReservation) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($activeReservations->isNotEmpty()) {
|
|
||||||
throw new \InvalidArgumentException('La reserva de stock del carrito es inconsistente.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->inventory->reserve($selection, (int) $cartItem->cantidad);
|
|
||||||
$this->recordIncrease($cartItem, $selection, (int) $cartItem->cantidad);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public function syncPurchaseExpiration(Purchase $purchase): void
|
|
||||||
{
|
|
||||||
StockReservation::query()
|
|
||||||
->where('purchase_id', $purchase->getKey())
|
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
|
||||||
->update(['expires_at' => $purchase->expires_at]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function transfer(CartItem $source, CartItem $target): void
|
|
||||||
{
|
|
||||||
DB::transaction(function () use ($source, $target): void {
|
|
||||||
$sourceReservations = StockReservation::query()
|
|
||||||
->where('cart_item_id', $source->getKey())
|
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
|
||||||
->orderBy('inventory_id')
|
|
||||||
->lockForUpdate()
|
|
||||||
->get();
|
|
||||||
|
|
||||||
foreach ($sourceReservations as $sourceReservation) {
|
|
||||||
$targetReservation = $this->lockReservation($target, (int) $sourceReservation->inventory_id);
|
|
||||||
|
|
||||||
if ($targetReservation === null) {
|
|
||||||
$sourceItemQuantity = (int) $source->cantidad;
|
|
||||||
$targetItemQuantity = (int) $target->fresh()->cantidad;
|
|
||||||
$perItemQuantity = intdiv((int) $sourceReservation->quantity, $sourceItemQuantity);
|
|
||||||
$sourceReservation->update([
|
|
||||||
'cart_item_id' => $target->getKey(),
|
|
||||||
'purchase_id' => null,
|
|
||||||
'quantity' => $perItemQuantity * $targetItemQuantity,
|
|
||||||
'expires_at' => $this->expiration(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$targetReservation->update([
|
|
||||||
'quantity' => $targetReservation->quantity + $sourceReservation->quantity,
|
|
||||||
'status' => StockReservation::STATUS_ACTIVE,
|
|
||||||
'expires_at' => $this->expiration(),
|
|
||||||
]);
|
|
||||||
$sourceReservation->delete();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private function recordIncrease(CartItem $cartItem, CatalogItem|Variant $selection, int $quantity): void
|
|
||||||
{
|
|
||||||
foreach ($this->inventory->requirementsFor($selection, $quantity) as $inventoryId => $requiredQuantity) {
|
|
||||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
|
||||||
|
|
||||||
if ($reservation === null) {
|
|
||||||
StockReservation::query()->create([
|
|
||||||
'inventory_id' => $inventoryId,
|
|
||||||
'cart_item_id' => $cartItem->getKey(),
|
|
||||||
'quantity' => $requiredQuantity,
|
|
||||||
'status' => StockReservation::STATUS_ACTIVE,
|
|
||||||
'expires_at' => $this->expiration(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$reservation->update([
|
|
||||||
'quantity' => ($reservation->status === StockReservation::STATUS_ACTIVE ? $reservation->quantity : 0) + $requiredQuantity,
|
|
||||||
'status' => StockReservation::STATUS_ACTIVE,
|
|
||||||
'committed_at' => null,
|
|
||||||
'released_at' => null,
|
|
||||||
'expires_at' => $this->expiration(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function recordDecrease(
|
|
||||||
CartItem $cartItem,
|
|
||||||
CatalogItem|Variant $selection,
|
|
||||||
int $quantity,
|
|
||||||
string $releasedStatus,
|
|
||||||
): void {
|
|
||||||
foreach ($this->inventory->requirementsFor($selection, $quantity) as $inventoryId => $requiredQuantity) {
|
|
||||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
|
||||||
if ($reservation === null || $reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity < $requiredQuantity) {
|
|
||||||
throw new \InvalidArgumentException('La reserva de stock no alcanza para liberar la cantidad solicitada.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$remaining = $reservation->quantity - $requiredQuantity;
|
|
||||||
$reservation->update([
|
|
||||||
'quantity' => $remaining,
|
|
||||||
'status' => $remaining === 0 ? $releasedStatus : StockReservation::STATUS_ACTIVE,
|
|
||||||
'released_at' => $remaining === 0 ? now() : null,
|
|
||||||
'expires_at' => $remaining === 0 ? null : $reservation->expires_at,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function lockReservation(CartItem $cartItem, int $inventoryId): ?StockReservation
|
|
||||||
{
|
|
||||||
return StockReservation::query()
|
|
||||||
->where('cart_item_id', $cartItem->getKey())
|
|
||||||
->where('inventory_id', $inventoryId)
|
|
||||||
->lockForUpdate()
|
|
||||||
->first();
|
|
||||||
}
|
|
||||||
|
|
||||||
private function expiration(): Carbon
|
|
||||||
{
|
|
||||||
return now()->addMinutes(
|
|
||||||
max(1, (int) config('catalog.stock_reservation_expiration_minutes', 30)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Cart\Controllers;
|
namespace App\Domains\Commerce\Cart\Controllers;
|
||||||
|
|
||||||
use App\Domains\Cart\Models\CartItem;
|
use App\Domains\Commerce\Cart\Models\CartItem;
|
||||||
use App\Domains\Cart\Requests\AddCartItemRequest;
|
use App\Domains\Commerce\Cart\Requests\AddCartItemRequest;
|
||||||
use App\Domains\Cart\Requests\UpdateCartItemQuantityRequest;
|
use App\Domains\Commerce\Cart\Requests\UpdateCartItemQuantityRequest;
|
||||||
use App\Domains\Cart\Resources\CartResource;
|
use App\Domains\Commerce\Cart\Resources\CartResource;
|
||||||
use App\Domains\Cart\Services\CartService;
|
use App\Domains\Commerce\Cart\Services\CartService;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -1,16 +1,17 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Cart\Models;
|
namespace App\Domains\Commerce\Cart\Models;
|
||||||
|
|
||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Core\Auth\Models\User;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Inventory;
|
use App\Domains\Commerce\Catalog\Models\Inventory;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Commerce\Catalog\Models\StockReservation;
|
||||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||||
use App\Domains\Catalog\Services\StockReservationService;
|
use App\Domains\Commerce\Catalog\Services\CatalogInventoryService;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Commerce\Catalog\Services\StockReservationService;
|
||||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Commerce\Purchase\Services\UserPurchaseLimitService;
|
||||||
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
@@ -28,6 +29,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|||||||
'status',
|
'status',
|
||||||
'origin',
|
'origin',
|
||||||
'current_purchase_id',
|
'current_purchase_id',
|
||||||
|
'current_stock_reservation_id',
|
||||||
])]
|
])]
|
||||||
class Cart extends Model
|
class Cart extends Model
|
||||||
{
|
{
|
||||||
@@ -36,6 +38,16 @@ class Cart extends Model
|
|||||||
|
|
||||||
protected $table = 'carritos';
|
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_USER = 'user';
|
||||||
|
|
||||||
public const ORIGIN_DIRECT_CHECKOUT = 'direct_checkout';
|
public const ORIGIN_DIRECT_CHECKOUT = 'direct_checkout';
|
||||||
@@ -45,6 +57,7 @@ class Cart extends Model
|
|||||||
return [
|
return [
|
||||||
'user_id' => 'integer',
|
'user_id' => 'integer',
|
||||||
'current_purchase_id' => 'integer',
|
'current_purchase_id' => 'integer',
|
||||||
|
'current_stock_reservation_id' => 'integer',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,6 +97,15 @@ class Cart extends Model
|
|||||||
return $this->belongsTo(Purchase::class, 'current_purchase_id');
|
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
|
public function getTotalAmount(): float
|
||||||
{
|
{
|
||||||
$items = $this->relationLoaded('items')
|
$items = $this->relationLoaded('items')
|
||||||
@@ -107,6 +129,7 @@ class Cart extends Model
|
|||||||
|
|
||||||
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
|
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
|
||||||
$this->invalidateCurrentCheckout();
|
$this->invalidateCurrentCheckout();
|
||||||
|
app(StockReservationService::class)->assertCartReservationUsable($this);
|
||||||
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
|
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
|
||||||
$cartQuantity = (int) $this->items()
|
$cartQuantity = (int) $this->items()
|
||||||
->where('catalog_item_id', $catalogItemId)
|
->where('catalog_item_id', $catalogItemId)
|
||||||
@@ -140,12 +163,11 @@ class Cart extends Model
|
|||||||
'cantidad' => $quantity,
|
'cantidad' => $quantity,
|
||||||
]);
|
]);
|
||||||
} else {
|
} else {
|
||||||
app(StockReservationService::class)->ensure($item, $selectedItem);
|
|
||||||
$item->cantidad += $quantity;
|
$item->cantidad += $quantity;
|
||||||
$item->save();
|
$item->save();
|
||||||
}
|
}
|
||||||
|
|
||||||
app(StockReservationService::class)->reserve($item, $selectedItem, $quantity);
|
app(StockReservationService::class)->syncCart($this);
|
||||||
|
|
||||||
return $item->fresh();
|
return $item->fresh();
|
||||||
});
|
});
|
||||||
@@ -172,6 +194,7 @@ class Cart extends Model
|
|||||||
$excludedPurchaseId,
|
$excludedPurchaseId,
|
||||||
): CartItem {
|
): CartItem {
|
||||||
$this->invalidateCurrentCheckout();
|
$this->invalidateCurrentCheckout();
|
||||||
|
app(StockReservationService::class)->assertCartReservationUsable($this);
|
||||||
|
|
||||||
/** @var CartItem $item */
|
/** @var CartItem $item */
|
||||||
$item = $this->items()
|
$item = $this->items()
|
||||||
@@ -205,7 +228,6 @@ class Cart extends Model
|
|||||||
$nextAvailableQuantity,
|
$nextAvailableQuantity,
|
||||||
);
|
);
|
||||||
|
|
||||||
app(StockReservationService::class)->release($item, $currentSelection, $item->cantidad);
|
|
||||||
$availableQuantity = $inventoryService->availableQuantity($nextSelection);
|
$availableQuantity = $inventoryService->availableQuantity($nextSelection);
|
||||||
|
|
||||||
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||||
@@ -222,11 +244,10 @@ class Cart extends Model
|
|||||||
->first();
|
->first();
|
||||||
|
|
||||||
if ($targetItem !== null) {
|
if ($targetItem !== null) {
|
||||||
app(StockReservationService::class)->ensure($targetItem, $nextSelection);
|
|
||||||
$targetItem->cantidad += $quantity;
|
$targetItem->cantidad += $quantity;
|
||||||
$targetItem->save();
|
$targetItem->save();
|
||||||
app(StockReservationService::class)->reserve($targetItem, $nextSelection, $quantity);
|
|
||||||
$item->delete();
|
$item->delete();
|
||||||
|
app(StockReservationService::class)->syncCart($this);
|
||||||
|
|
||||||
return $targetItem->fresh();
|
return $targetItem->fresh();
|
||||||
}
|
}
|
||||||
@@ -234,7 +255,7 @@ class Cart extends Model
|
|||||||
$item->variant_id = $variantId;
|
$item->variant_id = $variantId;
|
||||||
$item->cantidad = $quantity;
|
$item->cantidad = $quantity;
|
||||||
$item->save();
|
$item->save();
|
||||||
app(StockReservationService::class)->reserve($item, $nextSelection, $quantity);
|
app(StockReservationService::class)->syncCart($this);
|
||||||
|
|
||||||
return $item->fresh();
|
return $item->fresh();
|
||||||
}
|
}
|
||||||
@@ -263,16 +284,9 @@ class Cart extends Model
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($delta > 0) {
|
|
||||||
app(StockReservationService::class)->reserve($item, $currentSelection, $delta);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($delta < 0) {
|
|
||||||
app(StockReservationService::class)->release($item, $currentSelection, abs($delta));
|
|
||||||
}
|
|
||||||
|
|
||||||
$item->cantidad = $quantity;
|
$item->cantidad = $quantity;
|
||||||
$item->save();
|
$item->save();
|
||||||
|
app(StockReservationService::class)->syncCart($this);
|
||||||
|
|
||||||
return $item->fresh();
|
return $item->fresh();
|
||||||
});
|
});
|
||||||
@@ -282,6 +296,7 @@ class Cart extends Model
|
|||||||
{
|
{
|
||||||
DB::transaction(function () use ($cartItemId): void {
|
DB::transaction(function () use ($cartItemId): void {
|
||||||
$this->invalidateCurrentCheckout();
|
$this->invalidateCurrentCheckout();
|
||||||
|
app(StockReservationService::class)->assertCartReservationUsable($this);
|
||||||
|
|
||||||
/** @var CartItem $item */
|
/** @var CartItem $item */
|
||||||
$item = $this->items()
|
$item = $this->items()
|
||||||
@@ -289,17 +304,8 @@ class Cart extends Model
|
|||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->firstOrFail();
|
->firstOrFail();
|
||||||
|
|
||||||
$selectedItem = $this->resolveScopedItem(
|
|
||||||
$item->catalog_item_id,
|
|
||||||
$item->variant_id,
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
app(StockReservationService::class)->release(
|
|
||||||
$item,
|
|
||||||
$selectedItem,
|
|
||||||
$item->cantidad,
|
|
||||||
);
|
|
||||||
$item->delete();
|
$item->delete();
|
||||||
|
app(StockReservationService::class)->syncCart($this);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -341,13 +347,20 @@ class Cart extends Model
|
|||||||
Purchase::STATUS_CREATED,
|
Purchase::STATUS_CREATED,
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
], true)) {
|
], true)) {
|
||||||
|
app(StockReservationService::class)->returnToCart($currentPurchase, $cart);
|
||||||
$currentPurchase->update([
|
$currentPurchase->update([
|
||||||
'status' => Purchase::STATUS_SUPERSEDED,
|
'status' => Purchase::STATUS_SUPERSEDED,
|
||||||
'expires_at' => null,
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
$this->current_purchase_id = null;
|
||||||
|
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
app(StockReservationService::class)->detachFromPurchase($currentPurchase);
|
app(StockReservationService::class)->releaseForPurchase(
|
||||||
|
$currentPurchase,
|
||||||
|
reason: StockReservationService::REASON_PURCHASE_SUPERSEDED,
|
||||||
|
);
|
||||||
self::query()
|
self::query()
|
||||||
->whereKey($cart->getKey())
|
->whereKey($cart->getKey())
|
||||||
->where('current_purchase_id', $currentPurchase->getKey())
|
->where('current_purchase_id', $currentPurchase->getKey())
|
||||||
@@ -362,7 +375,7 @@ class Cart extends Model
|
|||||||
): CatalogItem|Variant {
|
): CatalogItem|Variant {
|
||||||
$catalogItemQuery = CatalogItem::query()
|
$catalogItemQuery = CatalogItem::query()
|
||||||
->whereKey($catalogItemId)
|
->whereKey($catalogItemId)
|
||||||
->where('tenant_code', $this->tenant_codigo);
|
->forTenantCatalog($this->tenant()->firstOrFail());
|
||||||
|
|
||||||
if ($lockForUpdate) {
|
if ($lockForUpdate) {
|
||||||
$catalogItemQuery->lockForUpdate();
|
$catalogItemQuery->lockForUpdate();
|
||||||
@@ -387,6 +400,17 @@ class Cart extends Model
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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;
|
return $catalogItem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -417,6 +441,12 @@ class Cart extends Model
|
|||||||
throw new NotFoundHttpException('Variant not found for catalog item.');
|
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);
|
$inventory = $this->resolveInventory($variant->inventory_id, $lockForUpdate);
|
||||||
$variant->setRelation('catalogItem', $catalogItem);
|
$variant->setRelation('catalogItem', $catalogItem);
|
||||||
$variant->setRelation('inventory', $inventory);
|
$variant->setRelation('inventory', $inventory);
|
||||||
@@ -1,15 +1,13 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Cart\Models;
|
namespace App\Domains\Commerce\Cart\Models;
|
||||||
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\StockReservation;
|
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'cart_id',
|
'cart_id',
|
||||||
@@ -57,10 +55,4 @@ class CartItem extends Model
|
|||||||
{
|
{
|
||||||
return $this->variant ?? $this->catalogItem;
|
return $this->variant ?? $this->catalogItem;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return HasMany<StockReservation, $this> */
|
|
||||||
public function stockReservations(): HasMany
|
|
||||||
{
|
|
||||||
return $this->hasMany(StockReservation::class);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Cart\Requests;
|
namespace App\Domains\Commerce\Cart\Requests;
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Cart\Requests;
|
namespace App\Domains\Commerce\Cart\Requests;
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Cart\Resources;
|
namespace App\Domains\Commerce\Cart\Resources;
|
||||||
|
|
||||||
use App\Domains\Cart\Models\CartItem;
|
use App\Domains\Commerce\Cart\Models\CartItem;
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
<?php
|
<?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\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
@@ -1,12 +1,15 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Cart\Services;
|
namespace App\Domains\Commerce\Cart\Services;
|
||||||
|
|
||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Core\Auth\Models\User;
|
||||||
use App\Domains\Cart\Models\Cart;
|
use App\Domains\Commerce\Cart\Models\Cart;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
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\Http\Request;
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
use Symfony\Component\HttpFoundation\Cookie;
|
use Symfony\Component\HttpFoundation\Cookie;
|
||||||
@@ -22,7 +25,7 @@ class CartService
|
|||||||
return $this->makeEmptyCart($tenant);
|
return $this->makeEmptyCart($tenant);
|
||||||
}
|
}
|
||||||
|
|
||||||
$cart = $this->findCart($tenant, $resolvedIdentity['identity']);
|
$cart = $this->resolveCart($tenant, $resolvedIdentity['identity']);
|
||||||
|
|
||||||
if ($cart === null) {
|
if ($cart === null) {
|
||||||
return $this->makeEmptyCart($tenant);
|
return $this->makeEmptyCart($tenant);
|
||||||
@@ -119,7 +122,7 @@ class CartService
|
|||||||
{
|
{
|
||||||
$cart = new Cart([
|
$cart = new Cart([
|
||||||
'tenant_codigo' => $tenant->codigo,
|
'tenant_codigo' => $tenant->codigo,
|
||||||
'status' => 'active',
|
'status' => Cart::STATUS_ACTIVE,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$cart->setRelation('items', collect());
|
$cart->setRelation('items', collect());
|
||||||
@@ -220,12 +223,14 @@ class CartService
|
|||||||
{
|
{
|
||||||
return Cart::query()
|
return Cart::query()
|
||||||
->where('tenant_codigo', $tenant->codigo)
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
->where('status', 'active')
|
->where('origin', Cart::ORIGIN_USER)
|
||||||
|
->whereIn('status', [Cart::STATUS_ACTIVE, Cart::STATUS_EXPIRED])
|
||||||
->when(
|
->when(
|
||||||
$identity['user_id'] !== null,
|
$identity['user_id'] !== null,
|
||||||
fn ($query) => $query->where('user_id', $identity['user_id']),
|
fn ($query) => $query->where('user_id', $identity['user_id']),
|
||||||
fn ($query) => $query->where('guest_token', $identity['guest_token']),
|
fn ($query) => $query->where('guest_token', $identity['guest_token']),
|
||||||
)
|
)
|
||||||
|
->orderByRaw('CASE WHEN status = ? THEN 0 ELSE 1 END', [Cart::STATUS_ACTIVE])
|
||||||
->first();
|
->first();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -234,7 +239,7 @@ class CartService
|
|||||||
*/
|
*/
|
||||||
protected function findCartOrFail(Tenant $tenant, array $identity): Cart
|
protected function findCartOrFail(Tenant $tenant, array $identity): Cart
|
||||||
{
|
{
|
||||||
$cart = $this->findCart($tenant, $identity);
|
$cart = $this->resolveCart($tenant, $identity, replaceExpired: false);
|
||||||
|
|
||||||
if ($cart === null) {
|
if ($cart === null) {
|
||||||
throw new NotFoundHttpException('Cart not found.');
|
throw new NotFoundHttpException('Cart not found.');
|
||||||
@@ -247,10 +252,73 @@ class CartService
|
|||||||
* @param array{user_id: ?int, guest_token: ?string} $identity
|
* @param array{user_id: ?int, guest_token: ?string} $identity
|
||||||
*/
|
*/
|
||||||
protected function findOrCreateCart(Tenant $tenant, array $identity): Cart
|
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 = [
|
$attributes = [
|
||||||
'tenant_codigo' => $tenant->codigo,
|
'tenant_codigo' => $tenant->codigo,
|
||||||
'status' => 'active',
|
'status' => Cart::STATUS_ACTIVE,
|
||||||
|
'origin' => Cart::ORIGIN_USER,
|
||||||
];
|
];
|
||||||
|
|
||||||
if ($identity['user_id'] !== null) {
|
if ($identity['user_id'] !== null) {
|
||||||
@@ -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')],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Cart\Services;
|
namespace App\Domains\Commerce\Cart\Services;
|
||||||
|
|
||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Core\Auth\Models\User;
|
||||||
use App\Domains\Cart\Models\Cart;
|
use App\Domains\Commerce\Cart\Models\Cart;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
class GuestCartMergeService
|
class GuestCartMergeService
|
||||||
@@ -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]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,13 +6,12 @@ Gestiona el carrito activo de un tenant tanto para visitantes como para usuarios
|
|||||||
|
|
||||||
## Modelo
|
## Modelo
|
||||||
|
|
||||||
- `Cart`: pertenece a un tenant y opcionalmente a un usuario; calcula el total y permite agregar, actualizar o quitar ítems.
|
- `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.
|
- `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
|
## Servicios
|
||||||
|
|
||||||
- `CartService`: obtiene el carrito, modifica ítems y administra la cookie del token invitado.
|
- `CartService`: obtiene el carrito, modifica ítems y administra la cookie del token invitado.
|
||||||
- `ExpireCartReservationsService`: libera las reservas vencidas de carritos activos y elimina los carritos que quedan vacíos.
|
|
||||||
- `GuestCartMergeService`: incorpora el carrito invitado al usuario cuando este se autentica.
|
- `GuestCartMergeService`: incorpora el carrito invitado al usuario cuando este se autentica.
|
||||||
|
|
||||||
## Endpoints
|
## Endpoints
|
||||||
@@ -34,4 +33,6 @@ Depende de `Catalog` para productos y variantes, de `Tenant` para aislar datos y
|
|||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
El comando unificado `php artisan reservations:expire` procesa primero las compras vencidas y luego las reservas activas sin compra cuyo `expires_at` haya vencido. Se ejecuta cada minuto mediante el scheduler, conserva la fila de reserva con estado `expired`, elimina el ítem abandonado y elimina lógicamente el carrito cuando queda vacío. Cada intento registra sus resultados o su error en el log diario `storage/logs/commands/commands-AAAA-MM-DD.log`.
|
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,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use App\Domains\Cart\Controllers\CartController;
|
use App\Domains\Commerce\Cart\Controllers\CartController;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
Route::prefix('tenants/{tenant:codigo}')
|
Route::prefix('tenants/{tenant:codigo}')
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Controllers\AdminApp;
|
namespace App\Domains\Commerce\Catalog\Controllers\AdminApp;
|
||||||
|
|
||||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
|
||||||
use App\Domains\Catalog\Requests\AdminApp\UpsertOnTicketFeaturedGroupRequest;
|
use App\Domains\Commerce\Catalog\Requests\AdminApp\UpsertOnTicketFeaturedGroupRequest;
|
||||||
use App\Domains\Catalog\Resources\AdminApp\OnTicketFeaturedGroupResource;
|
use App\Domains\Commerce\Catalog\Resources\AdminApp\OnTicketFeaturedGroupResource;
|
||||||
use App\Domains\Catalog\Services\OnTicketFeaturedGroupService;
|
use App\Domains\Commerce\Catalog\Services\OnTicketFeaturedGroupService;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -58,7 +58,7 @@ class OnTicketFeaturedGroupController extends Controller
|
|||||||
{
|
{
|
||||||
$tenant = $request->user()->tenant()->firstOrFail();
|
$tenant = $request->user()->tenant()->firstOrFail();
|
||||||
|
|
||||||
abort_unless($tenant->website_type_code === 'onticket', 404);
|
abort_unless(in_array($tenant->storefront_website_type_code, ['onticket', 'onticket_multi_event'], true), 404);
|
||||||
|
|
||||||
return $tenant;
|
return $tenant;
|
||||||
}
|
}
|
||||||
@@ -1,27 +1,25 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Controllers;
|
namespace App\Domains\Commerce\Catalog\Controllers;
|
||||||
|
|
||||||
use App\Domains\Cart\Services\CartService;
|
use App\Domains\Commerce\Cart\Services\CartService;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Category;
|
use App\Domains\Commerce\Catalog\Models\Category;
|
||||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
|
||||||
use App\Domains\Catalog\Requests\CatalogItemDetailRequest;
|
use App\Domains\Commerce\Catalog\Requests\CatalogItemDetailRequest;
|
||||||
use App\Domains\Catalog\Requests\CatalogVariantOptionsRequest;
|
use App\Domains\Commerce\Catalog\Requests\CatalogVariantOptionsRequest;
|
||||||
use App\Domains\Catalog\Requests\CategoryPageRequest;
|
use App\Domains\Commerce\Catalog\Requests\CategoryPageRequest;
|
||||||
use App\Domains\Catalog\Requests\FeaturedGroupPageRequest;
|
use App\Domains\Commerce\Catalog\Requests\FeaturedGroupPageRequest;
|
||||||
use App\Domains\Catalog\Requests\SearchCatalogItemsRequest;
|
use App\Domains\Commerce\Catalog\Requests\SearchCatalogItemsRequest;
|
||||||
use App\Domains\Catalog\Requests\StoreCatalogItemRequest;
|
use App\Domains\Commerce\Catalog\Resources\CatalogFeaturedGroupResource;
|
||||||
use App\Domains\Catalog\Resources\CatalogFeaturedGroupResource;
|
use App\Domains\Commerce\Catalog\Resources\CatalogItemDetailResource;
|
||||||
use App\Domains\Catalog\Resources\CatalogItemDetailResource;
|
use App\Domains\Commerce\Catalog\Resources\CatalogSearchItemResource;
|
||||||
use App\Domains\Catalog\Resources\CatalogItemResource;
|
use App\Domains\Commerce\Catalog\Resources\CatalogVariantOptionsResource;
|
||||||
use App\Domains\Catalog\Resources\CatalogSearchItemResource;
|
use App\Domains\Commerce\Catalog\Services\CatalogItemAllowanceService;
|
||||||
use App\Domains\Catalog\Resources\CatalogVariantOptionsResource;
|
use App\Domains\Commerce\Catalog\Services\CatalogService;
|
||||||
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
|
use App\Domains\Commerce\Catalog\Services\FeaturedGroupService;
|
||||||
use App\Domains\Catalog\Services\CatalogService;
|
use App\Domains\Commerce\Catalog\Services\VariantSelectionService;
|
||||||
use App\Domains\Catalog\Services\FeaturedGroupService;
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use App\Domains\Catalog\Services\VariantSelectionService;
|
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -40,7 +38,7 @@ class CatalogController extends Controller
|
|||||||
return response()->json($featuredGroups->map(
|
return response()->json($featuredGroups->map(
|
||||||
fn (FeaturedGroup $featuredGroup): array => (new CatalogFeaturedGroupResource(
|
fn (FeaturedGroup $featuredGroup): array => (new CatalogFeaturedGroupResource(
|
||||||
$featuredGroup,
|
$featuredGroup,
|
||||||
$featuredGroupService->itemsResponse($featuredGroup, 1, $this->userId($request)),
|
$featuredGroupService->itemsResponse($featuredGroup, $tenant, 1, $this->userId($request)),
|
||||||
))->resolve()
|
))->resolve()
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@@ -102,6 +100,7 @@ class CatalogController extends Controller
|
|||||||
|
|
||||||
return response()->json($featuredGroupService->itemsResponse(
|
return response()->json($featuredGroupService->itemsResponse(
|
||||||
$featuredGroup,
|
$featuredGroup,
|
||||||
|
$tenant,
|
||||||
$page,
|
$page,
|
||||||
$this->userId($request),
|
$this->userId($request),
|
||||||
));
|
));
|
||||||
@@ -114,7 +113,8 @@ class CatalogController extends Controller
|
|||||||
CatalogService $catalogService,
|
CatalogService $catalogService,
|
||||||
CatalogItemAllowanceService $allowances,
|
CatalogItemAllowanceService $allowances,
|
||||||
): CatalogItemDetailResource {
|
): CatalogItemDetailResource {
|
||||||
abort_unless($catalogItem->tenant_code === $tenant->codigo, 404);
|
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');
|
$variantId = $request->validated('variant_id');
|
||||||
|
|
||||||
@@ -134,7 +134,8 @@ class CatalogController extends Controller
|
|||||||
VariantSelectionService $variantSelectionService,
|
VariantSelectionService $variantSelectionService,
|
||||||
CartService $cartService,
|
CartService $cartService,
|
||||||
): CatalogVariantOptionsResource {
|
): CatalogVariantOptionsResource {
|
||||||
abort_unless($catalogItem->tenant_code === $tenant->codigo, 404);
|
abort_unless($catalogItem->tenant_code === $tenant->codigo
|
||||||
|
&& ($tenant->active_event_id === null || $catalogItem->event_id === $tenant->active_event_id), 404);
|
||||||
|
|
||||||
$includedVariantId = null;
|
$includedVariantId = null;
|
||||||
$cartItemId = $request->validated('cart_item_id');
|
$cartItemId = $request->validated('cart_item_id');
|
||||||
@@ -163,21 +164,6 @@ class CatalogController extends Controller
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function userId(Request $request): ?int
|
private function userId(Request $request): ?int
|
||||||
{
|
{
|
||||||
$userId = $request->user()?->getAuthIdentifier() ?? Auth::guard('sanctum')->id();
|
$userId = $request->user()?->getAuthIdentifier() ?? Auth::guard('sanctum')->id();
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Enums;
|
namespace App\Domains\Commerce\Catalog\Enums;
|
||||||
|
|
||||||
enum CatalogItemType: string
|
enum CatalogItemType: string
|
||||||
{
|
{
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Enums;
|
namespace App\Domains\Commerce\Catalog\Enums;
|
||||||
|
|
||||||
enum FeaturedGroupSource: string
|
enum FeaturedGroupSource: string
|
||||||
{
|
{
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Enums;
|
namespace App\Domains\Commerce\Catalog\Enums;
|
||||||
|
|
||||||
enum GroupLayout: string
|
enum GroupLayout: string
|
||||||
{
|
{
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Enums;
|
namespace App\Domains\Commerce\Catalog\Enums;
|
||||||
|
|
||||||
enum InventoryPolicy: string
|
enum InventoryPolicy: string
|
||||||
{
|
{
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Enums;
|
namespace App\Domains\Commerce\Catalog\Enums;
|
||||||
|
|
||||||
enum InventorySubject: string
|
enum InventorySubject: string
|
||||||
{
|
{
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Enums;
|
namespace App\Domains\Commerce\Catalog\Enums;
|
||||||
|
|
||||||
enum ProductLayout: string
|
enum ProductLayout: 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,10 +1,10 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Commerce\Catalog\Models;
|
||||||
|
|
||||||
use App\Domains\Event\Models\EventDate;
|
use App\Domains\Ticketing\Event\Models\EventDate;
|
||||||
use App\Domains\Shared\Enums\FieldType;
|
use App\Shared\Enums\FieldType;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
@@ -59,6 +59,8 @@ class Attribute extends Model
|
|||||||
public function eventDates(): HasMany
|
public function eventDates(): HasMany
|
||||||
{
|
{
|
||||||
return $this->hasMany(EventDate::class, 'tenant_code', 'tenant_codigo')
|
return $this->hasMany(EventDate::class, 'tenant_code', 'tenant_codigo')
|
||||||
|
->whereNull('rescheduled_to_event_date_id')
|
||||||
|
->whereNull('suspended_at')
|
||||||
->orderBy('date')
|
->orderBy('date')
|
||||||
->orderBy('time_start');
|
->orderBy('time_start');
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Commerce\Catalog\Models;
|
||||||
|
|
||||||
use App\Domains\Ticket\Models\ValidityTime;
|
use App\Domains\Ticketing\Ticket\Models\ValidityTime;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
<?php
|
<?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\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Commerce\Catalog\Models;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
@@ -1,14 +1,15 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Commerce\Catalog\Models;
|
||||||
|
|
||||||
use App\Domains\Attachable\Models\Attachment;
|
use App\Shared\Attachable\Models\Attachment;
|
||||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
use App\Domains\Commerce\Catalog\Enums\CatalogItemType;
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Enums\InventorySubject;
|
use App\Domains\Commerce\Catalog\Enums\InventorySubject;
|
||||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
use App\Domains\Commerce\Catalog\Services\CatalogInventoryService;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use App\Domains\Ticket\Models\Ticket;
|
use App\Domains\Ticketing\Event\Models\Event;
|
||||||
|
use App\Domains\Ticketing\Ticket\Models\Ticket;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
@@ -27,8 +28,10 @@ use Illuminate\Support\Collection;
|
|||||||
'type',
|
'type',
|
||||||
'slug',
|
'slug',
|
||||||
'nombre',
|
'nombre',
|
||||||
|
'group_order',
|
||||||
'descripcion',
|
'descripcion',
|
||||||
'precio',
|
'precio',
|
||||||
|
'sales_end_at',
|
||||||
'inventory_policy',
|
'inventory_policy',
|
||||||
'inventory_subject',
|
'inventory_subject',
|
||||||
'max_units_per_user',
|
'max_units_per_user',
|
||||||
@@ -47,16 +50,33 @@ class CatalogItem extends Model
|
|||||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||||
'inventory_subject' => InventorySubject::Product->value,
|
'inventory_subject' => InventorySubject::Product->value,
|
||||||
'has_tickets' => false,
|
'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
|
protected function casts(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
|
'event_id' => 'integer',
|
||||||
'category_id' => 'integer',
|
'category_id' => 'integer',
|
||||||
'brand_id' => 'integer',
|
'brand_id' => 'integer',
|
||||||
'inventory_id' => 'integer',
|
'inventory_id' => 'integer',
|
||||||
'type' => CatalogItemType::class,
|
'type' => CatalogItemType::class,
|
||||||
|
'group_order' => 'integer',
|
||||||
'precio' => 'decimal:2',
|
'precio' => 'decimal:2',
|
||||||
|
'sales_end_at' => 'datetime',
|
||||||
'inventory_policy' => InventoryPolicy::class,
|
'inventory_policy' => InventoryPolicy::class,
|
||||||
'inventory_subject' => InventorySubject::class,
|
'inventory_subject' => InventorySubject::class,
|
||||||
'max_units_per_user' => 'integer',
|
'max_units_per_user' => 'integer',
|
||||||
@@ -70,6 +90,21 @@ class CatalogItem extends Model
|
|||||||
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
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> */
|
/** @return BelongsTo<Category, $this> */
|
||||||
public function category(): BelongsTo
|
public function category(): BelongsTo
|
||||||
{
|
{
|
||||||
@@ -158,6 +193,10 @@ class CatalogItem extends Model
|
|||||||
|
|
||||||
public function isAvailable(): bool
|
public function isAvailable(): bool
|
||||||
{
|
{
|
||||||
|
if (! $this->isSaleOpen()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if ($this->type === CatalogItemType::Bundle) {
|
if ($this->type === CatalogItemType::Bundle) {
|
||||||
$availableStock = $this->availableStock();
|
$availableStock = $this->availableStock();
|
||||||
|
|
||||||
@@ -172,27 +211,67 @@ class CatalogItem extends Model
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @param Builder<CatalogItem> $query */
|
/** @param Builder<CatalogItem> $query */
|
||||||
public function scopeWhereVariantsAvailable(Builder $query): Builder
|
public function scopeWhereAvailable(Builder $query): Builder
|
||||||
{
|
{
|
||||||
return $query->where(function (Builder $query): void {
|
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
|
$query
|
||||||
->whereDoesntHave('variants')
|
->where(function (Builder $unlimitedQuery): void {
|
||||||
->orWhere('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value)
|
$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(
|
->orWhereHas(
|
||||||
'variants.inventory',
|
'variants',
|
||||||
fn (Builder $inventoryQuery): Builder => $inventoryQuery
|
fn (Builder $variantQuery): Builder => $variantQuery
|
||||||
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
|
->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> */
|
/** @return Collection<int, Variant> */
|
||||||
public function visibleVariants(?int $includedVariantId = null): Collection
|
public function visibleVariants(?int $includedVariantId = null): Collection
|
||||||
{
|
{
|
||||||
return $this->variants
|
return $this->variants
|
||||||
->filter(fn (Variant $variant): bool => ($includedVariantId !== null && $variant->id === $includedVariantId)
|
->each(fn (Variant $variant) => $variant->setRelation('catalogItem', $this))
|
||||||
|| $this->inventory_policy === InventoryPolicy::Unlimited
|
->filter(fn (Variant $variant): bool => $variant->hasOnlyActiveEventDates()
|
||||||
|| ($variant->inventory?->availableStock() ?? 0) > 0)
|
&& (($includedVariantId !== null && $variant->id === $includedVariantId)
|
||||||
|
|| ($variant->isSellable() && (
|
||||||
|
$this->inventory_policy === InventoryPolicy::Unlimited
|
||||||
|
|| ($variant->inventory?->availableStock() ?? 0) > 0
|
||||||
|
))))
|
||||||
->values();
|
->values();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Commerce\Catalog\Models;
|
||||||
|
|
||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Core\Auth\Models\User;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Commerce\Catalog\Models;
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\FeaturedGroupSource;
|
use App\Domains\Commerce\Catalog\Enums\FeaturedGroupSource;
|
||||||
use App\Domains\Catalog\Enums\GroupLayout;
|
use App\Domains\Commerce\Catalog\Enums\GroupLayout;
|
||||||
use App\Domains\Catalog\Enums\ProductLayout;
|
use App\Domains\Commerce\Catalog\Enums\ProductLayout;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Commerce\Catalog\Models;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Commerce\Catalog\Models;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
@@ -10,6 +10,7 @@ use Illuminate\Database\Eloquent\Relations\HasOne;
|
|||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'sold_units',
|
'sold_units',
|
||||||
|
'refunded_units',
|
||||||
'reserved_stock',
|
'reserved_stock',
|
||||||
'real_stock',
|
'real_stock',
|
||||||
])]
|
])]
|
||||||
@@ -23,6 +24,7 @@ class Inventory extends Model
|
|||||||
|
|
||||||
protected $attributes = [
|
protected $attributes = [
|
||||||
'sold_units' => 0,
|
'sold_units' => 0,
|
||||||
|
'refunded_units' => 0,
|
||||||
'reserved_stock' => 0,
|
'reserved_stock' => 0,
|
||||||
'real_stock' => 0,
|
'real_stock' => 0,
|
||||||
];
|
];
|
||||||
@@ -31,6 +33,7 @@ class Inventory extends Model
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'sold_units' => 'integer',
|
'sold_units' => 'integer',
|
||||||
|
'refunded_units' => 'integer',
|
||||||
'reserved_stock' => 'integer',
|
'reserved_stock' => 'integer',
|
||||||
'real_stock' => 'integer',
|
'real_stock' => 'integer',
|
||||||
];
|
];
|
||||||
@@ -42,16 +45,16 @@ class Inventory extends Model
|
|||||||
return $this->hasOne(CatalogItem::class);
|
return $this->hasOne(CatalogItem::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return HasOne<Variant, $this> */
|
/** @return HasMany<Variant, $this> */
|
||||||
public function variant(): HasOne
|
public function variants(): HasMany
|
||||||
{
|
{
|
||||||
return $this->hasOne(Variant::class);
|
return $this->hasMany(Variant::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return HasMany<StockReservation, $this> */
|
/** @return HasMany<StockReservationLine, $this> */
|
||||||
public function stockReservations(): HasMany
|
public function stockReservationLines(): HasMany
|
||||||
{
|
{
|
||||||
return $this->hasMany(StockReservation::class);
|
return $this->hasMany(StockReservationLine::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function availableStock(): int
|
public function availableStock(): int
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Commerce\Catalog\Models;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Commerce\Catalog\Models;
|
||||||
|
|
||||||
use App\Domains\Attachable\Models\Attachment;
|
use App\Shared\Attachable\Models\Attachment;
|
||||||
use App\Domains\Event\Models\EventDate;
|
use App\Domains\Ticketing\Event\Models\EventDate;
|
||||||
use App\Domains\Ticket\Models\Ticket;
|
use App\Domains\Ticketing\Ticket\Models\Ticket;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
@@ -20,6 +20,8 @@ use Illuminate\Support\Str;
|
|||||||
'catalog_item_id',
|
'catalog_item_id',
|
||||||
'event_date_id',
|
'event_date_id',
|
||||||
'inventory_id',
|
'inventory_id',
|
||||||
|
'replaced_by_variant_id',
|
||||||
|
'sales_disabled_at',
|
||||||
'descripcion',
|
'descripcion',
|
||||||
'precio',
|
'precio',
|
||||||
])]
|
])]
|
||||||
@@ -37,6 +39,8 @@ class Variant extends Model
|
|||||||
'catalog_item_id' => 'integer',
|
'catalog_item_id' => 'integer',
|
||||||
'event_date_id' => 'integer',
|
'event_date_id' => 'integer',
|
||||||
'inventory_id' => 'integer',
|
'inventory_id' => 'integer',
|
||||||
|
'replaced_by_variant_id' => 'integer',
|
||||||
|
'sales_disabled_at' => 'datetime',
|
||||||
'precio' => 'decimal:2',
|
'precio' => 'decimal:2',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -76,6 +80,40 @@ class Variant extends Model
|
|||||||
return $this->belongsTo(Inventory::class);
|
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> */
|
/** @return HasMany<VariantDefinition, $this> */
|
||||||
public function definitions(): HasMany
|
public function definitions(): HasMany
|
||||||
{
|
{
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Commerce\Catalog\Models;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Requests\AdminApp;
|
namespace App\Domains\Commerce\Catalog\Requests\AdminApp;
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Requests;
|
namespace App\Domains\Commerce\Catalog\Requests;
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Requests;
|
namespace App\Domains\Commerce\Catalog\Requests;
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Requests;
|
namespace App\Domains\Commerce\Catalog\Requests;
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Requests;
|
namespace App\Domains\Commerce\Catalog\Requests;
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Requests;
|
namespace App\Domains\Commerce\Catalog\Requests;
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Resources\AdminApp;
|
namespace App\Domains\Commerce\Catalog\Resources\AdminApp;
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\ProductLayout;
|
use App\Domains\Commerce\Catalog\Enums\ProductLayout;
|
||||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
<?php
|
<?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\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Resources;
|
namespace App\Domains\Commerce\Catalog\Resources;
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Enums\ProductLayout;
|
use App\Domains\Commerce\Catalog\Enums\ProductLayout;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||||
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
|
use App\Domains\Commerce\Catalog\Services\CatalogItemAllowanceService;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
@@ -46,7 +46,7 @@ class CatalogFeaturedItemResource extends JsonResource
|
|||||||
$availableStock,
|
$availableStock,
|
||||||
$remainingUserQuota,
|
$remainingUserQuota,
|
||||||
),
|
),
|
||||||
'variants' => $catalogItem->variants
|
'variants' => $catalogItem->visibleVariants()
|
||||||
->map(function (Variant $variant) use ($catalogItem, $remainingUserQuota): array {
|
->map(function (Variant $variant) use ($catalogItem, $remainingUserQuota): array {
|
||||||
$variantStock = $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
$variantStock = $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||||
? null
|
? null
|
||||||
@@ -115,7 +115,7 @@ class CatalogFeaturedItemResource extends JsonResource
|
|||||||
private function firstImageUrl(CatalogItem $catalogItem): ?string
|
private function firstImageUrl(CatalogItem $catalogItem): ?string
|
||||||
{
|
{
|
||||||
$attachment = $catalogItem->attachments->first()
|
$attachment = $catalogItem->attachments->first()
|
||||||
?? $catalogItem->variants
|
?? $catalogItem->visibleVariants()
|
||||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Resources;
|
namespace App\Domains\Commerce\Catalog\Resources;
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\ItemAttribute;
|
use App\Domains\Commerce\Catalog\Models\ItemAttribute;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||||
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
|
use App\Domains\Commerce\Catalog\Services\CatalogItemAllowanceService;
|
||||||
use App\Domains\Shared\Enums\FieldType;
|
use App\Shared\Enums\FieldType;
|
||||||
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
use App\Domains\Ticketing\Ticket\Resources\ValidityTimeResource;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Resources;
|
namespace App\Domains\Commerce\Catalog\Resources;
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||||
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
|
use App\Domains\Commerce\Catalog\Services\CatalogItemAllowanceService;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
@@ -16,8 +16,9 @@ class CatalogSearchItemResource extends JsonResource
|
|||||||
public function toArray(Request $request): array
|
public function toArray(Request $request): array
|
||||||
{
|
{
|
||||||
$availableStock = $this->availableStock();
|
$availableStock = $this->availableStock();
|
||||||
|
$visibleVariants = $this->visibleVariants();
|
||||||
$attachment = $this->attachments->first()
|
$attachment = $this->attachments->first()
|
||||||
?? $this->variants
|
?? $visibleVariants
|
||||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
@@ -30,7 +31,7 @@ class CatalogSearchItemResource extends JsonResource
|
|||||||
'image' => $attachment?->getTemporaryUrl(1440),
|
'image' => $attachment?->getTemporaryUrl(1440),
|
||||||
'maximum_addable_quantity' => $this->maximumAddable($availableStock),
|
'maximum_addable_quantity' => $this->maximumAddable($availableStock),
|
||||||
'unavailable_message' => $this->unavailableMessage($availableStock),
|
'unavailable_message' => $this->unavailableMessage($availableStock),
|
||||||
'variants' => $this->variants
|
'variants' => $visibleVariants
|
||||||
->map(function (Variant $variant): array {
|
->map(function (Variant $variant): array {
|
||||||
$variantStock = $this->inventory_policy === InventoryPolicy::Unlimited
|
$variantStock = $this->inventory_policy === InventoryPolicy::Unlimited
|
||||||
? null
|
? null
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Resources;
|
namespace App\Domains\Commerce\Catalog\Resources;
|
||||||
|
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Services;
|
namespace App\Domains\Commerce\Catalog\Services;
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
use App\Domains\Commerce\Catalog\Enums\CatalogItemType;
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Models\BundleComponent;
|
use App\Domains\Commerce\Catalog\Models\BundleComponent;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Inventory;
|
use App\Domains\Commerce\Catalog\Models\Inventory;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
class CatalogInventoryService
|
class CatalogInventoryService
|
||||||
@@ -25,6 +25,24 @@ class CatalogInventoryService
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @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
|
public function availableQuantity(CatalogItem|Variant $selection): ?int
|
||||||
{
|
{
|
||||||
if ($selection instanceof CatalogItem
|
if ($selection instanceof CatalogItem
|
||||||
@@ -45,9 +63,14 @@ class CatalogInventoryService
|
|||||||
|
|
||||||
$selection->loadMissing('variants.inventory');
|
$selection->loadMissing('variants.inventory');
|
||||||
|
|
||||||
return $selection->variants->sum(
|
return $selection->variants
|
||||||
fn (Variant $variant): int => $variant->inventory->availableStock(),
|
->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);
|
$requirements = $this->inventoryRequirements($selection);
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Services;
|
namespace App\Domains\Commerce\Catalog\Services;
|
||||||
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
use App\Domains\Commerce\Purchase\Services\UserPurchaseLimitService;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
class CatalogItemAllowanceService
|
class CatalogItemAllowanceService
|
||||||
@@ -1,18 +1,18 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Services;
|
namespace App\Domains\Commerce\Catalog\Services;
|
||||||
|
|
||||||
use App\Domains\Attachable\Models\Attachment;
|
use App\Shared\Attachable\Models\Attachment;
|
||||||
use App\Domains\Attachable\Services\AttachmentService;
|
use App\Shared\Attachable\Services\AttachmentService;
|
||||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
use App\Domains\Commerce\Catalog\Enums\CatalogItemType;
|
||||||
use App\Domains\Catalog\Models\Attribute;
|
use App\Domains\Commerce\Catalog\Models\Attribute;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Category;
|
use App\Domains\Commerce\Catalog\Models\Category;
|
||||||
use App\Domains\Catalog\Models\Inventory;
|
use App\Domains\Commerce\Catalog\Models\Inventory;
|
||||||
use App\Domains\Catalog\Models\ItemAttribute;
|
use App\Domains\Commerce\Catalog\Models\ItemAttribute;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||||
use App\Domains\Event\Models\EventDate;
|
use App\Domains\Ticketing\Event\Models\EventDate;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Pagination\LengthAwarePaginator;
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -205,6 +205,14 @@ class CatalogService
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
$visibleVariants = $catalogItem->visibleVariants();
|
$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
|
$selectedVariant = $variantId === null
|
||||||
? $visibleVariants->first()
|
? $visibleVariants->first()
|
||||||
: $visibleVariants->firstWhere('id', $variantId);
|
: $visibleVariants->firstWhere('id', $variantId);
|
||||||
@@ -230,7 +238,8 @@ class CatalogService
|
|||||||
$startsWithPattern = "{$normalizedTerm}%";
|
$startsWithPattern = "{$normalizedTerm}%";
|
||||||
|
|
||||||
$paginator = CatalogItem::query()
|
$paginator = CatalogItem::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->forTenantCatalog($tenant)
|
||||||
|
->whereAvailable()
|
||||||
->where(function (Builder $query) use ($containsPattern): void {
|
->where(function (Builder $query) use ($containsPattern): void {
|
||||||
$query
|
$query
|
||||||
->whereRaw('LOWER(nombre) LIKE ?', [$containsPattern])
|
->whereRaw('LOWER(nombre) LIKE ?', [$containsPattern])
|
||||||
@@ -278,8 +287,9 @@ class CatalogService
|
|||||||
int $page,
|
int $page,
|
||||||
): LengthAwarePaginator {
|
): LengthAwarePaginator {
|
||||||
return CatalogItem::query()
|
return CatalogItem::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->forTenantCatalog($tenant)
|
||||||
->where('category_id', $category->id)
|
->where('category_id', $category->id)
|
||||||
|
->whereAvailable()
|
||||||
->with([
|
->with([
|
||||||
'attachments',
|
'attachments',
|
||||||
'inventory',
|
'inventory',
|
||||||
@@ -315,9 +325,13 @@ class CatalogService
|
|||||||
->findOrFail($variant->catalog_item_id);
|
->findOrFail($variant->catalog_item_id);
|
||||||
$variant->delete();
|
$variant->delete();
|
||||||
|
|
||||||
if (! $catalogItem->variants()->exists()) {
|
$sellableVariants = $catalogItem->variants()
|
||||||
|
->whereNull('sales_disabled_at')
|
||||||
|
->whereNull('replaced_by_variant_id');
|
||||||
|
|
||||||
|
if (! (clone $sellableVariants)->exists()) {
|
||||||
$this->delete($catalogItem);
|
$this->delete($catalogItem);
|
||||||
} elseif (($minimumPrice = $catalogItem->variants()->min('precio')) !== null) {
|
} elseif (($minimumPrice = (clone $sellableVariants)->min('precio')) !== null) {
|
||||||
$catalogItem->update(['precio' => $minimumPrice]);
|
$catalogItem->update(['precio' => $minimumPrice]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -355,6 +369,8 @@ class CatalogService
|
|||||||
$componentItem = CatalogItem::query()
|
$componentItem = CatalogItem::query()
|
||||||
->whereKey($catalogItemId)
|
->whereKey($catalogItemId)
|
||||||
->where('tenant_code', $bundle->tenant_code)
|
->where('tenant_code', $bundle->tenant_code)
|
||||||
|
->when($bundle->event_id !== null, fn (Builder $query): Builder => $query
|
||||||
|
->where('event_id', $bundle->event_id))
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
if ($componentItem === null) {
|
if ($componentItem === null) {
|
||||||
@@ -390,7 +406,11 @@ class CatalogService
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($variantId !== null && ! $componentItem->variants()->whereKey($variantId)->exists()) {
|
if ($variantId !== null && ! $componentItem->variants()
|
||||||
|
->whereKey($variantId)
|
||||||
|
->whereNull('sales_disabled_at')
|
||||||
|
->whereNull('replaced_by_variant_id')
|
||||||
|
->exists()) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
"components.{$index}.variant_id" => [
|
"components.{$index}.variant_id" => [
|
||||||
__('api.catalog.component_variant_invalid'),
|
__('api.catalog.component_variant_invalid'),
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Services;
|
namespace App\Domains\Commerce\Catalog\Services;
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\FeaturedGroupSource;
|
use App\Domains\Commerce\Catalog\Enums\FeaturedGroupSource;
|
||||||
use App\Domains\Catalog\Enums\GroupLayout;
|
use App\Domains\Commerce\Catalog\Enums\GroupLayout;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
|
||||||
use App\Domains\Catalog\Resources\CatalogFeaturedItemResource;
|
use App\Domains\Commerce\Catalog\Resources\CatalogFeaturedItemResource;
|
||||||
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Pagination\LengthAwarePaginator;
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
|
|
||||||
@@ -19,10 +20,10 @@ class FeaturedGroupService
|
|||||||
private readonly CatalogItemAllowanceService $allowances,
|
private readonly CatalogItemAllowanceService $allowances,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public function itemsResponse(FeaturedGroup $featuredGroup, int $page, ?int $userId = null): array
|
public function itemsResponse(FeaturedGroup $featuredGroup, Tenant $tenant, int $page, ?int $userId = null): array
|
||||||
{
|
{
|
||||||
if ($featuredGroup->group_layout !== GroupLayout::Paginated) {
|
if ($featuredGroup->group_layout !== GroupLayout::Paginated) {
|
||||||
$query = $this->itemsQuery($featuredGroup);
|
$query = $this->itemsQuery($featuredGroup, $tenant);
|
||||||
|
|
||||||
if ($featuredGroup->group_layout === GroupLayout::Single) {
|
if ($featuredGroup->group_layout === GroupLayout::Single) {
|
||||||
$query->limit(1);
|
$query->limit(1);
|
||||||
@@ -35,7 +36,7 @@ class FeaturedGroupService
|
|||||||
return CatalogFeaturedItemResource::collection($items)->resolve();
|
return CatalogFeaturedItemResource::collection($items)->resolve();
|
||||||
}
|
}
|
||||||
|
|
||||||
$paginator = $this->paginateItems($featuredGroup, $page);
|
$paginator = $this->paginateItems($featuredGroup, $tenant, $page);
|
||||||
$this->attachGroup($paginator->getCollection(), $featuredGroup);
|
$this->attachGroup($paginator->getCollection(), $featuredGroup);
|
||||||
$this->allowances->attach($paginator->getCollection(), $userId);
|
$this->allowances->attach($paginator->getCollection(), $userId);
|
||||||
|
|
||||||
@@ -45,10 +46,11 @@ class FeaturedGroupService
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @return Builder<CatalogItem> */
|
/** @return Builder<CatalogItem> */
|
||||||
private function itemsQuery(FeaturedGroup $featuredGroup): Builder
|
private function itemsQuery(FeaturedGroup $featuredGroup, Tenant $tenant): Builder
|
||||||
{
|
{
|
||||||
$query = CatalogItem::query()
|
$query = CatalogItem::query()
|
||||||
->where('catalog_items.tenant_code', $featuredGroup->tenant_code)
|
->forTenantCatalog($tenant)
|
||||||
|
->whereAvailable()
|
||||||
->where(function (Builder $query): void {
|
->where(function (Builder $query): void {
|
||||||
$query
|
$query
|
||||||
->whereDoesntHave('category')
|
->whereDoesntHave('category')
|
||||||
@@ -81,15 +83,18 @@ class FeaturedGroupService
|
|||||||
FeaturedGroupSource::Category => $query
|
FeaturedGroupSource::Category => $query
|
||||||
->where('catalog_items.category_id', $featuredGroup->category_id)
|
->where('catalog_items.category_id', $featuredGroup->category_id)
|
||||||
->orderBy('catalog_items.id'),
|
->orderBy('catalog_items.id'),
|
||||||
FeaturedGroupSource::All => $query->orderBy('catalog_items.id'),
|
FeaturedGroupSource::All => $query
|
||||||
|
->orderBy('catalog_items.group_order')
|
||||||
|
->orderBy('catalog_items.id'),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private function paginateItems(
|
private function paginateItems(
|
||||||
FeaturedGroup $featuredGroup,
|
FeaturedGroup $featuredGroup,
|
||||||
|
Tenant $tenant,
|
||||||
int $page,
|
int $page,
|
||||||
): LengthAwarePaginator {
|
): LengthAwarePaginator {
|
||||||
$paginator = $this->itemsQuery($featuredGroup)->paginate(
|
$paginator = $this->itemsQuery($featuredGroup, $tenant)->paginate(
|
||||||
perPage: self::ITEMS_PER_PAGE,
|
perPage: self::ITEMS_PER_PAGE,
|
||||||
pageName: 'page',
|
pageName: 'page',
|
||||||
page: $page,
|
page: $page,
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Services;
|
namespace App\Domains\Commerce\Catalog\Services;
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\FeaturedGroupSource;
|
use App\Domains\Commerce\Catalog\Enums\FeaturedGroupSource;
|
||||||
use App\Domains\Catalog\Enums\GroupLayout;
|
use App\Domains\Commerce\Catalog\Enums\GroupLayout;
|
||||||
use App\Domains\Catalog\Enums\ProductLayout;
|
use App\Domains\Commerce\Catalog\Enums\ProductLayout;
|
||||||
use App\Domains\Catalog\Models\Category;
|
use App\Domains\Commerce\Catalog\Models\Category;
|
||||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use Illuminate\Database\Eloquent\Collection;
|
use Illuminate\Database\Eloquent\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Services;
|
namespace App\Domains\Commerce\Catalog\Services;
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\ItemAttribute;
|
use App\Domains\Commerce\Catalog\Models\ItemAttribute;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
class VariantSelectionService
|
class VariantSelectionService
|
||||||
@@ -9,7 +9,7 @@ Modela y publica la oferta comercial del tenant: productos, variantes, categorí
|
|||||||
- `CatalogItem` es la raíz del producto y se relaciona con tenant, categoría, marca, inventario, variantes, atributos, adjuntos y grupos destacados.
|
- `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.
|
- `Variant`, `ItemAttribute`, `Attribute`, `AttributeOption` y `VariantDefinition` describen opciones comercializables.
|
||||||
- `Inventory` administra stock disponible, reservado y comprado.
|
- `Inventory` administra stock disponible, reservado y comprado.
|
||||||
- `StockReservation` atribuye cada unidad reservada a un ítem de carrito y, durante checkout, a una compra, con estados `active`, `committed`, `released` y `expired`.
|
- `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.
|
- `Category` soporta jerarquía y categorías globales o propias del tenant.
|
||||||
- `FeaturedGroup` y `FeaturedItem` organizan secciones destacadas.
|
- `FeaturedGroup` y `FeaturedItem` organizan secciones destacadas.
|
||||||
- `BundleComponent` representa los componentes de un paquete.
|
- `BundleComponent` representa los componentes de un paquete.
|
||||||
@@ -18,7 +18,8 @@ Modela y publica la oferta comercial del tenant: productos, variantes, categorí
|
|||||||
|
|
||||||
- `CatalogService`: alta, búsqueda, detalle, listado por categoría y eliminación.
|
- `CatalogService`: alta, búsqueda, detalle, listado por categoría y eliminación.
|
||||||
- `CatalogInventoryService`: consulta, reserva, libera y confirma inventario.
|
- `CatalogInventoryService`: consulta, reserva, libera y confirma inventario.
|
||||||
- `StockReservationService`: mantiene el ledger de reservas sincronizado con `Inventory.reserved_stock`.
|
- `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.
|
- `FeaturedGroupService`: pagina los ítems destacados para la tienda.
|
||||||
- `OnTicketFeaturedGroupService`: administra grupos destacados del panel para sitios de tickets.
|
- `OnTicketFeaturedGroupService`: administra grupos destacados del panel para sitios de tickets.
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use App\Domains\Catalog\Controllers\AdminApp\OnTicketFeaturedGroupController;
|
use App\Domains\Commerce\Catalog\Controllers\AdminApp\OnTicketFeaturedGroupController;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
Route::prefix('v1/adminapp/tenant')
|
Route::prefix('v1/adminapp/tenant')
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use App\Domains\Catalog\Controllers\CatalogController;
|
use App\Domains\Commerce\Catalog\Controllers\CatalogController;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
||||||
@@ -13,7 +13,6 @@ Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
|||||||
->name('categories.show');
|
->name('categories.show');
|
||||||
Route::get('catalog-items/{catalogItem}', [CatalogController::class, 'show']);
|
Route::get('catalog-items/{catalogItem}', [CatalogController::class, 'show']);
|
||||||
Route::post('catalog-items/{catalogItem}/variant-options', [CatalogController::class, 'variantOptions']);
|
Route::post('catalog-items/{catalogItem}/variant-options', [CatalogController::class, 'variantOptions']);
|
||||||
Route::post('catalog-items', [CatalogController::class, 'store']);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
require __DIR__.'/adminapp.php';
|
require __DIR__.'/adminapp.php';
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Controllers;
|
namespace App\Domains\Commerce\Purchase\Controllers;
|
||||||
|
|
||||||
use App\Domains\Integration\Services\TelepagosIntegrationService;
|
use App\Shared\Integration\Services\TelepagosIntegrationService;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||||
use App\Domains\Purchase\Requests\PaymentIntentRequest;
|
use App\Domains\Commerce\Purchase\Requests\PaymentIntentRequest;
|
||||||
use App\Domains\Purchase\Requests\StartCheckoutRequest;
|
use App\Domains\Commerce\Purchase\Requests\StartCheckoutRequest;
|
||||||
use App\Domains\Purchase\Requests\UpdatePurchaseCustomerRequest;
|
use App\Domains\Commerce\Purchase\Requests\UpdatePurchaseCustomerRequest;
|
||||||
use App\Domains\Purchase\Resources\PurchaseResource;
|
use App\Domains\Commerce\Purchase\Resources\PurchaseResource;
|
||||||
use App\Domains\Purchase\Services\Checkout\PurchaseResponseLoader;
|
use App\Domains\Commerce\Purchase\Services\Checkout\PurchaseResponseLoader;
|
||||||
use App\Domains\Purchase\Services\CheckoutService;
|
use App\Domains\Commerce\Purchase\Services\CheckoutService;
|
||||||
use App\Domains\Purchase\Services\PurchaseStateGuard;
|
use App\Domains\Commerce\Purchase\Services\PurchaseStateGuard;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -36,6 +36,7 @@ class PurchaseController extends Controller
|
|||||||
|
|
||||||
return PurchaseResource::collection(
|
return PurchaseResource::collection(
|
||||||
Purchase::query()
|
Purchase::query()
|
||||||
|
->with('stockReservation')
|
||||||
->where('tenant_codigo', $tenant->codigo)
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
->where('user_id', $request->user()->id)
|
->where('user_id', $request->user()->id)
|
||||||
->when($statuses !== [], fn ($query) => $query->whereIn('status', $statuses))
|
->when($statuses !== [], fn ($query) => $query->whereIn('status', $statuses))
|
||||||
@@ -92,7 +93,6 @@ class PurchaseController extends Controller
|
|||||||
PaymentIntentRequest $request,
|
PaymentIntentRequest $request,
|
||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
Purchase $compra,
|
Purchase $compra,
|
||||||
CheckoutService $checkoutService,
|
|
||||||
PurchaseStateGuard $purchaseState,
|
PurchaseStateGuard $purchaseState,
|
||||||
): JsonResponse {
|
): JsonResponse {
|
||||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||||
@@ -101,7 +101,12 @@ class PurchaseController extends Controller
|
|||||||
? preg_replace('/\D+/', '', (string) $request->validated('transfer_payer_dni'))
|
? preg_replace('/\D+/', '', (string) $request->validated('transfer_payer_dni'))
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
$updated = DB::transaction(function () use ($compra, $method, $purchaseState, $transferPayerDni): bool {
|
$updated = DB::transaction(function () use (
|
||||||
|
$compra,
|
||||||
|
$method,
|
||||||
|
$purchaseState,
|
||||||
|
$transferPayerDni,
|
||||||
|
): bool {
|
||||||
/** @var Purchase|null $purchase */
|
/** @var Purchase|null $purchase */
|
||||||
$purchase = Purchase::query()
|
$purchase = Purchase::query()
|
||||||
->whereKey($compra->getKey())
|
->whereKey($compra->getKey())
|
||||||
@@ -128,9 +133,6 @@ class PurchaseController extends Controller
|
|||||||
$purchaseUpdate = [
|
$purchaseUpdate = [
|
||||||
'payment_method' => $method,
|
'payment_method' => $method,
|
||||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||||
'expires_at' => now()->addMinutes(
|
|
||||||
max(1, (int) config("purchase.payment_expiration_minutes.{$method}", 30))
|
|
||||||
),
|
|
||||||
'total' => $purchase->calculateCurrentTotalAmount(),
|
'total' => $purchase->calculateCurrentTotalAmount(),
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -150,7 +152,6 @@ class PurchaseController extends Controller
|
|||||||
|
|
||||||
$compra->refresh();
|
$compra->refresh();
|
||||||
$totalAmount = (float) $compra->total;
|
$totalAmount = (float) $compra->total;
|
||||||
$checkoutService->syncReservationExpiration($compra);
|
|
||||||
|
|
||||||
if ($method === 'transfer') {
|
if ($method === 'transfer') {
|
||||||
$telepagosService = new TelepagosIntegrationService;
|
$telepagosService = new TelepagosIntegrationService;
|
||||||
@@ -1,8 +1,7 @@
|
|||||||
<?php
|
<?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\Foundation\Events\Dispatchable;
|
||||||
use Illuminate\Queue\SerializesModels;
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
|
||||||
@@ -10,5 +9,5 @@ class PurchasePaid
|
|||||||
{
|
{
|
||||||
use Dispatchable, SerializesModels;
|
use Dispatchable, SerializesModels;
|
||||||
|
|
||||||
public function __construct(public readonly Purchase $purchase) {}
|
public function __construct(public readonly int $purchaseId) {}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Exceptions;
|
namespace App\Domains\Commerce\Purchase\Exceptions;
|
||||||
|
|
||||||
use RuntimeException;
|
use RuntimeException;
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Exceptions;
|
namespace App\Domains\Commerce\Purchase\Exceptions;
|
||||||
|
|
||||||
use RuntimeException;
|
use RuntimeException;
|
||||||
|
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Exceptions;
|
namespace App\Domains\Commerce\Purchase\Exceptions;
|
||||||
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
class PurchaseLimitExceededException extends ValidationException
|
class PurchaseLimitExceededException extends ValidationException
|
||||||
@@ -1,29 +1,30 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Models;
|
namespace App\Domains\Commerce\Purchase\Models;
|
||||||
|
|
||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Core\Auth\Models\User;
|
||||||
use App\Domains\Cart\Models\Cart;
|
use App\Domains\Commerce\Cart\Models\Cart;
|
||||||
use App\Domains\Catalog\Models\StockReservation;
|
use App\Domains\Commerce\Catalog\Models\StockReservation;
|
||||||
use App\Domains\Logging\Models\Concerns\LogsValueChanges;
|
use App\Shared\Logging\Models\Concerns\LogsValueChanges;
|
||||||
use App\Domains\Purchase\Events\PurchasePaid;
|
use App\Domains\Commerce\Purchase\Events\PurchasePaid;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use App\Domains\Ticket\Models\Ticket;
|
use App\Domains\Ticketing\Ticket\Models\Ticket;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'cart_id',
|
'cart_id',
|
||||||
|
'stock_reservation_id',
|
||||||
'tenant_codigo',
|
'tenant_codigo',
|
||||||
'user_id',
|
'user_id',
|
||||||
'status',
|
'status',
|
||||||
'payment_method',
|
'payment_method',
|
||||||
'expires_at',
|
|
||||||
'total',
|
'total',
|
||||||
'dni',
|
'dni',
|
||||||
'transfer_payer_dni',
|
'transfer_payer_dni',
|
||||||
@@ -51,6 +52,14 @@ class Purchase extends Model
|
|||||||
|
|
||||||
public const STATUS_SUPERSEDED = 'superseded';
|
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> */
|
/** @return list<string> */
|
||||||
public static function statuses(): array
|
public static function statuses(): array
|
||||||
{
|
{
|
||||||
@@ -66,6 +75,68 @@ class Purchase extends Model
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @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';
|
protected $table = 'compras';
|
||||||
|
|
||||||
/** @var array<int, string> */
|
/** @var array<int, string> */
|
||||||
@@ -77,8 +148,8 @@ class Purchase extends Model
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'cart_id' => 'integer',
|
'cart_id' => 'integer',
|
||||||
|
'stock_reservation_id' => 'integer',
|
||||||
'user_id' => 'integer',
|
'user_id' => 'integer',
|
||||||
'expires_at' => 'datetime',
|
|
||||||
'total' => 'decimal:2',
|
'total' => 'decimal:2',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -115,18 +186,21 @@ class Purchase extends Model
|
|||||||
return $this->hasMany(PurchaseItem::class, 'compra_id');
|
return $this->hasMany(PurchaseItem::class, 'compra_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return HasManyThrough<Ticket, PurchaseItem, $this> */
|
||||||
* @return HasMany<Ticket, $this>
|
public function tickets(): HasManyThrough
|
||||||
*/
|
|
||||||
public function tickets(): HasMany
|
|
||||||
{
|
{
|
||||||
return $this->hasMany(Ticket::class, 'source_purchase_id');
|
return $this->hasManyThrough(
|
||||||
|
Ticket::class,
|
||||||
|
PurchaseItem::class,
|
||||||
|
'compra_id',
|
||||||
|
'source_purchase_item_id',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return HasMany<StockReservation, $this> */
|
/** @return BelongsTo<StockReservation, $this> */
|
||||||
public function stockReservations(): HasMany
|
public function stockReservation(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->hasMany(StockReservation::class);
|
return $this->belongsTo(StockReservation::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -145,6 +219,12 @@ class Purchase extends Model
|
|||||||
return $this->hasMany(TelepagosPayment::class, 'compra_id');
|
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
|
public function getTotalAmount(): float
|
||||||
{
|
{
|
||||||
if ($this->total !== null) {
|
if ($this->total !== null) {
|
||||||
@@ -193,7 +273,7 @@ class Purchase extends Model
|
|||||||
'status' => self::STATUS_PAID,
|
'status' => self::STATUS_PAID,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
PurchasePaid::dispatch($this);
|
PurchasePaid::dispatch($this->getKey());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,17 @@
|
|||||||
<?php
|
<?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\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
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\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'compra_id',
|
'compra_id',
|
||||||
@@ -56,6 +59,18 @@ class PurchaseItem extends Model
|
|||||||
return $this->belongsTo(Purchase::class, 'compra_id');
|
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> */
|
/** @return BelongsTo<Attachment, $this> */
|
||||||
public function imageAttachment(): BelongsTo
|
public function imageAttachment(): BelongsTo
|
||||||
{
|
{
|
||||||
@@ -1,15 +1,15 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Models;
|
namespace App\Domains\Commerce\Purchase\Models;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'compra_id',
|
'compra_id',
|
||||||
'matched_purchase_ids',
|
|
||||||
'cuit_buyer',
|
'cuit_buyer',
|
||||||
'cvu_buyer',
|
'cvu_buyer',
|
||||||
'amount',
|
'amount',
|
||||||
@@ -30,7 +30,6 @@ class TelepagosPayment extends Model
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'compra_id' => 'integer',
|
'compra_id' => 'integer',
|
||||||
'matched_purchase_ids' => 'array',
|
|
||||||
'amount' => 'decimal:2',
|
'amount' => 'decimal:2',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -42,4 +41,10 @@ class TelepagosPayment extends Model
|
|||||||
{
|
{
|
||||||
return $this->belongsTo(Purchase::class, 'compra_id');
|
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
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Models;
|
namespace App\Domains\Commerce\Purchase\Models;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Requests;
|
namespace App\Domains\Commerce\Purchase\Requests;
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Requests;
|
namespace App\Domains\Commerce\Purchase\Requests;
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Requests;
|
namespace App\Domains\Commerce\Purchase\Requests;
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Resources;
|
namespace App\Domains\Commerce\Purchase\Resources;
|
||||||
|
|
||||||
use App\Domains\Purchase\Models\PurchaseItem;
|
use App\Domains\Commerce\Purchase\Models\PurchaseItem;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Core\Tenant\Models\StorefrontWebsiteType;
|
||||||
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
@@ -14,7 +15,11 @@ class PurchaseItemResource extends JsonResource
|
|||||||
public function toArray(Request $request): array
|
public function toArray(Request $request): array
|
||||||
{
|
{
|
||||||
$tenant = $request->route('tenant');
|
$tenant = $request->route('tenant');
|
||||||
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
|
$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
|
$imageUrl = $displayImage
|
||||||
? $this->imageAttachment?->getTemporaryUrl(1440)
|
? $this->imageAttachment?->getTemporaryUrl(1440)
|
||||||
@@ -31,7 +36,7 @@ class PurchaseItemResource extends JsonResource
|
|||||||
'nombre' => $this->item_nombre,
|
'nombre' => $this->item_nombre,
|
||||||
'descripcion' => $this->descripcion,
|
'descripcion' => $this->descripcion,
|
||||||
'slug' => $this->slug,
|
'slug' => $this->slug,
|
||||||
'imagen' => $imageUrl,
|
'imagen' => $this->when(! $usesEventSummary, $imageUrl),
|
||||||
'attributes' => $this->variant_attributes ?? [],
|
'attributes' => $this->variant_attributes ?? [],
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Services\Checkout;
|
namespace App\Domains\Commerce\Purchase\Services\Checkout;
|
||||||
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Inventory;
|
use App\Domains\Commerce\Catalog\Models\Inventory;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@ class CatalogSelectionResolver
|
|||||||
/** @var CatalogItem|null $catalogItem */
|
/** @var CatalogItem|null $catalogItem */
|
||||||
$catalogItem = CatalogItem::query()
|
$catalogItem = CatalogItem::query()
|
||||||
->whereKey($catalogItemId)
|
->whereKey($catalogItemId)
|
||||||
->where('tenant_code', $tenant->codigo)
|
->forTenantCatalog($tenant)
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
@@ -28,6 +28,12 @@ class CatalogSelectionResolver
|
|||||||
throw new NotFoundHttpException('Catalog item not found for tenant.');
|
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 ($catalogItem->isBundle()) {
|
||||||
if ($variantId !== null) {
|
if ($variantId !== null) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
@@ -41,6 +47,17 @@ class CatalogSelectionResolver
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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;
|
return $catalogItem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,6 +87,12 @@ class CatalogSelectionResolver
|
|||||||
throw new NotFoundHttpException('Variant not found for catalog item.');
|
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('catalogItem', $catalogItem);
|
||||||
$variant->setRelation(
|
$variant->setRelation(
|
||||||
'inventory',
|
'inventory',
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Services\Checkout;
|
namespace App\Domains\Commerce\Purchase\Services\Checkout;
|
||||||
|
|
||||||
use App\Domains\Cart\Models\CartItem;
|
use App\Domains\Commerce\Cart\Models\CartItem;
|
||||||
use App\Domains\Catalog\Services\StockReservationService;
|
use App\Domains\Commerce\Catalog\Services\StockReservationService;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||||
use App\Domains\Purchase\Services\PurchaseStateGuard;
|
use App\Domains\Commerce\Purchase\Services\PurchaseStateGuard;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
@@ -61,10 +61,7 @@ class CompleteCheckoutService
|
|||||||
|
|
||||||
$this->purchaseState->lockCurrentCart($purchase);
|
$this->purchaseState->lockCurrentCart($purchase);
|
||||||
|
|
||||||
if (
|
if ($purchase->status !== Purchase::STATUS_PENDING_PAYMENT) {
|
||||||
$purchase->status !== Purchase::STATUS_PENDING_PAYMENT
|
|
||||||
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
|
|
||||||
) {
|
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'purchase' => __('api.purchase.not_available_for_review'),
|
'purchase' => __('api.purchase.not_available_for_review'),
|
||||||
]);
|
]);
|
||||||
@@ -72,9 +69,8 @@ class CompleteCheckoutService
|
|||||||
|
|
||||||
$purchase->update([
|
$purchase->update([
|
||||||
'status' => Purchase::STATUS_IN_REVIEW,
|
'status' => Purchase::STATUS_IN_REVIEW,
|
||||||
'expires_at' => null,
|
|
||||||
]);
|
]);
|
||||||
$this->reservations->syncPurchaseExpiration($purchase);
|
$this->reservations->clearExpirationForReview($purchase);
|
||||||
|
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
});
|
});
|
||||||
@@ -161,13 +157,14 @@ class CompleteCheckoutService
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
}
|
||||||
$this->reservations->commit($cartItem, $selection, $purchase);
|
|
||||||
} catch (\InvalidArgumentException) {
|
try {
|
||||||
throw ValidationException::withMessages([
|
$this->reservations->commit($purchase);
|
||||||
'items' => __('api.purchase.inconsistent_reservation'),
|
} catch (\InvalidArgumentException) {
|
||||||
]);
|
throw ValidationException::withMessages([
|
||||||
}
|
'items' => __('api.purchase.inconsistent_reservation'),
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->sourceCart->finalize($purchase);
|
$this->sourceCart->finalize($purchase);
|
||||||
@@ -194,7 +191,7 @@ class CompleteCheckoutService
|
|||||||
|
|
||||||
private function loadPurchase(Purchase $purchase): Purchase
|
private function loadPurchase(Purchase $purchase): Purchase
|
||||||
{
|
{
|
||||||
return $purchase->load(['items.imageAttachment']);
|
return $purchase->load(['items.imageAttachment', 'stockReservation']);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function itemKey(int $catalogItemId, ?int $variantId): string
|
private function itemKey(int $catalogItemId, ?int $variantId): string
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Services\Checkout;
|
namespace App\Domains\Commerce\Purchase\Services\Checkout;
|
||||||
|
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||||
use App\Domains\Purchase\Services\PurchaseStateGuard;
|
use App\Domains\Commerce\Purchase\Services\PurchaseStateGuard;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Services\Checkout;
|
namespace App\Domains\Commerce\Purchase\Services\Checkout;
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\InventorySubject;
|
use App\Domains\Commerce\Catalog\Enums\InventorySubject;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||||
|
|
||||||
class InsufficientStockMessageBuilder
|
class InsufficientStockMessageBuilder
|
||||||
{
|
{
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Services\Checkout;
|
namespace App\Domains\Commerce\Purchase\Services\Checkout;
|
||||||
|
|
||||||
use App\Domains\Attachable\Models\Attachment;
|
use App\Shared\Attachable\Models\Attachment;
|
||||||
use App\Domains\Cart\Models\CartItem;
|
use App\Domains\Commerce\Cart\Models\CartItem;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
class PurchaseItemSnapshotFactory
|
class PurchaseItemSnapshotFactory
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Commerce\Purchase\Services\Checkout;
|
||||||
|
|
||||||
|
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||||
|
use App\Domains\Core\Tenant\Models\StorefrontWebsiteType;
|
||||||
|
|
||||||
|
class PurchaseResponseLoader
|
||||||
|
{
|
||||||
|
public function load(Purchase $purchase): Purchase
|
||||||
|
{
|
||||||
|
$purchase->loadMissing('tenant.storefrontWebsiteType');
|
||||||
|
$usesEventSummary = $purchase->tenant?->storefrontWebsiteType?->checkout_summary_type
|
||||||
|
=== StorefrontWebsiteType::CHECKOUT_SUMMARY_EVENT;
|
||||||
|
$relations = [
|
||||||
|
'tenant',
|
||||||
|
'items.sourceCatalogItem.event.attachment',
|
||||||
|
'stockReservation',
|
||||||
|
];
|
||||||
|
|
||||||
|
if (! $usesEventSummary) {
|
||||||
|
$relations[] = 'items.imageAttachment';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
$purchase->status === Purchase::STATUS_IN_REVIEW
|
||||||
|
&& $purchase->payment_method === 'transfer'
|
||||||
|
) {
|
||||||
|
$relations[] = 'telepagosPaymentCandidates.payment';
|
||||||
|
}
|
||||||
|
|
||||||
|
return $purchase->load($relations);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Commerce\Purchase\Services\Checkout;
|
||||||
|
|
||||||
|
use App\Domains\Commerce\Cart\Models\Cart;
|
||||||
|
use App\Domains\Commerce\Cart\Models\CartItem;
|
||||||
|
use App\Domains\Commerce\Catalog\Models\StockReservation;
|
||||||
|
use App\Domains\Commerce\Catalog\Services\StockReservationService;
|
||||||
|
use App\Domains\Commerce\Purchase\Exceptions\PurchaseExpiredException;
|
||||||
|
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
|
class ReleaseCheckoutService
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly StockReservationService $reservations,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function cancel(Purchase $purchase): Purchase
|
||||||
|
{
|
||||||
|
return $this->release($purchase, Purchase::STATUS_CANCELLED);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function cancelFromAdmin(Purchase $purchase): Purchase
|
||||||
|
{
|
||||||
|
return $this->release($purchase, Purchase::STATUS_CANCELLED, allowInReviewCancellation: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function expire(Purchase $purchase): Purchase
|
||||||
|
{
|
||||||
|
return $this->release($purchase, Purchase::STATUS_EXPIRED);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function release(
|
||||||
|
Purchase $purchase,
|
||||||
|
string $targetStatus,
|
||||||
|
bool $allowInReviewCancellation = false,
|
||||||
|
): Purchase {
|
||||||
|
return DB::transaction(function () use (
|
||||||
|
$purchase,
|
||||||
|
$targetStatus,
|
||||||
|
$allowInReviewCancellation,
|
||||||
|
): Purchase {
|
||||||
|
$purchase = $this->lockPurchase($purchase);
|
||||||
|
|
||||||
|
if ($purchase->status === Purchase::STATUS_EXPIRED
|
||||||
|
&& $targetStatus === Purchase::STATUS_CANCELLED) {
|
||||||
|
return $this->loadPurchase($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($purchase->status === Purchase::STATUS_EXPIRED
|
||||||
|
&& $targetStatus !== Purchase::STATUS_EXPIRED) {
|
||||||
|
throw new PurchaseExpiredException;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||||
|
if ($targetStatus === Purchase::STATUS_EXPIRED) {
|
||||||
|
return $this->loadPurchase($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'purchase' => __('api.purchase.paid_cannot_cancel'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
$purchase->status === Purchase::STATUS_IN_REVIEW
|
||||||
|
&& $targetStatus === Purchase::STATUS_CANCELLED
|
||||||
|
&& ! $allowInReviewCancellation
|
||||||
|
) {
|
||||||
|
return $this->createNewCartWithoutCancelling($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->isAlreadyReleased($purchase)) {
|
||||||
|
return $this->loadPurchase($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
|
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
|
||||||
|
|
||||||
|
// Leaving checkout is allowed at the exact instant the reservation
|
||||||
|
// expires. Finish the expiration while holding the purchase lock so
|
||||||
|
// the request is idempotent with the scheduled expiration job.
|
||||||
|
if ($targetStatus === Purchase::STATUS_CANCELLED
|
||||||
|
&& $this->hasOverdueActiveReservation($purchase)) {
|
||||||
|
$targetStatus = Purchase::STATUS_EXPIRED;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($targetStatus === Purchase::STATUS_CANCELLED
|
||||||
|
&& $cart?->status === 'active'
|
||||||
|
&& in_array($purchase->status, [
|
||||||
|
Purchase::STATUS_CREATED,
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
], true)) {
|
||||||
|
if ($this->hasUnavailableVariants($cart)) {
|
||||||
|
$this->releasePurchaseReservations($purchase, $targetStatus, $cart);
|
||||||
|
$cart->update([
|
||||||
|
'status' => Cart::STATUS_EXPIRED,
|
||||||
|
'current_purchase_id' => null,
|
||||||
|
'current_stock_reservation_id' => null,
|
||||||
|
]);
|
||||||
|
} else {
|
||||||
|
$this->reservations->returnToCart($purchase, $cart);
|
||||||
|
}
|
||||||
|
$purchase->update(['status' => Purchase::STATUS_CANCELLED]);
|
||||||
|
|
||||||
|
return $this->loadPurchase($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
$targetStatus === Purchase::STATUS_EXPIRED
|
||||||
|
&& (! in_array($purchase->status, [
|
||||||
|
Purchase::STATUS_CREATED,
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
], true) || ! $this->hasOverdueActiveReservation($purchase))
|
||||||
|
) {
|
||||||
|
return $this->loadPurchase($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->releasePurchaseReservations($purchase, $targetStatus, $cart);
|
||||||
|
|
||||||
|
$purchase->update(['status' => $targetStatus]);
|
||||||
|
|
||||||
|
return $this->loadPurchase($purchase);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function hasUnavailableVariants(Cart $cart): bool
|
||||||
|
{
|
||||||
|
return $cart->items()
|
||||||
|
->whereNotNull('variant_id')
|
||||||
|
->with(['variant.eventDate', 'variant.eventDates'])
|
||||||
|
->lockForUpdate()
|
||||||
|
->get()
|
||||||
|
->contains(fn (CartItem $item): bool => $item->variant === null
|
||||||
|
|| ! $item->variant->isSellable());
|
||||||
|
}
|
||||||
|
|
||||||
|
private function releasePurchaseReservations(
|
||||||
|
Purchase $purchase,
|
||||||
|
string $targetStatus,
|
||||||
|
?Cart $cart,
|
||||||
|
): void {
|
||||||
|
try {
|
||||||
|
$this->reservations->releaseForPurchase(
|
||||||
|
$purchase,
|
||||||
|
$targetStatus === Purchase::STATUS_EXPIRED
|
||||||
|
? StockReservation::STATUS_EXPIRED
|
||||||
|
: StockReservation::STATUS_RELEASED,
|
||||||
|
$targetStatus === Purchase::STATUS_CANCELLED
|
||||||
|
? StockReservationService::REASON_PURCHASE_CANCELLED
|
||||||
|
: ($targetStatus === Purchase::STATUS_REJECTED
|
||||||
|
? StockReservationService::REASON_PAYMENT_REJECTED
|
||||||
|
: null),
|
||||||
|
);
|
||||||
|
} catch (\InvalidArgumentException) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'items' => __('api.purchase.inconsistent_reservation'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($cart === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($targetStatus === Purchase::STATUS_EXPIRED
|
||||||
|
&& in_array($cart->status, [Cart::STATUS_ACTIVE, Cart::STATUS_CHECKOUT], true)) {
|
||||||
|
Cart::query()
|
||||||
|
->whereKey($cart->getKey())
|
||||||
|
->where('current_purchase_id', $purchase->getKey())
|
||||||
|
->where('current_stock_reservation_id', $purchase->stock_reservation_id)
|
||||||
|
->update([
|
||||||
|
'status' => Cart::STATUS_EXPIRED,
|
||||||
|
'current_purchase_id' => null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($cart->status === Cart::STATUS_ACTIVE) {
|
||||||
|
$cartUpdate = [
|
||||||
|
'current_purchase_id' => null,
|
||||||
|
'current_stock_reservation_id' => null,
|
||||||
|
];
|
||||||
|
|
||||||
|
Cart::query()
|
||||||
|
->whereKey($cart->getKey())
|
||||||
|
->where('current_purchase_id', $purchase->getKey())
|
||||||
|
->update($cartUpdate);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($cart->status !== Cart::STATUS_CHECKOUT) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $cart->trashed()) {
|
||||||
|
$cart->update(['status' => Cart::STATUS_CONVERTED]);
|
||||||
|
$cart->delete();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createNewCartWithoutCancelling(Purchase $purchase): Purchase
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($purchase): Purchase {
|
||||||
|
$purchase = $this->lockPurchase($purchase);
|
||||||
|
|
||||||
|
if ($purchase->status !== Purchase::STATUS_IN_REVIEW || $purchase->user_id === null) {
|
||||||
|
return $this->loadPurchase($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var Cart|null $sourceCart */
|
||||||
|
$sourceCart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
|
||||||
|
if ($sourceCart !== null && ! $sourceCart->trashed() && $sourceCart->status === 'active') {
|
||||||
|
$sourceCart->update(['status' => 'checkout']);
|
||||||
|
}
|
||||||
|
|
||||||
|
Cart::query()->firstOrCreate([
|
||||||
|
'tenant_codigo' => $purchase->tenant_codigo,
|
||||||
|
'user_id' => $purchase->user_id,
|
||||||
|
'guest_token' => null,
|
||||||
|
'status' => 'active',
|
||||||
|
'origin' => Cart::ORIGIN_USER,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $this->loadPurchase($purchase);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function isAlreadyReleased(Purchase $purchase): bool
|
||||||
|
{
|
||||||
|
return in_array($purchase->status, [
|
||||||
|
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 hasOverdueActiveReservation(Purchase $purchase): bool
|
||||||
|
{
|
||||||
|
/** @var StockReservation|null $reservation */
|
||||||
|
$reservation = $purchase->stockReservation()->lockForUpdate()->first();
|
||||||
|
|
||||||
|
return $reservation !== null
|
||||||
|
&& $reservation->status === StockReservation::STATUS_ACTIVE
|
||||||
|
&& $reservation->expires_at !== null
|
||||||
|
&& ! $reservation->expires_at->isFuture();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Services\Checkout;
|
namespace App\Domains\Commerce\Purchase\Services\Checkout;
|
||||||
|
|
||||||
use App\Domains\Cart\Models\Cart;
|
use App\Domains\Commerce\Cart\Models\Cart;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||||
|
|
||||||
class SourceCartService
|
class SourceCartService
|
||||||
{
|
{
|
||||||
@@ -1,17 +1,20 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Services\Checkout;
|
namespace App\Domains\Commerce\Purchase\Services\Checkout;
|
||||||
|
|
||||||
use App\Domains\Cart\Models\Cart;
|
use App\Domains\Commerce\Cart\Models\Cart;
|
||||||
use App\Domains\Cart\Models\CartItem;
|
use App\Domains\Commerce\Cart\Models\CartItem;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Commerce\Cart\Services\CartVariantReplacementService;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Commerce\Catalog\Exceptions\StockReservationExpiredException;
|
||||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Services\StockReservationService;
|
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||||
use App\Domains\Purchase\Exceptions\InsufficientStockException;
|
use App\Domains\Commerce\Catalog\Services\CatalogInventoryService;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Commerce\Catalog\Services\StockReservationService;
|
||||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
use App\Domains\Commerce\Purchase\Exceptions\InsufficientStockException;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||||
|
use App\Domains\Commerce\Purchase\Services\UserPurchaseLimitService;
|
||||||
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
@@ -27,6 +30,7 @@ class StartCheckoutService
|
|||||||
private readonly InsufficientStockMessageBuilder $stockMessages,
|
private readonly InsufficientStockMessageBuilder $stockMessages,
|
||||||
private readonly PurchaseResponseLoader $responses,
|
private readonly PurchaseResponseLoader $responses,
|
||||||
private readonly PurchaseItemSnapshotFactory $snapshots,
|
private readonly PurchaseItemSnapshotFactory $snapshots,
|
||||||
|
private readonly CartVariantReplacementService $variantReplacements,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/** @param array<string, mixed> $purchaseData */
|
/** @param array<string, mixed> $purchaseData */
|
||||||
@@ -169,21 +173,31 @@ class StartCheckoutService
|
|||||||
'cantidad' => $line['quantity'],
|
'cantidad' => $line['quantity'],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
try {
|
|
||||||
$this->reservations->reserve($cartItem, $line['selection'], $line['quantity']);
|
|
||||||
} catch (\InvalidArgumentException) {
|
|
||||||
$availableQuantity = $this->inventory->availableQuantity($line['selection']) ?? 0;
|
|
||||||
|
|
||||||
throw new InsufficientStockException([
|
|
||||||
$this->unavailableItem($line, $availableQuantity),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$cartItem->setRelation('catalogItem', $line['catalog_item']);
|
$cartItem->setRelation('catalogItem', $line['catalog_item']);
|
||||||
$cartItem->setRelation('variant', $line['selection'] instanceof Variant ? $line['selection'] : null);
|
$cartItem->setRelation('variant', $line['selection'] instanceof Variant ? $line['selection'] : null);
|
||||||
$cartItems->push($cartItem);
|
$cartItems->push($cartItem);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$this->reservations->syncCart($cart);
|
||||||
|
} catch (\InvalidArgumentException) {
|
||||||
|
$unavailable = $resolvedLines
|
||||||
|
->map(function (array $line): ?array {
|
||||||
|
$availableQuantity = $this->inventory->availableQuantity($line['selection']);
|
||||||
|
|
||||||
|
return $availableQuantity !== null && $availableQuantity < $line['quantity']
|
||||||
|
? $this->unavailableItem($line, $availableQuantity)
|
||||||
|
: null;
|
||||||
|
})
|
||||||
|
->filter()
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
|
||||||
|
throw new InsufficientStockException($unavailable !== [] ? $unavailable : [
|
||||||
|
$this->unavailableItem($resolvedLines->first(), 0),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
$purchase = $this->createPurchase(
|
$purchase = $this->createPurchase(
|
||||||
$tenant,
|
$tenant,
|
||||||
$userId,
|
$userId,
|
||||||
@@ -194,19 +208,12 @@ class StartCheckoutService
|
|||||||
$cart->getKey(),
|
$cart->getKey(),
|
||||||
);
|
);
|
||||||
$cart->update(['current_purchase_id' => $purchase->getKey()]);
|
$cart->update(['current_purchase_id' => $purchase->getKey()]);
|
||||||
|
$this->reservations->attachToPurchase($cart, $purchase, $this->checkoutExpiration());
|
||||||
|
|
||||||
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
|
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
|
||||||
$this->loadCartItems($cartItems);
|
$this->loadCartItems($cartItems);
|
||||||
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
|
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
|
||||||
|
|
||||||
foreach ($cartItems as $index => $cartItem) {
|
|
||||||
$this->reservations->attachToPurchase(
|
|
||||||
$cartItem,
|
|
||||||
$resolvedLines->get($index)['selection'],
|
|
||||||
$purchase,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,6 +252,7 @@ class StartCheckoutService
|
|||||||
int $cartId,
|
int $cartId,
|
||||||
): Purchase {
|
): Purchase {
|
||||||
$cart = $this->resolveCart($tenant, $userId, $cartId);
|
$cart = $this->resolveCart($tenant, $userId, $cartId);
|
||||||
|
$this->variantReplacements->replaceHistoricalVariants($cart);
|
||||||
$cartItems = $cart->items()->lockForUpdate()->get();
|
$cartItems = $cart->items()->lockForUpdate()->get();
|
||||||
|
|
||||||
if ($cartItems->isEmpty()) {
|
if ($cartItems->isEmpty()) {
|
||||||
@@ -257,6 +265,7 @@ class StartCheckoutService
|
|||||||
$this->verifyTenantItems($tenant, $cartItems);
|
$this->verifyTenantItems($tenant, $cartItems);
|
||||||
$this->assertCartPurchaseLimits($tenant, $userId, $cartItems, $cart->getKey());
|
$this->assertCartPurchaseLimits($tenant, $userId, $cartItems, $cart->getKey());
|
||||||
$cart->setRelation('items', $cartItems);
|
$cart->setRelation('items', $cartItems);
|
||||||
|
$this->reservations->syncCart($cart);
|
||||||
|
|
||||||
$purchase = $this->createPurchase(
|
$purchase = $this->createPurchase(
|
||||||
$tenant,
|
$tenant,
|
||||||
@@ -266,16 +275,9 @@ class StartCheckoutService
|
|||||||
$cart->getKey(),
|
$cart->getKey(),
|
||||||
);
|
);
|
||||||
$cart->update(['current_purchase_id' => $purchase->getKey()]);
|
$cart->update(['current_purchase_id' => $purchase->getKey()]);
|
||||||
|
$this->reservations->attachToPurchase($cart, $purchase, $this->checkoutExpiration());
|
||||||
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
|
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
|
||||||
|
|
||||||
foreach ($cartItems as $cartItem) {
|
|
||||||
$this->reservations->attachToPurchase(
|
|
||||||
$cartItem,
|
|
||||||
$cartItem->selectedItem(),
|
|
||||||
$purchase,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -316,9 +318,9 @@ class StartCheckoutService
|
|||||||
Purchase::STATUS_CREATED,
|
Purchase::STATUS_CREATED,
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
], true)) {
|
], true)) {
|
||||||
|
$this->reservations->returnToCart($currentPurchase, $cart);
|
||||||
$currentPurchase->update([
|
$currentPurchase->update([
|
||||||
'status' => Purchase::STATUS_SUPERSEDED,
|
'status' => Purchase::STATUS_SUPERSEDED,
|
||||||
'expires_at' => null,
|
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -331,7 +333,11 @@ class StartCheckoutService
|
|||||||
throw new NotFoundHttpException('Cart not found for tenant.');
|
throw new NotFoundHttpException('Cart not found for tenant.');
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($cart->status !== 'active') {
|
if ($cart->status === Cart::STATUS_EXPIRED) {
|
||||||
|
throw new StockReservationExpiredException;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($cart->status !== Cart::STATUS_ACTIVE) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'cart_id' => __('api.purchase.inactive_cart'),
|
'cart_id' => __('api.purchase.inactive_cart'),
|
||||||
]);
|
]);
|
||||||
@@ -353,6 +359,13 @@ class StartCheckoutService
|
|||||||
'cart_id' => __('api.purchase.catalog_item_wrong_tenant'),
|
'cart_id' => __('api.purchase.catalog_item_wrong_tenant'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($tenant->active_event_id !== null
|
||||||
|
&& $item->catalogItem->event_id !== $tenant->active_event_id) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'cart_id' => __('api.purchase.catalog_item_missing'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -405,13 +418,17 @@ class StartCheckoutService
|
|||||||
'user_id' => $userId,
|
'user_id' => $userId,
|
||||||
'status' => Purchase::STATUS_CREATED,
|
'status' => Purchase::STATUS_CREATED,
|
||||||
'payment_method' => null,
|
'payment_method' => null,
|
||||||
'expires_at' => now()->addMinutes(
|
|
||||||
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
|
|
||||||
),
|
|
||||||
'total' => $total,
|
'total' => $total,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function checkoutExpiration(): Carbon
|
||||||
|
{
|
||||||
|
return now()->addMinutes(
|
||||||
|
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** @param Collection<int, CartItem> $cartItems */
|
/** @param Collection<int, CartItem> $cartItems */
|
||||||
private function loadCartItems(Collection $cartItems): void
|
private function loadCartItems(Collection $cartItems): void
|
||||||
{
|
{
|
||||||
@@ -1,14 +1,13 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Services;
|
namespace App\Domains\Commerce\Purchase\Services;
|
||||||
|
|
||||||
use App\Domains\Catalog\Services\StockReservationService;
|
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Commerce\Purchase\Services\Checkout\CompleteCheckoutService;
|
||||||
use App\Domains\Purchase\Services\Checkout\CompleteCheckoutService;
|
use App\Domains\Commerce\Purchase\Services\Checkout\EditCheckoutService;
|
||||||
use App\Domains\Purchase\Services\Checkout\EditCheckoutService;
|
use App\Domains\Commerce\Purchase\Services\Checkout\ReleaseCheckoutService;
|
||||||
use App\Domains\Purchase\Services\Checkout\ReleaseCheckoutService;
|
use App\Domains\Commerce\Purchase\Services\Checkout\StartCheckoutService;
|
||||||
use App\Domains\Purchase\Services\Checkout\StartCheckoutService;
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -23,7 +22,6 @@ class CheckoutService
|
|||||||
private readonly EditCheckoutService $editor,
|
private readonly EditCheckoutService $editor,
|
||||||
private readonly CompleteCheckoutService $completer,
|
private readonly CompleteCheckoutService $completer,
|
||||||
private readonly ReleaseCheckoutService $releaser,
|
private readonly ReleaseCheckoutService $releaser,
|
||||||
private readonly StockReservationService $reservations,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/** @param array<string, mixed> $purchaseData */
|
/** @param array<string, mixed> $purchaseData */
|
||||||
@@ -77,14 +75,4 @@ class CheckoutService
|
|||||||
{
|
{
|
||||||
return $this->releaser->expire($purchase);
|
return $this->releaser->expire($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function expireOverduePurchases(): int
|
|
||||||
{
|
|
||||||
return $this->releaser->expireOverdue();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function syncReservationExpiration(Purchase $purchase): void
|
|
||||||
{
|
|
||||||
$this->reservations->syncPurchaseExpiration($purchase);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Commerce\Purchase\Services;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Measures likely DNI typing errors using the optimal-string-alignment
|
||||||
|
* variant of the Damerau-Levenshtein distance.
|
||||||
|
*
|
||||||
|
* The returned value is the minimum number of single-character edits needed
|
||||||
|
* to transform one DNI into the other. Supported edits are insertion,
|
||||||
|
* deletion, substitution and transposition of two adjacent digits.
|
||||||
|
*/
|
||||||
|
class DniDistanceService
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Calculate the edit distance between two normalized DNI strings.
|
||||||
|
*
|
||||||
|
* Each matrix cell [row][column] stores the minimum edits required to
|
||||||
|
* transform the first $row digits of $left into the first $column digits
|
||||||
|
* of $right. The bottom-right cell therefore contains the final distance.
|
||||||
|
*/
|
||||||
|
public function distance(string $left, string $right): int
|
||||||
|
{
|
||||||
|
$left = $this->normalize($left);
|
||||||
|
$right = $this->normalize($right);
|
||||||
|
$leftLength = strlen($left);
|
||||||
|
$rightLength = strlen($right);
|
||||||
|
$matrix = [];
|
||||||
|
|
||||||
|
// Transforming a prefix into an empty string requires deleting every digit.
|
||||||
|
for ($row = 0; $row <= $leftLength; $row++) {
|
||||||
|
$matrix[$row] = [$row];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transforming an empty string into a prefix requires inserting every digit.
|
||||||
|
for ($column = 0; $column <= $rightLength; $column++) {
|
||||||
|
$matrix[0][$column] = $column;
|
||||||
|
}
|
||||||
|
|
||||||
|
for ($row = 1; $row <= $leftLength; $row++) {
|
||||||
|
for ($column = 1; $column <= $rightLength; $column++) {
|
||||||
|
$substitutionCost = $left[$row - 1] === $right[$column - 1] ? 0 : 1;
|
||||||
|
$deletionDistance = $matrix[$row - 1][$column] + 1;
|
||||||
|
$insertionDistance = $matrix[$row][$column - 1] + 1;
|
||||||
|
$substitutionDistance = $matrix[$row - 1][$column - 1] + $substitutionCost;
|
||||||
|
|
||||||
|
// Keep the cheapest way to align the two prefixes at this position.
|
||||||
|
$matrix[$row][$column] = min(
|
||||||
|
$deletionDistance,
|
||||||
|
$insertionDistance,
|
||||||
|
$substitutionDistance,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Count two adjacent inverted digits as one edit instead of two substitutions.
|
||||||
|
if (
|
||||||
|
$row > 1
|
||||||
|
&& $column > 1
|
||||||
|
&& $left[$row - 1] === $right[$column - 2]
|
||||||
|
&& $left[$row - 2] === $right[$column - 1]
|
||||||
|
) {
|
||||||
|
$matrix[$row][$column] = min(
|
||||||
|
$matrix[$row][$column],
|
||||||
|
$matrix[$row - 2][$column - 2] + 1,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $matrix[$leftLength][$rightLength];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep only digits and left-pad seven-digit DNIs so comparisons preserve
|
||||||
|
* the leading zero that is present when the DNI is extracted from a CUIT.
|
||||||
|
*/
|
||||||
|
public function normalize(string $dni): string
|
||||||
|
{
|
||||||
|
$digits = preg_replace('/\D+/', '', $dni) ?? '';
|
||||||
|
|
||||||
|
return str_pad($digits, 8, '0', STR_PAD_LEFT);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Commerce\Purchase\Services;
|
||||||
|
|
||||||
|
use App\Domains\Core\Tenant\Models\Tenant;
|
||||||
|
use App\Domains\Ticketing\Ticket\Models\TicketRefund;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
|
||||||
|
class PurchaseRefundSummaryService
|
||||||
|
{
|
||||||
|
public function totalForTenant(Tenant $tenant): string
|
||||||
|
{
|
||||||
|
$total = TicketRefund::query()
|
||||||
|
->whereHas(
|
||||||
|
'purchaseItem.purchase',
|
||||||
|
fn (Builder $query): Builder => $query->where('tenant_codigo', $tenant->codigo)
|
||||||
|
)
|
||||||
|
->sum('amount');
|
||||||
|
|
||||||
|
return number_format((float) $total, 2, '.', '');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Commerce\Purchase\Services;
|
||||||
|
|
||||||
|
use App\Domains\Commerce\Cart\Models\Cart;
|
||||||
|
use App\Domains\Commerce\Catalog\Models\StockReservation;
|
||||||
|
use App\Domains\Commerce\Purchase\Exceptions\PurchaseExpiredException;
|
||||||
|
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
|
class PurchaseStateGuard
|
||||||
|
{
|
||||||
|
public function assertNotExpired(Purchase $purchase): void
|
||||||
|
{
|
||||||
|
if ($purchase->status === Purchase::STATUS_EXPIRED) {
|
||||||
|
throw new PurchaseExpiredException;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! in_array($purchase->status, [
|
||||||
|
Purchase::STATUS_CREATED,
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
], true)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var StockReservation|null $reservation */
|
||||||
|
$reservation = $purchase->relationLoaded('stockReservation')
|
||||||
|
? $purchase->getRelation('stockReservation')
|
||||||
|
: ($purchase->exists
|
||||||
|
? $purchase->stockReservation()->first()
|
||||||
|
: null);
|
||||||
|
|
||||||
|
if ($reservation !== null && (
|
||||||
|
$reservation->status === StockReservation::STATUS_EXPIRED
|
||||||
|
|| (
|
||||||
|
$reservation->status === StockReservation::STATUS_ACTIVE
|
||||||
|
&& $reservation->expires_at !== null
|
||||||
|
&& ! $reservation->expires_at->isFuture()
|
||||||
|
)
|
||||||
|
)) {
|
||||||
|
throw new PurchaseExpiredException;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function lockCurrentCart(Purchase $purchase): Cart
|
||||||
|
{
|
||||||
|
/** @var Cart|null $cart */
|
||||||
|
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
|
||||||
|
|
||||||
|
if ($cart === null || $cart->current_purchase_id !== $purchase->getKey()) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'purchase' => __('api.purchase.not_current'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $cart;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Services;
|
namespace App\Domains\Commerce\Purchase\Services;
|
||||||
|
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Commerce\Purchase\Models\Purchase;
|
||||||
use Illuminate\Database\Query\Builder;
|
use Illuminate\Database\Query\Builder;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -65,9 +65,10 @@ class TenantTransactionResetService
|
|||||||
DB::table('inventories')
|
DB::table('inventories')
|
||||||
->whereIn('id', $scope['inventory_ids'])
|
->whereIn('id', $scope['inventory_ids'])
|
||||||
->update([
|
->update([
|
||||||
'real_stock' => DB::raw('real_stock + sold_units'),
|
'real_stock' => DB::raw('real_stock + sold_units - refunded_units'),
|
||||||
'reserved_stock' => 0,
|
'reserved_stock' => 0,
|
||||||
'sold_units' => 0,
|
'sold_units' => 0,
|
||||||
|
'refunded_units' => 0,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return $summary;
|
return $summary;
|
||||||
@@ -135,11 +136,25 @@ class TenantTransactionResetService
|
|||||||
*/
|
*/
|
||||||
private function reservationQuery(array $scope): Builder
|
private function reservationQuery(array $scope): Builder
|
||||||
{
|
{
|
||||||
|
$reservationIds = DB::table('carritos')
|
||||||
|
->whereIn('id', $scope['cart_ids'])
|
||||||
|
->whereNotNull('current_stock_reservation_id')
|
||||||
|
->pluck('current_stock_reservation_id')
|
||||||
|
->merge(
|
||||||
|
DB::table('compras')
|
||||||
|
->whereIn('id', $scope['purchase_ids'])
|
||||||
|
->whereNotNull('stock_reservation_id')
|
||||||
|
->pluck('stock_reservation_id'),
|
||||||
|
)
|
||||||
|
->merge(
|
||||||
|
DB::table('stock_reservation_lines')
|
||||||
|
->whereIn('inventory_id', $scope['inventory_ids'])
|
||||||
|
->pluck('stock_reservation_id'),
|
||||||
|
)
|
||||||
|
->unique()
|
||||||
|
->values();
|
||||||
|
|
||||||
return DB::table('stock_reservations')
|
return DB::table('stock_reservations')
|
||||||
->where(function (Builder $query) use ($scope): void {
|
->whereIn('id', $reservationIds);
|
||||||
$query->whereIn('inventory_id', $scope['inventory_ids'])
|
|
||||||
->orWhereIn('purchase_id', $scope['purchase_ids'])
|
|
||||||
->orWhereIn('cart_item_id', $scope['cart_item_ids']);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user