Compare commits
45 Commits
4f7ede1072
...
feature/re
| Author | SHA1 | Date | |
|---|---|---|---|
| 5503559899 | |||
| 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 |
@@ -45,6 +45,7 @@ COMMANDS_LOG_LEVEL=info
|
|||||||
COMMANDS_LOG_DAYS=30
|
COMMANDS_LOG_DAYS=30
|
||||||
EMAILS_LOG_LEVEL=info
|
EMAILS_LOG_LEVEL=info
|
||||||
EMAILS_LOG_DAYS=30
|
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
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
# 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 under `app/Domains`.
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ namespace App\Domains\Auth\Models;
|
|||||||
use App\Domains\Authorization\Enums\RoleCode;
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
use App\Domains\Authorization\Models\Role;
|
use App\Domains\Authorization\Models\Role;
|
||||||
use App\Domains\Catalog\Models\Category;
|
use App\Domains\Catalog\Models\Category;
|
||||||
|
use App\Domains\Event\Models\EventDateChangeView;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use App\Domains\Ticket\Models\ScanAttempt;
|
use App\Domains\Ticket\Models\ScanAttempt;
|
||||||
use Database\Factories\UserFactory;
|
use Database\Factories\UserFactory;
|
||||||
@@ -53,6 +54,12 @@ class User extends Authenticatable
|
|||||||
return $this->hasMany(ScanAttempt::class, 'scanner_user_id');
|
return $this->hasMany(ScanAttempt::class, 'scanner_user_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return HasMany<EventDateChangeView, $this> */
|
||||||
|
public function eventDateChangeViews(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(EventDateChangeView::class);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return BelongsTo<Role, $this>
|
* @return BelongsTo<Role, $this>
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ class TenantBootstrapService
|
|||||||
return $this->tenantInformationService->load(
|
return $this->tenantInformationService->load(
|
||||||
$tenant,
|
$tenant,
|
||||||
[
|
[
|
||||||
|
'eventDateChanges',
|
||||||
'menues' => fn ($query) => $query->whereHas(
|
'menues' => fn ($query) => $query->whereHas(
|
||||||
'roles',
|
'roles',
|
||||||
fn ($query) => $query->where('codigo', RoleCode::User->value)
|
fn ($query) => $query->where('codigo', RoleCode::User->value)
|
||||||
|
|||||||
@@ -400,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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -430,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);
|
||||||
|
|||||||
99
app/Domains/Cart/Services/CartVariantReplacementService.php
Normal file
99
app/Domains/Cart/Services/CartVariantReplacementService.php
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Cart\Services;
|
||||||
|
|
||||||
|
use App\Domains\Cart\Models\Cart;
|
||||||
|
use App\Domains\Cart\Models\CartItem;
|
||||||
|
use App\Domains\Catalog\Models\Variant;
|
||||||
|
use App\Domains\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')],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Cart\Services;
|
||||||
|
|
||||||
|
use App\Domains\Cart\Models\Cart;
|
||||||
|
use App\Domains\Catalog\Models\StockReservation;
|
||||||
|
use App\Domains\Catalog\Services\StockReservationService;
|
||||||
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
use App\Domains\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]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -179,12 +179,28 @@ class CatalogItem extends Model
|
|||||||
{
|
{
|
||||||
return $query->where(function (Builder $query): void {
|
return $query->where(function (Builder $query): void {
|
||||||
$query
|
$query
|
||||||
|
->where(function (Builder $unlimitedQuery): void {
|
||||||
|
$unlimitedQuery
|
||||||
->where('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value)
|
->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 $variantQuery): Builder => $variantQuery
|
||||||
|
->whereNull('sales_disabled_at')
|
||||||
|
->whereNull('replaced_by_variant_id')
|
||||||
|
->whereHas(
|
||||||
|
'inventory',
|
||||||
fn (Builder $inventoryQuery): Builder => $inventoryQuery
|
fn (Builder $inventoryQuery): Builder => $inventoryQuery
|
||||||
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
|
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
|
||||||
)
|
)
|
||||||
|
)
|
||||||
->orWhere(function (Builder $directItemQuery): void {
|
->orWhere(function (Builder $directItemQuery): void {
|
||||||
$directItemQuery
|
$directItemQuery
|
||||||
->whereDoesntHave('variants')
|
->whereDoesntHave('variants')
|
||||||
@@ -205,9 +221,12 @@ class CatalogItem extends Model
|
|||||||
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)
|
->filter(fn (Variant $variant): bool => $variant->hasOnlyActiveEventDates()
|
||||||
|| $this->inventory_policy === InventoryPolicy::Unlimited
|
&& (($includedVariantId !== null && $variant->id === $includedVariantId)
|
||||||
|| ($variant->inventory?->availableStock() ?? 0) > 0)
|
|| ($variant->isSellable() && (
|
||||||
|
$this->inventory_policy === InventoryPolicy::Unlimited
|
||||||
|
|| ($variant->inventory?->availableStock() ?? 0) > 0
|
||||||
|
))))
|
||||||
->values();
|
->values();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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,10 +45,10 @@ 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<StockReservationLine, $this> */
|
/** @return HasMany<StockReservationLine, $this> */
|
||||||
|
|||||||
@@ -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,39 @@ 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->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
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -63,7 +63,12 @@ class CatalogInventoryService
|
|||||||
|
|
||||||
$selection->loadMissing('variants.inventory');
|
$selection->loadMissing('variants.inventory');
|
||||||
|
|
||||||
return $selection->variants->sum(
|
return $selection->variants
|
||||||
|
->filter(fn (Variant $variant): bool => $variant->isSellable())
|
||||||
|
->unique(fn (Variant $variant): string => $variant->inventory_id === null
|
||||||
|
? 'object:'.spl_object_id($variant->inventory)
|
||||||
|
: 'id:'.$variant->inventory_id)
|
||||||
|
->sum(
|
||||||
fn (Variant $variant): int => $variant->inventory->availableStock(),
|
fn (Variant $variant): int => $variant->inventory->availableStock(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -207,7 +207,8 @@ class CatalogService
|
|||||||
$visibleVariants = $catalogItem->visibleVariants();
|
$visibleVariants = $catalogItem->visibleVariants();
|
||||||
if ($catalogItem->type === CatalogItemType::Standard
|
if ($catalogItem->type === CatalogItemType::Standard
|
||||||
&& ($catalogItem->inventory_id !== null || $catalogItem->variants->isNotEmpty())
|
&& ($catalogItem->inventory_id !== null || $catalogItem->variants->isNotEmpty())
|
||||||
&& ! $catalogItem->isAvailable()) {
|
&& (($catalogItem->variants->isNotEmpty() && $visibleVariants->isEmpty())
|
||||||
|
|| ! $catalogItem->isAvailable())) {
|
||||||
throw new NotFoundHttpException('Catalog item is out of stock.');
|
throw new NotFoundHttpException('Catalog item is out of stock.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -324,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]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -399,7 +404,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'),
|
||||||
|
|||||||
@@ -19,6 +19,10 @@ class StockReservationService
|
|||||||
|
|
||||||
public const REASON_CART_CHANGED = 'cart_changed';
|
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_SUPERSEDED = 'purchase_superseded';
|
||||||
|
|
||||||
public const REASON_PURCHASE_CANCELLED = 'purchase_cancelled';
|
public const REASON_PURCHASE_CANCELLED = 'purchase_cancelled';
|
||||||
|
|||||||
263
app/Domains/Catalog/Services/VariantReplacementService.php
Normal file
263
app/Domains/Catalog/Services/VariantReplacementService.php
Normal file
@@ -0,0 +1,263 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Models\BundleComponent;
|
||||||
|
use App\Domains\Catalog\Models\Inventory;
|
||||||
|
use App\Domains\Catalog\Models\StockReservation;
|
||||||
|
use App\Domains\Catalog\Models\StockReservationLine;
|
||||||
|
use App\Domains\Catalog\Models\Variant;
|
||||||
|
use App\Domains\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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -52,6 +52,7 @@ class EventController extends Controller
|
|||||||
$request->user()->tenant()->firstOrFail(),
|
$request->user()->tenant()->firstOrFail(),
|
||||||
$eventDate,
|
$eventDate,
|
||||||
$request->validated(),
|
$request->validated(),
|
||||||
|
$request->user(),
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -62,6 +63,7 @@ class EventController extends Controller
|
|||||||
$this->eventService->suspendDateForTenant(
|
$this->eventService->suspendDateForTenant(
|
||||||
$request->user()->tenant()->firstOrFail(),
|
$request->user()->tenant()->firstOrFail(),
|
||||||
$eventDate,
|
$eventDate,
|
||||||
|
$request->user(),
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
22
app/Domains/Event/Controllers/EventDateNoticeController.php
Normal file
22
app/Domains/Event/Controllers/EventDateNoticeController.php
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Controllers;
|
||||||
|
|
||||||
|
use App\Domains\Event\Resources\EventDateNoticeResource;
|
||||||
|
use App\Domains\Event\Services\EventDateNoticeService;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||||
|
|
||||||
|
class EventDateNoticeController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(private readonly EventDateNoticeService $noticeService) {}
|
||||||
|
|
||||||
|
public function claim(Request $request, Tenant $tenant): AnonymousResourceCollection
|
||||||
|
{
|
||||||
|
return EventDateNoticeResource::collection(
|
||||||
|
$this->noticeService->claimFor($request->user(), $tenant)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
9
app/Domains/Event/Enums/EventDateChangeType.php
Normal file
9
app/Domains/Event/Enums/EventDateChangeType.php
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Enums;
|
||||||
|
|
||||||
|
enum EventDateChangeType: string
|
||||||
|
{
|
||||||
|
case Rescheduled = 'rescheduled';
|
||||||
|
case Suspended = 'suspended';
|
||||||
|
}
|
||||||
22
app/Domains/Event/Events/EventDateRescheduled.php
Normal file
22
app/Domains/Event/Events/EventDateRescheduled.php
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Events;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Events\Dispatchable;
|
||||||
|
|
||||||
|
class EventDateRescheduled
|
||||||
|
{
|
||||||
|
use Dispatchable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<array{purchase_id: int, ticket_ids: list<int>}> $purchaseTickets
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public readonly string $tenantCode,
|
||||||
|
public readonly int $sourceEventDateId,
|
||||||
|
public readonly int $destinationEventDateId,
|
||||||
|
public readonly string $previousDate,
|
||||||
|
public readonly string $newDate,
|
||||||
|
public readonly array $purchaseTickets,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
20
app/Domains/Event/Events/EventDateSuspended.php
Normal file
20
app/Domains/Event/Events/EventDateSuspended.php
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Events;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Events\Dispatchable;
|
||||||
|
|
||||||
|
class EventDateSuspended
|
||||||
|
{
|
||||||
|
use Dispatchable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<array{purchase_id: int, ticket_ids: list<int>}> $purchaseTickets
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public readonly string $tenantCode,
|
||||||
|
public readonly int $eventDateId,
|
||||||
|
public readonly string $date,
|
||||||
|
public readonly array $purchaseTickets,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ namespace App\Domains\Event\Models;
|
|||||||
|
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
use App\Domains\Event\Enums\EventDateStatus;
|
use App\Domains\Event\Enums\EventDateStatus;
|
||||||
|
use App\Domains\Event\Services\EffectiveEventDateResolver;
|
||||||
use App\Domains\Event\Services\EventDateTextFormatter;
|
use App\Domains\Event\Services\EventDateTextFormatter;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use App\Domains\Ticket\Enums\ValidityTimeType;
|
use App\Domains\Ticket\Enums\ValidityTimeType;
|
||||||
@@ -80,12 +81,29 @@ class EventDate extends Model
|
|||||||
return $this->belongsTo(self::class, 'rescheduled_to_event_date_id');
|
return $this->belongsTo(self::class, 'rescheduled_to_event_date_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function effectiveDate(): ?self
|
||||||
|
{
|
||||||
|
return app(EffectiveEventDateResolver::class)->resolve($this);
|
||||||
|
}
|
||||||
|
|
||||||
/** @return HasMany<EventDate, $this> */
|
/** @return HasMany<EventDate, $this> */
|
||||||
public function rescheduledFrom(): HasMany
|
public function rescheduledFrom(): HasMany
|
||||||
{
|
{
|
||||||
return $this->hasMany(self::class, 'rescheduled_to_event_date_id');
|
return $this->hasMany(self::class, 'rescheduled_to_event_date_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return HasMany<EventDateChange, $this> */
|
||||||
|
public function changeHistory(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(EventDateChange::class, 'source_event_date_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return HasMany<EventDateChange, $this> */
|
||||||
|
public function destinationChangeHistory(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(EventDateChange::class, 'destination_event_date_id');
|
||||||
|
}
|
||||||
|
|
||||||
/** @return HasMany<Variant, $this> */
|
/** @return HasMany<Variant, $this> */
|
||||||
public function variants(): HasMany
|
public function variants(): HasMany
|
||||||
{
|
{
|
||||||
@@ -110,7 +128,11 @@ class EventDate extends Model
|
|||||||
|
|
||||||
public function endsAt(): CarbonInterface
|
public function endsAt(): CarbonInterface
|
||||||
{
|
{
|
||||||
return Carbon::parse($this->date->format('Y-m-d').' '.$this->time_end);
|
$endsAt = Carbon::parse($this->date->format('Y-m-d').' '.$this->time_end);
|
||||||
|
|
||||||
|
return $endsAt->lessThanOrEqualTo($this->startsAt())
|
||||||
|
? $endsAt->addDay()
|
||||||
|
: $endsAt;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getStatusAttribute(): EventDateStatus
|
public function getStatusAttribute(): EventDateStatus
|
||||||
@@ -157,10 +179,6 @@ class EventDate extends Model
|
|||||||
$startsAt = $this->startsAt();
|
$startsAt = $this->startsAt();
|
||||||
$expiresAt = $this->endsAt();
|
$expiresAt = $this->endsAt();
|
||||||
|
|
||||||
if ($expiresAt->lessThanOrEqualTo($startsAt)) {
|
|
||||||
$expiresAt = $expiresAt->addDay();
|
|
||||||
}
|
|
||||||
|
|
||||||
$attributes = [
|
$attributes = [
|
||||||
'type' => ValidityTimeType::FixedWindow,
|
'type' => ValidityTimeType::FixedWindow,
|
||||||
'start_time' => null,
|
'start_time' => null,
|
||||||
|
|||||||
68
app/Domains/Event/Models/EventDateChange.php
Normal file
68
app/Domains/Event/Models/EventDateChange.php
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Models;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Event\Enums\EventDateChangeType;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'tenant_code',
|
||||||
|
'change_type',
|
||||||
|
'source_event_date_id',
|
||||||
|
'destination_event_date_id',
|
||||||
|
'created_by_user_id',
|
||||||
|
'previous_date',
|
||||||
|
'new_date',
|
||||||
|
])]
|
||||||
|
class EventDateChange extends Model
|
||||||
|
{
|
||||||
|
public $timestamps = false;
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'change_type' => EventDateChangeType::class,
|
||||||
|
'source_event_date_id' => 'integer',
|
||||||
|
'destination_event_date_id' => 'integer',
|
||||||
|
'created_by_user_id' => 'integer',
|
||||||
|
'previous_date' => 'date:Y-m-d',
|
||||||
|
'new_date' => 'date:Y-m-d',
|
||||||
|
'created_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<Tenant, $this> */
|
||||||
|
public function tenant(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<EventDate, $this> */
|
||||||
|
public function sourceEventDate(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(EventDate::class, 'source_event_date_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<EventDate, $this> */
|
||||||
|
public function destinationEventDate(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(EventDate::class, 'destination_event_date_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<User, $this> */
|
||||||
|
public function createdBy(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class, 'created_by_user_id')->withTrashed();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return HasMany<EventDateChangeView, $this> */
|
||||||
|
public function views(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(EventDateChangeView::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
41
app/Domains/Event/Models/EventDateChangeView.php
Normal file
41
app/Domains/Event/Models/EventDateChangeView.php
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Models;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'user_id',
|
||||||
|
'event_date_change_id',
|
||||||
|
'display_count',
|
||||||
|
'last_displayed_at',
|
||||||
|
])]
|
||||||
|
class EventDateChangeView extends Model
|
||||||
|
{
|
||||||
|
protected $table = 'user_event_date_change_views';
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'user_id' => 'integer',
|
||||||
|
'event_date_change_id' => 'integer',
|
||||||
|
'display_count' => 'integer',
|
||||||
|
'last_displayed_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<User, $this> */
|
||||||
|
public function user(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<EventDateChange, $this> */
|
||||||
|
public function eventDateChange(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(EventDateChange::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
24
app/Domains/Event/Resources/EventDateChangeResource.php
Normal file
24
app/Domains/Event/Resources/EventDateChangeResource.php
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Resources;
|
||||||
|
|
||||||
|
use App\Domains\Event\Models\EventDateChange;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
/** @mixin EventDateChange */
|
||||||
|
class EventDateChangeResource extends JsonResource
|
||||||
|
{
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'type' => $this->change_type->value,
|
||||||
|
'source_event_date_id' => $this->source_event_date_id,
|
||||||
|
'destination_event_date_id' => $this->destination_event_date_id,
|
||||||
|
'previous_date' => $this->previous_date->format('Y-m-d'),
|
||||||
|
'new_date' => $this->new_date?->format('Y-m-d'),
|
||||||
|
'occurred_at' => $this->created_at->toISOString(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
20
app/Domains/Event/Resources/EventDateNoticeResource.php
Normal file
20
app/Domains/Event/Resources/EventDateNoticeResource.php
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Resources;
|
||||||
|
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
class EventDateNoticeResource extends JsonResource
|
||||||
|
{
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'type' => $this->resource['type'],
|
||||||
|
'change_ids' => $this->resource['change_ids'],
|
||||||
|
'title' => $this->resource['title'],
|
||||||
|
'message' => $this->resource['message'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,6 +23,9 @@ class EventDateResource extends JsonResource
|
|||||||
'status' => $this->status->value,
|
'status' => $this->status->value,
|
||||||
'rescheduled_to_event_date_id' => $this->rescheduled_to_event_date_id,
|
'rescheduled_to_event_date_id' => $this->rescheduled_to_event_date_id,
|
||||||
'suspended_at' => $this->suspended_at?->toISOString(),
|
'suspended_at' => $this->suspended_at?->toISOString(),
|
||||||
|
'rescheduled_dates' => EventDateResource::collection(
|
||||||
|
$this->whenLoaded('adminRescheduledDates')
|
||||||
|
),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domains\Event\Resources;
|
namespace App\Domains\Event\Resources;
|
||||||
|
|
||||||
|
use App\Domains\Event\Services\EventDateGroupingService;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
@@ -22,7 +23,9 @@ class EventResource extends JsonResource
|
|||||||
'allow_ticket_total_refund' => $this->allow_ticket_total_refund,
|
'allow_ticket_total_refund' => $this->allow_ticket_total_refund,
|
||||||
'allow_ticket_partial_refund' => $this->allow_ticket_partial_refund,
|
'allow_ticket_partial_refund' => $this->allow_ticket_partial_refund,
|
||||||
'ticket_partial_refund_percentage' => $this->ticket_partial_refund_percentage,
|
'ticket_partial_refund_percentage' => $this->ticket_partial_refund_percentage,
|
||||||
'dates' => EventDateResource::collection($this->eventDates),
|
'dates' => EventDateResource::collection(
|
||||||
|
app(EventDateGroupingService::class)->group($this->eventDates)
|
||||||
|
),
|
||||||
'social_media' => $this->socialMedia->map(fn ($item): array => [
|
'social_media' => $this->socialMedia->map(fn ($item): array => [
|
||||||
'code' => $item->code,
|
'code' => $item->code,
|
||||||
'url' => $item->pivot->url,
|
'url' => $item->pivot->url,
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Services;
|
||||||
|
|
||||||
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use App\Domains\Ticket\Services\TicketValidityResolver;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
|
class AffectedEventDatePurchaseResolver
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Finds active tickets belonging to paid purchases before an event-date mutation.
|
||||||
|
*
|
||||||
|
* @param Collection<int, int>|list<int> $eventDateIds
|
||||||
|
* @return list<array{purchase_id: int, ticket_ids: list<int>}>
|
||||||
|
*/
|
||||||
|
public function resolve(Tenant $tenant, Collection|array $eventDateIds): array
|
||||||
|
{
|
||||||
|
$eventDateIds = collect($eventDateIds)->map(fn (mixed $id): int => (int) $id)->unique()->values();
|
||||||
|
|
||||||
|
if ($eventDateIds->isEmpty()) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var Collection<int, Ticket> $tickets */
|
||||||
|
$tickets = Ticket::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->whereHas('sourcePurchaseItem.purchase', fn (Builder $query) => $query
|
||||||
|
->where('status', Purchase::STATUS_PAID))
|
||||||
|
->whereHas('sourceVariant', function (Builder $query) use ($eventDateIds): void {
|
||||||
|
$query->whereIn('event_date_id', $eventDateIds)
|
||||||
|
->orWhereHas('eventDates', fn (Builder $eventDates) => $eventDates
|
||||||
|
->whereIn('event_dates.id', $eventDateIds));
|
||||||
|
})
|
||||||
|
->with([
|
||||||
|
...TicketValidityResolver::RELATIONS,
|
||||||
|
'sourcePurchaseItem.purchase',
|
||||||
|
])
|
||||||
|
->get()
|
||||||
|
->filter(fn (Ticket $ticket): bool => $ticket->is_active())
|
||||||
|
->values();
|
||||||
|
|
||||||
|
return $tickets
|
||||||
|
->groupBy(fn (Ticket $ticket): int => (int) $ticket->sourcePurchaseItem->purchase->getKey())
|
||||||
|
->map(function (Collection $purchaseTickets): array {
|
||||||
|
return [
|
||||||
|
'purchase_id' => (int) $purchaseTickets->first()->sourcePurchaseItem->purchase->getKey(),
|
||||||
|
'ticket_ids' => $purchaseTickets->modelKeys(),
|
||||||
|
];
|
||||||
|
})
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,14 @@ use App\Domains\Event\Models\EventDate;
|
|||||||
class EffectiveEventDateResolver
|
class EffectiveEventDateResolver
|
||||||
{
|
{
|
||||||
public function resolve(EventDate $eventDate): ?EventDate
|
public function resolve(EventDate $eventDate): ?EventDate
|
||||||
|
{
|
||||||
|
$date = $this->resolveLatest($eventDate);
|
||||||
|
|
||||||
|
return $date !== null && $date->suspended_at === null ? $date : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sigue las reprogramaciones para presentación, incluso si el destino está suspendido. */
|
||||||
|
public function resolveLatest(EventDate $eventDate): ?EventDate
|
||||||
{
|
{
|
||||||
$current = $eventDate;
|
$current = $eventDate;
|
||||||
$visited = [];
|
$visited = [];
|
||||||
@@ -23,7 +31,7 @@ class EffectiveEventDateResolver
|
|||||||
$visited[$identity] = true;
|
$visited[$identity] = true;
|
||||||
|
|
||||||
if ($current->rescheduled_to_event_date_id === null) {
|
if ($current->rescheduled_to_event_date_id === null) {
|
||||||
return $current->suspended_at === null ? $current : null;
|
return $current;
|
||||||
}
|
}
|
||||||
|
|
||||||
$current->loadMissing('rescheduledTo');
|
$current->loadMissing('rescheduledTo');
|
||||||
|
|||||||
101
app/Domains/Event/Services/EventDateGroupingService.php
Normal file
101
app/Domains/Event/Services/EventDateGroupingService.php
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Services;
|
||||||
|
|
||||||
|
use App\Domains\Event\Models\EventDate;
|
||||||
|
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
|
class EventDateGroupingService
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Groups every historical date under its final active destination.
|
||||||
|
*
|
||||||
|
* @param Collection<int, EventDate> $dates
|
||||||
|
* @return Collection<int, EventDate>
|
||||||
|
*/
|
||||||
|
public function group(Collection $dates): Collection
|
||||||
|
{
|
||||||
|
$byId = $dates->keyBy(fn (EventDate $date): int => (int) $date->getKey());
|
||||||
|
$groups = collect();
|
||||||
|
|
||||||
|
foreach ($dates as $date) {
|
||||||
|
$destination = $this->finalDestination($date, $byId);
|
||||||
|
$key = (int) $destination->getKey();
|
||||||
|
|
||||||
|
if (! $groups->has($key)) {
|
||||||
|
$groups->put($key, [
|
||||||
|
'destination' => $destination,
|
||||||
|
'rescheduled' => collect(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $date->is($destination)) {
|
||||||
|
$group = $groups->get($key);
|
||||||
|
$historicalDate = clone $date;
|
||||||
|
$historicalDate->setAttribute(
|
||||||
|
'rescheduled_to_event_date_id',
|
||||||
|
$destination->getKey(),
|
||||||
|
);
|
||||||
|
$group['rescheduled']->push($historicalDate);
|
||||||
|
$groups->put($key, $group);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $groups
|
||||||
|
->map(function (array $group): EventDate {
|
||||||
|
/** @var EventDate $destination */
|
||||||
|
$destination = clone $group['destination'];
|
||||||
|
/** @var Collection<int, EventDate> $rescheduled */
|
||||||
|
$rescheduled = $group['rescheduled'];
|
||||||
|
$destination->setRelation(
|
||||||
|
'adminRescheduledDates',
|
||||||
|
new EloquentCollection($rescheduled->sort($this->dateSorter())->values()->all()),
|
||||||
|
);
|
||||||
|
|
||||||
|
return $destination;
|
||||||
|
})
|
||||||
|
->sort($this->dateSorter())
|
||||||
|
->values();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Collection<int, EventDate> $byId */
|
||||||
|
private function finalDestination(EventDate $date, Collection $byId): EventDate
|
||||||
|
{
|
||||||
|
$current = $date;
|
||||||
|
$visited = collect();
|
||||||
|
|
||||||
|
while ($current->rescheduled_to_event_date_id !== null) {
|
||||||
|
$currentId = (int) $current->getKey();
|
||||||
|
|
||||||
|
if ($visited->contains($currentId)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
$visited->push($currentId);
|
||||||
|
$destination = $byId->get((int) $current->rescheduled_to_event_date_id);
|
||||||
|
|
||||||
|
if (! $destination instanceof EventDate) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
$current = $destination;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $current;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return callable(EventDate, EventDate): int */
|
||||||
|
private function dateSorter(): callable
|
||||||
|
{
|
||||||
|
return fn (EventDate $left, EventDate $right): int => [
|
||||||
|
$left->date->format('Y-m-d'),
|
||||||
|
$left->time_start,
|
||||||
|
$left->getKey(),
|
||||||
|
] <=> [
|
||||||
|
$right->date->format('Y-m-d'),
|
||||||
|
$right->time_start,
|
||||||
|
$right->getKey(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
76
app/Domains/Event/Services/EventDateInfoFormatter.php
Normal file
76
app/Domains/Event/Services/EventDateInfoFormatter.php
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Services;
|
||||||
|
|
||||||
|
use App\Domains\Event\Enums\EventDateChangeType;
|
||||||
|
use App\Domains\Event\Models\EventDate;
|
||||||
|
use App\Domains\Event\Models\EventDateChange;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
|
class EventDateInfoFormatter
|
||||||
|
{
|
||||||
|
/** @param Collection<int, EventDateChange> $changes */
|
||||||
|
public function format(EventDate $eventDate, Collection $changes): ?string
|
||||||
|
{
|
||||||
|
$messages = collect();
|
||||||
|
|
||||||
|
if ($eventDate->suspended_at !== null) {
|
||||||
|
$messages->push('Esta fecha fue cancelada.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$sourceDates = $this->reschedulesEndingAt($eventDate, $changes)
|
||||||
|
->pluck('previous_date')
|
||||||
|
->filter()
|
||||||
|
->map(fn ($date): string => $date->format('d/m/Y'))
|
||||||
|
->unique()
|
||||||
|
->values();
|
||||||
|
|
||||||
|
if ($sourceDates->isNotEmpty()) {
|
||||||
|
$verb = $sourceDates->count() === 1 ? 'se reprogramó' : 'se reprogramaron';
|
||||||
|
$messages->push("{$sourceDates->join(', ', ' y ')} {$verb} para este día.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return $messages->isEmpty() ? null : $messages->join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Includes direct and intermediate reschedules that ultimately end at the
|
||||||
|
* displayed event date, while preserving the original change order.
|
||||||
|
*
|
||||||
|
* @param Collection<int, EventDateChange> $changes
|
||||||
|
* @return Collection<int, EventDateChange>
|
||||||
|
*/
|
||||||
|
private function reschedulesEndingAt(EventDate $eventDate, Collection $changes): Collection
|
||||||
|
{
|
||||||
|
$eventDateId = $eventDate->getKey();
|
||||||
|
$reschedules = $changes->where('change_type', EventDateChangeType::Rescheduled);
|
||||||
|
|
||||||
|
if ($eventDateId === null) {
|
||||||
|
return $reschedules->where('destination_event_date_id', null);
|
||||||
|
}
|
||||||
|
|
||||||
|
$destinationIds = [(int) $eventDateId => true];
|
||||||
|
|
||||||
|
do {
|
||||||
|
$foundAncestor = false;
|
||||||
|
|
||||||
|
foreach ($reschedules as $change) {
|
||||||
|
$destinationId = $change->destination_event_date_id;
|
||||||
|
$sourceId = $change->source_event_date_id;
|
||||||
|
|
||||||
|
if ($destinationId === null || $sourceId === null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($destinationIds[(int) $destinationId]) && ! isset($destinationIds[(int) $sourceId])) {
|
||||||
|
$destinationIds[(int) $sourceId] = true;
|
||||||
|
$foundAncestor = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} while ($foundAncestor);
|
||||||
|
|
||||||
|
return $reschedules
|
||||||
|
->filter(fn (EventDateChange $change): bool => $change->destination_event_date_id !== null
|
||||||
|
&& isset($destinationIds[(int) $change->destination_event_date_id]));
|
||||||
|
}
|
||||||
|
}
|
||||||
126
app/Domains/Event/Services/EventDateNoticeFormatter.php
Normal file
126
app/Domains/Event/Services/EventDateNoticeFormatter.php
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Services;
|
||||||
|
|
||||||
|
use App\Domains\Event\Enums\EventDateChangeType;
|
||||||
|
use App\Domains\Event\Models\EventDateChange;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
|
class EventDateNoticeFormatter
|
||||||
|
{
|
||||||
|
public function __construct(private readonly EventDateTextFormatter $dateTextFormatter) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, EventDateChange> $changes
|
||||||
|
* @return list<array{
|
||||||
|
* type: string,
|
||||||
|
* change_ids: list<int>,
|
||||||
|
* title: string,
|
||||||
|
* message: list<array{text: string, bold: bool}>
|
||||||
|
* }>
|
||||||
|
*/
|
||||||
|
public function format(Collection $changes): array
|
||||||
|
{
|
||||||
|
return collect([
|
||||||
|
$this->suspensionNotice(
|
||||||
|
$changes->where('change_type', EventDateChangeType::Suspended)
|
||||||
|
),
|
||||||
|
$this->rescheduleNotice(
|
||||||
|
$changes->where('change_type', EventDateChangeType::Rescheduled)
|
||||||
|
),
|
||||||
|
])->filter()->values()->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, EventDateChange> $changes
|
||||||
|
* @return array{type: string, change_ids: list<int>, title: string, message: list<array{text: string, bold: bool}>}|null
|
||||||
|
*/
|
||||||
|
private function suspensionNotice(Collection $changes): ?array
|
||||||
|
{
|
||||||
|
$dates = $this->formatDates($changes, 'previous_date');
|
||||||
|
|
||||||
|
if ($dates === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$plural = $changes->count() > 1;
|
||||||
|
|
||||||
|
return [
|
||||||
|
'type' => EventDateChangeType::Suspended->value,
|
||||||
|
'change_ids' => $this->changeIds($changes),
|
||||||
|
'title' => $plural ? 'FECHAS CANCELADAS!' : 'FECHA CANCELADA!',
|
||||||
|
'message' => [
|
||||||
|
['text' => $plural ? 'Las fechas del ' : 'La fecha del ', 'bold' => false],
|
||||||
|
['text' => $dates, 'bold' => true],
|
||||||
|
['text' => $plural ? ' han sido canceladas.' : ' ha sido cancelada.', 'bold' => false],
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, EventDateChange> $changes
|
||||||
|
* @return array{type: string, change_ids: list<int>, title: string, message: list<array{text: string, bold: bool}>}|null
|
||||||
|
*/
|
||||||
|
private function rescheduleNotice(Collection $changes): ?array
|
||||||
|
{
|
||||||
|
$changes = $changes->whereNotNull('new_date');
|
||||||
|
$sourceDates = $this->formatDates($changes, 'previous_date');
|
||||||
|
$destinationDates = $this->formatDates($changes, 'new_date');
|
||||||
|
|
||||||
|
if ($sourceDates === null || $destinationDates === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$plural = $changes->count() > 1;
|
||||||
|
$message = [
|
||||||
|
['text' => $plural ? 'Las fechas del ' : 'La fecha del ', 'bold' => false],
|
||||||
|
['text' => $sourceDates, 'bold' => true],
|
||||||
|
[
|
||||||
|
'text' => $plural ? ' han sido reprogramadas para el ' : ' ha sido reprogramada para el ',
|
||||||
|
'bold' => false,
|
||||||
|
],
|
||||||
|
['text' => $destinationDates, 'bold' => true],
|
||||||
|
];
|
||||||
|
|
||||||
|
if ($plural) {
|
||||||
|
$message[] = ['text' => ', ', 'bold' => false];
|
||||||
|
$message[] = ['text' => 'respectivamente', 'bold' => true];
|
||||||
|
}
|
||||||
|
|
||||||
|
$message[] = ['text' => '.', 'bold' => false];
|
||||||
|
|
||||||
|
return [
|
||||||
|
'type' => EventDateChangeType::Rescheduled->value,
|
||||||
|
'change_ids' => $this->changeIds($changes),
|
||||||
|
'title' => $plural ? 'FECHAS REPROGRAMADAS!' : 'FECHA REPROGRAMADA!',
|
||||||
|
'message' => $message,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, EventDateChange> $changes
|
||||||
|
*/
|
||||||
|
private function formatDates(Collection $changes, string $attribute): ?string
|
||||||
|
{
|
||||||
|
return $this->dateTextFormatter->formatForSentence(
|
||||||
|
$changes
|
||||||
|
->pluck($attribute)
|
||||||
|
->filter()
|
||||||
|
->map(fn ($date): string => $date->format('Y-m-d'))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, EventDateChange> $changes
|
||||||
|
* @return list<int>
|
||||||
|
*/
|
||||||
|
private function changeIds(Collection $changes): array
|
||||||
|
{
|
||||||
|
return $changes
|
||||||
|
->pluck('id')
|
||||||
|
->filter(fn ($id): bool => $id !== null)
|
||||||
|
->map(fn ($id): int => (int) $id)
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
}
|
||||||
60
app/Domains/Event/Services/EventDateNoticeService.php
Normal file
60
app/Domains/Event/Services/EventDateNoticeService.php
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Services;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Event\Models\EventDateChange;
|
||||||
|
use App\Domains\Event\Models\EventDateChangeView;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
class EventDateNoticeService
|
||||||
|
{
|
||||||
|
public const MAX_DISPLAYS = 3;
|
||||||
|
|
||||||
|
public function __construct(private readonly EventDateNoticeFormatter $formatter) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Claims one display of every pending change and returns them grouped by type.
|
||||||
|
*
|
||||||
|
* @return list<array{
|
||||||
|
* type: string,
|
||||||
|
* change_ids: list<int>,
|
||||||
|
* title: string,
|
||||||
|
* message: list<array{text: string, bold: bool}>
|
||||||
|
* }>
|
||||||
|
*/
|
||||||
|
public function claimFor(User $user, Tenant $tenant): array
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($user, $tenant): array {
|
||||||
|
$lockedUser = User::query()->whereKey($user->getKey())->lockForUpdate()->firstOrFail();
|
||||||
|
|
||||||
|
$changes = EventDateChange::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->whereDoesntHave('views', fn ($query) => $query
|
||||||
|
->where('user_id', $lockedUser->getKey())
|
||||||
|
->where('display_count', '>=', self::MAX_DISPLAYS))
|
||||||
|
->orderBy('created_at')
|
||||||
|
->orderBy('id')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
$notices = $this->formatter->format($changes);
|
||||||
|
$claimedChangeIds = collect($notices)->pluck('change_ids')->flatten()->unique();
|
||||||
|
|
||||||
|
foreach ($claimedChangeIds as $changeId) {
|
||||||
|
$view = EventDateChangeView::query()->firstOrNew([
|
||||||
|
'user_id' => $lockedUser->getKey(),
|
||||||
|
'event_date_change_id' => $changeId,
|
||||||
|
]);
|
||||||
|
$view->display_count = min(
|
||||||
|
self::MAX_DISPLAYS,
|
||||||
|
((int) $view->display_count) + 1,
|
||||||
|
);
|
||||||
|
$view->last_displayed_at = now();
|
||||||
|
$view->save();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $notices;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,6 +25,21 @@ class EventDateTextFormatter
|
|||||||
/** @param iterable<string> $dates */
|
/** @param iterable<string> $dates */
|
||||||
public function format(iterable $dates): ?string
|
public function format(iterable $dates): ?string
|
||||||
{
|
{
|
||||||
|
return $this->formatWithOptions($dates, false, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param iterable<string> $dates */
|
||||||
|
public function formatForSentence(iterable $dates): ?string
|
||||||
|
{
|
||||||
|
return $this->formatWithOptions($dates, true, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param iterable<string> $dates */
|
||||||
|
private function formatWithOptions(
|
||||||
|
iterable $dates,
|
||||||
|
bool $padDays,
|
||||||
|
bool $includeYearPreposition,
|
||||||
|
): ?string {
|
||||||
$normalizedDates = collect($dates)
|
$normalizedDates = collect($dates)
|
||||||
->map(fn (string $date): DateTimeImmutable => new DateTimeImmutable($date))
|
->map(fn (string $date): DateTimeImmutable => new DateTimeImmutable($date))
|
||||||
->unique(fn (DateTimeImmutable $date): string => $date->format('Y-m-d'))
|
->unique(fn (DateTimeImmutable $date): string => $date->format('Y-m-d'))
|
||||||
@@ -37,12 +52,14 @@ class EventDateTextFormatter
|
|||||||
|
|
||||||
$years = $normalizedDates
|
$years = $normalizedDates
|
||||||
->groupBy(fn (DateTimeImmutable $date): string => $date->format('Y'))
|
->groupBy(fn (DateTimeImmutable $date): string => $date->format('Y'))
|
||||||
->map(function ($yearDates, string $year): string {
|
->map(function ($yearDates, string $year) use ($padDays, $includeYearPreposition): string {
|
||||||
$months = $yearDates
|
$months = $yearDates
|
||||||
->groupBy(fn (DateTimeImmutable $date): string => $date->format('n'))
|
->groupBy(fn (DateTimeImmutable $date): string => $date->format('n'))
|
||||||
->map(function ($monthDates, string $month): string {
|
->map(function ($monthDates, string $month) use ($padDays): string {
|
||||||
$days = $monthDates
|
$days = $monthDates
|
||||||
->map(fn (DateTimeImmutable $date): string => (string) ((int) $date->format('j')))
|
->map(fn (DateTimeImmutable $date): string => $padDays
|
||||||
|
? $date->format('d')
|
||||||
|
: (string) ((int) $date->format('j')))
|
||||||
->values()
|
->values()
|
||||||
->all();
|
->all();
|
||||||
|
|
||||||
@@ -51,7 +68,7 @@ class EventDateTextFormatter
|
|||||||
->values()
|
->values()
|
||||||
->all();
|
->all();
|
||||||
|
|
||||||
return $this->join($months).' '.$year;
|
return $this->join($months).($includeYearPreposition ? ' de ' : ' ').$year;
|
||||||
})
|
})
|
||||||
->values()
|
->values()
|
||||||
->all();
|
->all();
|
||||||
|
|||||||
@@ -2,10 +2,19 @@
|
|||||||
|
|
||||||
namespace App\Domains\Event\Services;
|
namespace App\Domains\Event\Services;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Cart\Services\InvalidateEventDateCartsService;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
|
use App\Domains\Catalog\Services\StockReservationService;
|
||||||
|
use App\Domains\Catalog\Services\VariantReplacementService;
|
||||||
|
use App\Domains\Event\Enums\EventDateChangeType;
|
||||||
|
use App\Domains\Event\Events\EventDateRescheduled;
|
||||||
|
use App\Domains\Event\Events\EventDateSuspended;
|
||||||
use App\Domains\Event\Models\EventDate;
|
use App\Domains\Event\Models\EventDate;
|
||||||
|
use App\Domains\Event\Models\EventDateChange;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use App\Domains\Ticket\Models\Ticket;
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
@@ -19,6 +28,9 @@ class EventService
|
|||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
private readonly EffectiveEventDateResolver $effectiveEventDateResolver,
|
private readonly EffectiveEventDateResolver $effectiveEventDateResolver,
|
||||||
|
private readonly AffectedEventDatePurchaseResolver $affectedPurchaseResolver,
|
||||||
|
private readonly VariantReplacementService $variantReplacementService,
|
||||||
|
private readonly InvalidateEventDateCartsService $invalidateEventDateCarts,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public function forTenant(Tenant $tenant): Tenant
|
public function forTenant(Tenant $tenant): Tenant
|
||||||
@@ -69,9 +81,13 @@ class EventService
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @param array{date: string} $data */
|
/** @param array{date: string} $data */
|
||||||
public function rescheduleDateForTenant(Tenant $tenant, EventDate $eventDate, array $data): EventDate
|
public function rescheduleDateForTenant(
|
||||||
{
|
Tenant $tenant,
|
||||||
return DB::transaction(function () use ($tenant, $eventDate, $data): EventDate {
|
EventDate $eventDate,
|
||||||
|
array $data,
|
||||||
|
?User $createdBy = null,
|
||||||
|
): EventDate {
|
||||||
|
return DB::transaction(function () use ($tenant, $eventDate, $data, $createdBy): EventDate {
|
||||||
$source = $this->lockedDateForTenant($tenant, $eventDate);
|
$source = $this->lockedDateForTenant($tenant, $eventDate);
|
||||||
|
|
||||||
if ($source->suspended_at !== null) {
|
if ($source->suspended_at !== null) {
|
||||||
@@ -105,21 +121,51 @@ class EventService
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($this->effectiveEventDateResolver->resolve($destination) === null) {
|
$effectiveDestination = $this->effectiveEventDateResolver->resolve($destination);
|
||||||
|
if ($effectiveDestination === null) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'date' => ['La fecha de destino no es utilizable.'],
|
'date' => ['La fecha de destino no es utilizable.'],
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$affectedDateIds = $this->affectedDateIds($tenant, $source);
|
||||||
|
$this->invalidateEventDateCarts->invalidate($tenant, $affectedDateIds);
|
||||||
|
$purchaseTickets = $this->affectedPurchaseResolver->resolve(
|
||||||
|
$tenant,
|
||||||
|
$affectedDateIds,
|
||||||
|
);
|
||||||
$source->update(['rescheduled_to_event_date_id' => $destination->getKey()]);
|
$source->update(['rescheduled_to_event_date_id' => $destination->getKey()]);
|
||||||
|
$this->variantReplacementService->replaceEventDate($source, $effectiveDestination);
|
||||||
|
|
||||||
|
EventDateChange::query()->create([
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'change_type' => EventDateChangeType::Rescheduled,
|
||||||
|
'source_event_date_id' => $source->getKey(),
|
||||||
|
'destination_event_date_id' => $destination->getKey(),
|
||||||
|
'created_by_user_id' => $createdBy?->getKey(),
|
||||||
|
'previous_date' => $source->date->format('Y-m-d'),
|
||||||
|
'new_date' => $destination->date->format('Y-m-d'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
EventDateRescheduled::dispatch(
|
||||||
|
$tenant->codigo,
|
||||||
|
$source->getKey(),
|
||||||
|
$destination->getKey(),
|
||||||
|
$source->date->format('d/m/Y'),
|
||||||
|
$destination->date->format('d/m/Y'),
|
||||||
|
$purchaseTickets,
|
||||||
|
);
|
||||||
|
|
||||||
return $source->fresh(['validityTime', 'rescheduledTo.validityTime']);
|
return $source->fresh(['validityTime', 'rescheduledTo.validityTime']);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function suspendDateForTenant(Tenant $tenant, EventDate $eventDate): EventDate
|
public function suspendDateForTenant(
|
||||||
{
|
Tenant $tenant,
|
||||||
return DB::transaction(function () use ($tenant, $eventDate): EventDate {
|
EventDate $eventDate,
|
||||||
|
?User $createdBy = null,
|
||||||
|
): EventDate {
|
||||||
|
return DB::transaction(function () use ($tenant, $eventDate, $createdBy): EventDate {
|
||||||
$date = $this->lockedDateForTenant($tenant, $eventDate);
|
$date = $this->lockedDateForTenant($tenant, $eventDate);
|
||||||
|
|
||||||
if ($date->rescheduled_to_event_date_id !== null) {
|
if ($date->rescheduled_to_event_date_id !== null) {
|
||||||
@@ -132,9 +178,34 @@ class EventService
|
|||||||
return $date->load('validityTime');
|
return $date->load('validityTime');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$affectedDateIds = $this->affectedDateIds($tenant, $date);
|
||||||
|
$this->invalidateEventDateCarts->invalidate(
|
||||||
|
$tenant,
|
||||||
|
$affectedDateIds,
|
||||||
|
StockReservationService::REASON_EVENT_DATE_SUSPENDED,
|
||||||
|
);
|
||||||
|
$purchaseTickets = $this->affectedPurchaseResolver->resolve($tenant, $affectedDateIds);
|
||||||
$date->update(['suspended_at' => now()]);
|
$date->update(['suspended_at' => now()]);
|
||||||
|
$this->variantReplacementService->disableForSuspension($date);
|
||||||
$this->disableTicketsWithoutUsableDates($tenant, $date);
|
$this->disableTicketsWithoutUsableDates($tenant, $date);
|
||||||
|
|
||||||
|
EventDateChange::query()->create([
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'change_type' => EventDateChangeType::Suspended,
|
||||||
|
'source_event_date_id' => $date->getKey(),
|
||||||
|
'destination_event_date_id' => null,
|
||||||
|
'created_by_user_id' => $createdBy?->getKey(),
|
||||||
|
'previous_date' => $date->date->format('Y-m-d'),
|
||||||
|
'new_date' => null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
EventDateSuspended::dispatch(
|
||||||
|
$tenant->codigo,
|
||||||
|
$date->getKey(),
|
||||||
|
$date->date->format('d/m/Y'),
|
||||||
|
$purchaseTickets,
|
||||||
|
);
|
||||||
|
|
||||||
return $date->fresh('validityTime');
|
return $date->fresh('validityTime');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -172,9 +243,10 @@ class EventService
|
|||||||
return $current->is($expected);
|
return $current->is($expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function disableTicketsWithoutUsableDates(Tenant $tenant, EventDate $suspendedDate): void
|
/** @return Collection<int, int> */
|
||||||
|
private function affectedDateIds(Tenant $tenant, EventDate $eventDate): Collection
|
||||||
{
|
{
|
||||||
$affectedDateIds = collect([$suspendedDate->getKey()]);
|
$affectedDateIds = collect([$eventDate->getKey()]);
|
||||||
$frontier = $affectedDateIds;
|
$frontier = $affectedDateIds;
|
||||||
|
|
||||||
while ($frontier->isNotEmpty()) {
|
while ($frontier->isNotEmpty()) {
|
||||||
@@ -187,6 +259,13 @@ class EventService
|
|||||||
$frontier = $predecessors;
|
$frontier = $predecessors;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return $affectedDateIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function disableTicketsWithoutUsableDates(Tenant $tenant, EventDate $suspendedDate): void
|
||||||
|
{
|
||||||
|
$affectedDateIds = $this->affectedDateIds($tenant, $suspendedDate);
|
||||||
|
|
||||||
$variants = Variant::withTrashed()
|
$variants = Variant::withTrashed()
|
||||||
->where(function ($query) use ($affectedDateIds): void {
|
->where(function ($query) use ($affectedDateIds): void {
|
||||||
$query->whereIn('event_date_id', $affectedDateIds)
|
$query->whereIn('event_date_id', $affectedDateIds)
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ Administra la configuración temporal de un tenant orientado a eventos y sus fec
|
|||||||
|
|
||||||
- `Models/EventDate.php`: fecha del evento con inicio, fin, tenant y variantes asociadas.
|
- `Models/EventDate.php`: fecha del evento con inicio, fin, tenant y variantes asociadas.
|
||||||
- `Services/EventService.php`: obtiene y actualiza la configuración de evento del tenant.
|
- `Services/EventService.php`: obtiene y actualiza la configuración de evento del tenant.
|
||||||
|
- `Services/EventDateNoticeService.php`: reclama y agrupa los cambios pendientes de cada usuario.
|
||||||
- `Controllers/AdminApp/EventController.php`: consulta y modificación desde AdminApp.
|
- `Controllers/AdminApp/EventController.php`: consulta y modificación desde AdminApp.
|
||||||
- `UpdateEventRequest`: valida datos y reglas cruzadas de fechas.
|
- `UpdateEventRequest`: valida datos y reglas cruzadas de fechas.
|
||||||
- `EventResource`: serializa la configuración de salida.
|
- `EventResource`: serializa la configuración de salida.
|
||||||
@@ -19,10 +20,18 @@ Bajo `/v1/adminapp/tenant/event`, protegidos por `auth:sanctum` y `adminapp.tena
|
|||||||
- `GET`: obtiene la configuración.
|
- `GET`: obtiene la configuración.
|
||||||
- `PUT`: actualiza la configuración.
|
- `PUT`: actualiza la configuración.
|
||||||
|
|
||||||
|
Para el storefront autenticado:
|
||||||
|
|
||||||
|
- `POST /tenants/{tenant}/event-date-notices/claim`: devuelve hasta un aviso de suspensiones y otro de
|
||||||
|
reprogramaciones. Cada cambio se muestra como máximo tres veces por usuario.
|
||||||
|
|
||||||
## Dependencias
|
## Dependencias
|
||||||
|
|
||||||
Depende de `Tenant`. Las fechas se vinculan con variantes de `Catalog`, que a su vez pueden generar tickets.
|
Depende de `Tenant`. Las fechas se vinculan con variantes de `Catalog`, que a su vez pueden generar tickets.
|
||||||
|
|
||||||
## Consideraciones
|
## Consideraciones
|
||||||
|
|
||||||
El archivo `routes/api.php` no publica operaciones adicionales. Al modificar fechas debe mantenerse la validación de orden y coherencia temporal de `UpdateEventRequest`.
|
Los avisos se construyen dinámicamente después de excluir los cambios que el usuario ya vio
|
||||||
|
tres veces. Al reclamar los avisos se incrementa una vez cada cambio incluido, aunque varios
|
||||||
|
cambios aparezcan agrupados en el mismo mensaje. El reclamo bloquea al usuario durante la
|
||||||
|
transacción para impedir que pestañas concurrentes superen el máximo.
|
||||||
|
|||||||
@@ -1,3 +1,11 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Event\Controllers\EventDateNoticeController;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
require __DIR__.'/adminapp.php';
|
require __DIR__.'/adminapp.php';
|
||||||
|
|
||||||
|
Route::middleware('auth:sanctum')->post(
|
||||||
|
'tenants/{tenant:codigo}/event-date-notices/claim',
|
||||||
|
[EventDateNoticeController::class, 'claim'],
|
||||||
|
);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domains\FiestaFutbolInfantil\Controllers;
|
namespace App\Domains\FiestaFutbolInfantil\Controllers;
|
||||||
|
|
||||||
|
use App\Domains\FiestaFutbolInfantil\Requests\UpdateHistoricalFoodStockRequest;
|
||||||
use App\Domains\FiestaFutbolInfantil\Requests\UpsertFoodVariantsRequest;
|
use App\Domains\FiestaFutbolInfantil\Requests\UpsertFoodVariantsRequest;
|
||||||
use App\Domains\FiestaFutbolInfantil\Resources\FoodResource;
|
use App\Domains\FiestaFutbolInfantil\Resources\FoodResource;
|
||||||
use App\Domains\FiestaFutbolInfantil\Services\FoodService;
|
use App\Domains\FiestaFutbolInfantil\Services\FoodService;
|
||||||
@@ -32,6 +33,16 @@ class FoodController extends Controller
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function updateHistoricalStock(UpdateHistoricalFoodStockRequest $request): FoodResource
|
||||||
|
{
|
||||||
|
return FoodResource::make(
|
||||||
|
$this->foodService->updateHistoricalStock(
|
||||||
|
$request->user()->tenant()->firstOrFail(),
|
||||||
|
$request->validated('variants'),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
public function destroy(Request $request, int $food): Response
|
public function destroy(Request $request, int $food): Response
|
||||||
{
|
{
|
||||||
$this->foodService->delete(
|
$this->foodService->delete(
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\FiestaFutbolInfantil\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class UpdateHistoricalFoodStockRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'variants' => ['required', 'array', 'min:1', 'max:500'],
|
||||||
|
'variants.*' => ['required', 'array:id,stock'],
|
||||||
|
'variants.*.id' => ['required', 'integer', 'distinct'],
|
||||||
|
'variants.*.stock' => ['required', 'integer', 'min:0'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ namespace App\Domains\FiestaFutbolInfantil\Resources;
|
|||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
/** @mixin CatalogItem */
|
/** @mixin CatalogItem */
|
||||||
class EntryResource extends JsonResource
|
class EntryResource extends JsonResource
|
||||||
@@ -12,7 +13,20 @@ class EntryResource extends JsonResource
|
|||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
public function toArray(Request $request): array
|
public function toArray(Request $request): array
|
||||||
{
|
{
|
||||||
$variant = $this->variants->sole();
|
$variants = $this->variants->whereNull('replaced_by_variant_id');
|
||||||
|
|
||||||
|
if ($variants->count() !== 1) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'entries' => [sprintf(
|
||||||
|
'La entrada %s tiene %d variantes sin reemplazar (IDs: %s). Se esperaba una.',
|
||||||
|
$this->id,
|
||||||
|
$variants->count(),
|
||||||
|
$variants->pluck('id')->implode(', '),
|
||||||
|
)],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$variant = $variants->first();
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => $this->id,
|
'id' => $this->id,
|
||||||
|
|||||||
@@ -3,8 +3,14 @@
|
|||||||
namespace App\Domains\FiestaFutbolInfantil\Resources;
|
namespace App\Domains\FiestaFutbolInfantil\Resources;
|
||||||
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
|
use App\Domains\Catalog\Models\Variant;
|
||||||
|
use App\Domains\Event\Enums\EventDateChangeType;
|
||||||
|
use App\Domains\Event\Enums\EventDateStatus;
|
||||||
|
use App\Domains\Event\Models\EventDate;
|
||||||
|
use App\Domains\Event\Models\EventDateChange;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
/** @mixin CatalogItem */
|
/** @mixin CatalogItem */
|
||||||
class FoodResource extends JsonResource
|
class FoodResource extends JsonResource
|
||||||
@@ -17,13 +23,54 @@ class FoodResource extends JsonResource
|
|||||||
'id' => null,
|
'id' => null,
|
||||||
'name' => 'Comida',
|
'name' => 'Comida',
|
||||||
'variants' => [],
|
'variants' => [],
|
||||||
|
'history' => [],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$currentVariants = $this->variants
|
||||||
|
->filter(fn (Variant $variant): bool => $this->isCurrent($variant));
|
||||||
|
$historicalVariants = $this->variants
|
||||||
|
->filter(fn (Variant $variant): bool => $this->isHistorical($variant));
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => $this->id,
|
'id' => $this->id,
|
||||||
'name' => $this->nombre,
|
'name' => $this->nombre,
|
||||||
'variants' => $this->variants->map(function ($variant): array {
|
'variants' => $currentVariants->map($this->variantData(...))->values(),
|
||||||
|
'history' => $this->historyData($historicalVariants),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function isCurrent(Variant $variant): bool
|
||||||
|
{
|
||||||
|
if ($variant->sales_disabled_at !== null || $variant->replaced_by_variant_id !== null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$status = $variant->selectedEventDates()->first()?->status;
|
||||||
|
|
||||||
|
return $status === null || in_array(
|
||||||
|
$status,
|
||||||
|
[EventDateStatus::Scheduled, EventDateStatus::InProgress],
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function isHistorical(Variant $variant): bool
|
||||||
|
{
|
||||||
|
return in_array(
|
||||||
|
$variant->selectedEventDates()->first()?->status,
|
||||||
|
[
|
||||||
|
EventDateStatus::Rescheduled,
|
||||||
|
EventDateStatus::Suspended,
|
||||||
|
EventDateStatus::Completed,
|
||||||
|
],
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
private function variantData(Variant $variant): array
|
||||||
|
{
|
||||||
$values = $variant->selectionValues();
|
$values = $variant->selectionValues();
|
||||||
$eventDate = $variant->selectedEventDates()->first();
|
$eventDate = $variant->selectedEventDates()->first();
|
||||||
|
|
||||||
@@ -37,7 +84,73 @@ class FoodResource extends JsonResource
|
|||||||
'stock' => $variant->inventory->real_stock,
|
'stock' => $variant->inventory->real_stock,
|
||||||
'price' => number_format($variant->getPrice(), 2, '.', ''),
|
'price' => number_format($variant->getPrice(), 2, '.', ''),
|
||||||
];
|
];
|
||||||
})->values(),
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, Variant> $variants
|
||||||
|
* @return Collection<int, array<string, mixed>>
|
||||||
|
*/
|
||||||
|
private function historyData(Collection $variants): Collection
|
||||||
|
{
|
||||||
|
return $variants
|
||||||
|
->filter(fn (Variant $variant): bool => $variant->selectedEventDates()->first() !== null)
|
||||||
|
->groupBy(fn (Variant $variant): int => (int) $variant->selectedEventDates()->first()->id)
|
||||||
|
->map(function (Collection $dateVariants): array {
|
||||||
|
/** @var EventDate $eventDate */
|
||||||
|
$eventDate = $dateVariants->first()->selectedEventDates()->first();
|
||||||
|
$status = $this->historicalStatus($eventDate);
|
||||||
|
$change = $this->changeForStatus($eventDate, $status);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'id' => $eventDate->id,
|
||||||
|
'change_id' => $change?->id,
|
||||||
|
'status' => $status->value,
|
||||||
|
'status_text' => match ($status) {
|
||||||
|
EventDateStatus::Rescheduled => 'REPROGRAMADA',
|
||||||
|
EventDateStatus::Suspended => 'CANCELADA',
|
||||||
|
EventDateStatus::Completed => 'FINALIZADA',
|
||||||
|
default => '',
|
||||||
|
},
|
||||||
|
'event_date_id' => $eventDate->id,
|
||||||
|
'event_date' => $eventDate->date->format('Y-m-d'),
|
||||||
|
'replacement_event_date_id' => $status === EventDateStatus::Rescheduled
|
||||||
|
? ($change?->destination_event_date_id
|
||||||
|
?? $eventDate->rescheduled_to_event_date_id)
|
||||||
|
: null,
|
||||||
|
'replacement_event_date' => $status === EventDateStatus::Rescheduled
|
||||||
|
? ($change?->new_date?->format('Y-m-d')
|
||||||
|
?? $eventDate->rescheduledTo?->date?->format('Y-m-d'))
|
||||||
|
: null,
|
||||||
|
'occurred_at' => ($change?->created_at ?? $eventDate->endsAt())->toISOString(),
|
||||||
|
'variants' => $dateVariants->map($this->variantData(...))->values(),
|
||||||
];
|
];
|
||||||
|
})
|
||||||
|
->sortByDesc('occurred_at')
|
||||||
|
->values();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function historicalStatus(EventDate $eventDate): EventDateStatus
|
||||||
|
{
|
||||||
|
return match ($eventDate->status) {
|
||||||
|
EventDateStatus::Rescheduled => EventDateStatus::Rescheduled,
|
||||||
|
EventDateStatus::Suspended => EventDateStatus::Suspended,
|
||||||
|
default => EventDateStatus::Completed,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private function changeForStatus(
|
||||||
|
EventDate $eventDate,
|
||||||
|
EventDateStatus $status,
|
||||||
|
): ?EventDateChange {
|
||||||
|
$changeType = match ($status) {
|
||||||
|
EventDateStatus::Rescheduled => EventDateChangeType::Rescheduled,
|
||||||
|
EventDateStatus::Suspended => EventDateChangeType::Suspended,
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
return $changeType === null
|
||||||
|
? null
|
||||||
|
: $eventDate->changeHistory
|
||||||
|
->first(fn (EventDateChange $change): bool => $change->change_type === $changeType);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,13 @@ class EntryService
|
|||||||
return CatalogItem::query()
|
return CatalogItem::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
->whereHas('category', fn ($query) => $query->where('nombre', 'Entradas'))
|
->whereHas('category', fn ($query) => $query->where('nombre', 'Entradas'))
|
||||||
|
->whereHas('variants', fn ($query) => $query
|
||||||
|
->whereNull('replaced_by_variant_id')
|
||||||
|
->whereNull('sales_disabled_at'))
|
||||||
->with([
|
->with([
|
||||||
|
'variants' => fn ($query) => $query
|
||||||
|
->whereNull('replaced_by_variant_id')
|
||||||
|
->whereNull('sales_disabled_at'),
|
||||||
'variants.inventory',
|
'variants.inventory',
|
||||||
'variants.eventDate',
|
'variants.eventDate',
|
||||||
'variants.eventDates',
|
'variants.eventDates',
|
||||||
@@ -97,6 +103,7 @@ class EntryService
|
|||||||
|
|
||||||
$variants = Variant::query()
|
$variants = Variant::query()
|
||||||
->where('catalog_item_id', $catalogItem->id)
|
->where('catalog_item_id', $catalogItem->id)
|
||||||
|
->whereNull('replaced_by_variant_id')
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->get();
|
->get();
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ use App\Domains\Catalog\Models\Inventory;
|
|||||||
use App\Domains\Catalog\Models\ItemAttribute;
|
use App\Domains\Catalog\Models\ItemAttribute;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
use App\Domains\Catalog\Services\CatalogService;
|
use App\Domains\Catalog\Services\CatalogService;
|
||||||
|
use App\Domains\Event\Enums\EventDateStatus;
|
||||||
|
use App\Domains\Event\Models\EventDate;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -36,8 +38,10 @@ class FoodService
|
|||||||
->with([
|
->with([
|
||||||
'variants.catalogItem',
|
'variants.catalogItem',
|
||||||
'variants.inventory',
|
'variants.inventory',
|
||||||
'variants.eventDate',
|
'variants.eventDate.rescheduledTo',
|
||||||
'variants.eventDates',
|
'variants.eventDate.changeHistory.destinationEventDate',
|
||||||
|
'variants.eventDates.rescheduledTo',
|
||||||
|
'variants.eventDates.changeHistory.destinationEventDate',
|
||||||
'variants.definitions.itemAttribute.attribute',
|
'variants.definitions.itemAttribute.attribute',
|
||||||
])
|
])
|
||||||
->first();
|
->first();
|
||||||
@@ -55,11 +59,16 @@ class FoodService
|
|||||||
|
|
||||||
$food->variants()->whereNull('precio')->update(['precio' => $food->precio]);
|
$food->variants()->whereNull('precio')->update(['precio' => $food->precio]);
|
||||||
$existingVariants = $food->variants()
|
$existingVariants = $food->variants()
|
||||||
|
->whereNull('sales_disabled_at')
|
||||||
|
->whereNull('replaced_by_variant_id')
|
||||||
->with(['inventory', 'eventDate', 'eventDates', 'definitions.itemAttribute.attribute'])
|
->with(['inventory', 'eventDate', 'eventDates', 'definitions.itemAttribute.attribute'])
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->get();
|
->get()
|
||||||
|
->filter(fn (Variant $variant): bool => $this->hasCurrentDate($variant))
|
||||||
|
->values();
|
||||||
$resolvedVariants = $this->resolveVariants($variants, $attributes);
|
$resolvedVariants = $this->resolveVariants($variants, $attributes);
|
||||||
|
|
||||||
|
$this->validateCurrentEventDates($tenant, $resolvedVariants);
|
||||||
$this->validateCombinations($resolvedVariants, $existingVariants);
|
$this->validateCombinations($resolvedVariants, $existingVariants);
|
||||||
|
|
||||||
foreach ($resolvedVariants as $index => $data) {
|
foreach ($resolvedVariants as $index => $data) {
|
||||||
@@ -80,7 +89,13 @@ class FoodService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$minimumPrice = $food->variants()->min('precio');
|
$minimumPrice = $food->variants()
|
||||||
|
->whereNull('sales_disabled_at')
|
||||||
|
->whereNull('replaced_by_variant_id')
|
||||||
|
->with(['eventDate', 'eventDates'])
|
||||||
|
->get()
|
||||||
|
->filter(fn (Variant $variant): bool => $this->hasCurrentDate($variant))
|
||||||
|
->min('precio');
|
||||||
if ($minimumPrice !== null) {
|
if ($minimumPrice !== null) {
|
||||||
$food->update(['precio' => $minimumPrice]);
|
$food->update(['precio' => $minimumPrice]);
|
||||||
}
|
}
|
||||||
@@ -88,22 +103,103 @@ class FoodService
|
|||||||
return $food->fresh()->load([
|
return $food->fresh()->load([
|
||||||
'variants.catalogItem',
|
'variants.catalogItem',
|
||||||
'variants.inventory',
|
'variants.inventory',
|
||||||
'variants.eventDate',
|
'variants.eventDate.rescheduledTo',
|
||||||
'variants.eventDates',
|
'variants.eventDate.changeHistory.destinationEventDate',
|
||||||
|
'variants.eventDates.rescheduledTo',
|
||||||
|
'variants.eventDates.changeHistory.destinationEventDate',
|
||||||
'variants.definitions.itemAttribute.attribute',
|
'variants.definitions.itemAttribute.attribute',
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, array{id: int, stock: int}> $variants
|
||||||
|
*/
|
||||||
|
public function updateHistoricalStock(Tenant $tenant, array $variants): CatalogItem
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($tenant, $variants): CatalogItem {
|
||||||
|
$food = CatalogItem::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->where('slug', 'comida')
|
||||||
|
->lockForUpdate()
|
||||||
|
->firstOrFail();
|
||||||
|
$variantIds = collect($variants)->pluck('id')->map(fn ($id): int => (int) $id);
|
||||||
|
$historicalVariants = $food->variants()
|
||||||
|
->whereIn('id', $variantIds)
|
||||||
|
->with(['inventory', 'eventDate', 'eventDates'])
|
||||||
|
->lockForUpdate()
|
||||||
|
->get()
|
||||||
|
->filter(fn (Variant $variant): bool => $this->hasHistoricalDate($variant))
|
||||||
|
->keyBy('id');
|
||||||
|
|
||||||
|
foreach ($variants as $index => $data) {
|
||||||
|
$variant = $historicalVariants->get((int) $data['id']);
|
||||||
|
if ($variant === null) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
"variants.{$index}.id" => [
|
||||||
|
'La variante no pertenece al historial de Comida.',
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$stock = (int) $data['stock'];
|
||||||
|
$inventory = $this->inventoryForHistoricalStockUpdate($variant);
|
||||||
|
if ($stock < $inventory->reserved_stock) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
"variants.{$index}.stock" => [
|
||||||
|
'El stock no puede ser menor que la cantidad actualmente reservada.',
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$inventory->update(['real_stock' => $stock]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->current($tenant) ?? $food;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function inventoryForHistoricalStockUpdate(Variant $variant): Inventory
|
||||||
|
{
|
||||||
|
$inventory = Inventory::query()
|
||||||
|
->whereKey($variant->inventory_id)
|
||||||
|
->lockForUpdate()
|
||||||
|
->firstOrFail();
|
||||||
|
$variantsSharingInventory = Variant::query()
|
||||||
|
->where('inventory_id', $inventory->getKey())
|
||||||
|
->orderBy('id')
|
||||||
|
->lockForUpdate()
|
||||||
|
->get(['id']);
|
||||||
|
|
||||||
|
if ($variantsSharingInventory->count() === 1) {
|
||||||
|
return $inventory;
|
||||||
|
}
|
||||||
|
|
||||||
|
$historicalInventory = Inventory::query()->create([
|
||||||
|
'sold_units' => $inventory->sold_units,
|
||||||
|
'refunded_units' => $inventory->refunded_units,
|
||||||
|
'reserved_stock' => 0,
|
||||||
|
'real_stock' => $inventory->real_stock,
|
||||||
|
]);
|
||||||
|
$variant->update(['inventory_id' => $historicalInventory->getKey()]);
|
||||||
|
|
||||||
|
return $historicalInventory;
|
||||||
|
}
|
||||||
|
|
||||||
public function delete(Tenant $tenant, int $foodId): void
|
public function delete(Tenant $tenant, int $foodId): void
|
||||||
{
|
{
|
||||||
$variant = Variant::query()
|
$variant = Variant::query()
|
||||||
->whereKey($foodId)
|
->whereKey($foodId)
|
||||||
|
->whereNull('sales_disabled_at')
|
||||||
|
->whereNull('replaced_by_variant_id')
|
||||||
|
->with(['eventDate', 'eventDates'])
|
||||||
->whereHas('catalogItem', fn ($query) => $query
|
->whereHas('catalogItem', fn ($query) => $query
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
->where('slug', 'comida'))
|
->where('slug', 'comida'))
|
||||||
->firstOrFail();
|
->firstOrFail();
|
||||||
|
|
||||||
|
abort_unless($this->hasCurrentDate($variant), 404);
|
||||||
|
|
||||||
$this->catalogService->deleteVariant($variant);
|
$this->catalogService->deleteVariant($variant);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,6 +321,30 @@ class FoodService
|
|||||||
return $option;
|
return $option;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param array<int, array<string, mixed>> $variants */
|
||||||
|
private function validateCurrentEventDates(Tenant $tenant, array $variants): void
|
||||||
|
{
|
||||||
|
$eventDates = EventDate::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->whereIn('id', collect($variants)->pluck('event_date_id')->unique())
|
||||||
|
->get()
|
||||||
|
->keyBy('id');
|
||||||
|
|
||||||
|
foreach ($variants as $index => $variant) {
|
||||||
|
$eventDate = $eventDates->get($variant['event_date_id']);
|
||||||
|
|
||||||
|
if ($eventDate !== null && $this->isCurrentStatus($eventDate->status)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
"variants.{$index}.event_date_id" => [
|
||||||
|
'La fecha seleccionada ya no está disponible.',
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<int, array<string, mixed>> $incoming
|
* @param array<int, array<string, mixed>> $incoming
|
||||||
* @param Collection<int, Variant> $existing
|
* @param Collection<int, Variant> $existing
|
||||||
@@ -329,4 +449,25 @@ class FoodService
|
|||||||
mb_strtolower(trim($service)),
|
mb_strtolower(trim($service)),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function hasCurrentDate(Variant $variant): bool
|
||||||
|
{
|
||||||
|
$status = $variant->selectedEventDates()->first()?->status;
|
||||||
|
|
||||||
|
return $status === null || $this->isCurrentStatus($status);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function hasHistoricalDate(Variant $variant): bool
|
||||||
|
{
|
||||||
|
return in_array(
|
||||||
|
$variant->selectedEventDates()->first()?->status,
|
||||||
|
[EventDateStatus::Rescheduled, EventDateStatus::Suspended, EventDateStatus::Completed],
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function isCurrentStatus(EventDateStatus $status): bool
|
||||||
|
{
|
||||||
|
return in_array($status, [EventDateStatus::Scheduled, EventDateStatus::InProgress], true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,9 @@ Route::prefix('v1/adminapp/tenant')
|
|||||||
Route::post('foods', [FoodController::class, 'store'])
|
Route::post('foods', [FoodController::class, 'store'])
|
||||||
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.comida')
|
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.comida')
|
||||||
->name('adminapp.fiesta-futbol-infantil.foods.store');
|
->name('adminapp.fiesta-futbol-infantil.foods.store');
|
||||||
|
Route::patch('foods/history-stock', [FoodController::class, 'updateHistoricalStock'])
|
||||||
|
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.comida')
|
||||||
|
->name('adminapp.fiesta-futbol-infantil.foods.history-stock.update');
|
||||||
Route::delete('foods/{food}', [FoodController::class, 'destroy'])
|
Route::delete('foods/{food}', [FoodController::class, 'destroy'])
|
||||||
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.comida')
|
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.comida')
|
||||||
->name('adminapp.fiesta-futbol-infantil.foods.destroy');
|
->name('adminapp.fiesta-futbol-infantil.foods.destroy');
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Forms\Controllers\AdminApp;
|
||||||
|
|
||||||
|
use App\Domains\Forms\Resources\EntryFormResource;
|
||||||
|
use App\Domains\Forms\Services\EntryFormService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
class EntryFormController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(protected EntryFormService $entryFormService) {}
|
||||||
|
|
||||||
|
public function __invoke(Request $request): EntryFormResource
|
||||||
|
{
|
||||||
|
return EntryFormResource::make(
|
||||||
|
$this->entryFormService->get(
|
||||||
|
$request->user('sanctum')->tenant()->firstOrFail()
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
26
app/Domains/Forms/Resources/EntryFormResource.php
Normal file
26
app/Domains/Forms/Resources/EntryFormResource.php
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Forms\Resources;
|
||||||
|
|
||||||
|
use App\Domains\Event\Models\EventDate;
|
||||||
|
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
class EntryFormResource extends JsonResource
|
||||||
|
{
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'event_dates' => $this->resource['event_dates']->map(
|
||||||
|
fn (EventDate $eventDate): array => [
|
||||||
|
'id' => $eventDate->id,
|
||||||
|
'validity_time_id' => $eventDate->validity_time_id,
|
||||||
|
'validity_time' => ValidityTimeResource::make($eventDate->validityTime),
|
||||||
|
'date' => $eventDate->date->format('Y-m-d'),
|
||||||
|
]
|
||||||
|
)->values(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
22
app/Domains/Forms/Services/EntryFormService.php
Normal file
22
app/Domains/Forms/Services/EntryFormService.php
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Forms\Services;
|
||||||
|
|
||||||
|
use App\Domains\Event\Models\EventDate;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use Illuminate\Database\Eloquent\Collection;
|
||||||
|
|
||||||
|
class EntryFormService
|
||||||
|
{
|
||||||
|
/** @return array{event_dates: Collection<int, EventDate>} */
|
||||||
|
public function get(Tenant $tenant): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'event_dates' => $tenant->eventDates()
|
||||||
|
->whereNull('rescheduled_to_event_date_id')
|
||||||
|
->whereNull('suspended_at')
|
||||||
|
->with('validityTime')
|
||||||
|
->get(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ namespace App\Domains\Forms\Services;
|
|||||||
|
|
||||||
use App\Domains\Catalog\Models\Attribute;
|
use App\Domains\Catalog\Models\Attribute;
|
||||||
use App\Domains\Catalog\Models\AttributeOption;
|
use App\Domains\Catalog\Models\AttributeOption;
|
||||||
|
use App\Domains\Event\Enums\EventDateStatus;
|
||||||
use App\Domains\Event\Models\EventDate;
|
use App\Domains\Event\Models\EventDate;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Database\Eloquent\Collection;
|
use Illuminate\Database\Eloquent\Collection;
|
||||||
@@ -27,7 +28,17 @@ class FoodFormService
|
|||||||
->keyBy('codigo');
|
->keyBy('codigo');
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'event_dates' => $tenant->eventDates()->with('validityTime')->get(),
|
'event_dates' => $tenant->eventDates()
|
||||||
|
->whereNull('rescheduled_to_event_date_id')
|
||||||
|
->whereNull('suspended_at')
|
||||||
|
->with('validityTime')
|
||||||
|
->get()
|
||||||
|
->filter(fn (EventDate $eventDate): bool => in_array(
|
||||||
|
$eventDate->status,
|
||||||
|
[EventDateStatus::Scheduled, EventDateStatus::InProgress],
|
||||||
|
true,
|
||||||
|
))
|
||||||
|
->values(),
|
||||||
'schedules' => $attributes->get('horario')?->options ?? new Collection,
|
'schedules' => $attributes->get('horario')?->options ?? new Collection,
|
||||||
'services' => $attributes->get('servicio')?->options ?? new Collection,
|
'services' => $attributes->get('servicio')?->options ?? new Collection,
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -124,7 +124,10 @@ class TicketFilterFormService
|
|||||||
'required' => false,
|
'required' => false,
|
||||||
'default' => null,
|
'default' => null,
|
||||||
'placeholder' => 'Estado',
|
'placeholder' => 'Estado',
|
||||||
'options' => Ticket::statusOptions(),
|
'options' => array_values(array_filter(
|
||||||
|
Ticket::statusOptions(),
|
||||||
|
fn (array $option): bool => $option['value'] !== Ticket::STATUS_CANCELLED,
|
||||||
|
)),
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Forms\Controllers\AdminApp\EntryFormController;
|
||||||
use App\Domains\Forms\Controllers\AdminApp\EventFormController;
|
use App\Domains\Forms\Controllers\AdminApp\EventFormController;
|
||||||
use App\Domains\Forms\Controllers\AdminApp\FoodFormController;
|
use App\Domains\Forms\Controllers\AdminApp\FoodFormController;
|
||||||
use App\Domains\Forms\Controllers\AdminApp\MerchandiseFormController;
|
use App\Domains\Forms\Controllers\AdminApp\MerchandiseFormController;
|
||||||
@@ -22,6 +23,10 @@ Route::prefix('v1/adminapp/forms')
|
|||||||
'fiesta-futbol-infantil/ticket',
|
'fiesta-futbol-infantil/ticket',
|
||||||
TicketFormController::class
|
TicketFormController::class
|
||||||
);
|
);
|
||||||
|
Route::get(
|
||||||
|
'fiesta-futbol-infantil/entry',
|
||||||
|
EntryFormController::class
|
||||||
|
);
|
||||||
Route::get(
|
Route::get(
|
||||||
'fiesta-futbol-infantil/merchandise',
|
'fiesta-futbol-infantil/merchandise',
|
||||||
MerchandiseFormController::class
|
MerchandiseFormController::class
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Notification\Listeners;
|
||||||
|
|
||||||
|
use App\Domains\Event\Events\EventDateRescheduled;
|
||||||
|
use App\Domains\Notification\Services\NotificationMailService;
|
||||||
|
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
|
||||||
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
|
|
||||||
|
class SendEventDateRescheduledEmails implements ShouldQueueAfterCommit
|
||||||
|
{
|
||||||
|
use InteractsWithQueue;
|
||||||
|
|
||||||
|
public string $queue = 'emails';
|
||||||
|
|
||||||
|
public int $tries = 3;
|
||||||
|
|
||||||
|
/** @var array<int, int> */
|
||||||
|
public array $backoff = [30, 120, 300];
|
||||||
|
|
||||||
|
public function handle(EventDateRescheduled $event): void
|
||||||
|
{
|
||||||
|
app(NotificationMailService::class)->sendEventDateRescheduled(
|
||||||
|
$event->tenantCode,
|
||||||
|
$event->sourceEventDateId,
|
||||||
|
$event->destinationEventDateId,
|
||||||
|
$event->previousDate,
|
||||||
|
$event->newDate,
|
||||||
|
$event->purchaseTickets,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Notification\Listeners;
|
||||||
|
|
||||||
|
use App\Domains\Event\Events\EventDateSuspended;
|
||||||
|
use App\Domains\Notification\Services\NotificationMailService;
|
||||||
|
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
|
||||||
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
|
|
||||||
|
class SendEventDateSuspendedEmails implements ShouldQueueAfterCommit
|
||||||
|
{
|
||||||
|
use InteractsWithQueue;
|
||||||
|
|
||||||
|
public string $queue = 'emails';
|
||||||
|
|
||||||
|
public int $tries = 3;
|
||||||
|
|
||||||
|
/** @var array<int, int> */
|
||||||
|
public array $backoff = [30, 120, 300];
|
||||||
|
|
||||||
|
public function handle(EventDateSuspended $event): void
|
||||||
|
{
|
||||||
|
app(NotificationMailService::class)->sendEventDateSuspended(
|
||||||
|
$event->tenantCode,
|
||||||
|
$event->eventDateId,
|
||||||
|
$event->date,
|
||||||
|
$event->purchaseTickets,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
44
app/Domains/Notification/Models/EmailDelivery.php
Normal file
44
app/Domains/Notification/Models/EmailDelivery.php
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Notification\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'idempotency_key',
|
||||||
|
'email_type',
|
||||||
|
'tenant_code',
|
||||||
|
'status',
|
||||||
|
'attempts',
|
||||||
|
'context',
|
||||||
|
'recipient_fingerprint',
|
||||||
|
'claim_token',
|
||||||
|
'claimed_at',
|
||||||
|
'lease_expires_at',
|
||||||
|
'sent_at',
|
||||||
|
'failed_at',
|
||||||
|
'last_error',
|
||||||
|
])]
|
||||||
|
class EmailDelivery extends Model
|
||||||
|
{
|
||||||
|
public const STATUS_PENDING = 'pending';
|
||||||
|
|
||||||
|
public const STATUS_PROCESSING = 'processing';
|
||||||
|
|
||||||
|
public const STATUS_SENT = 'sent';
|
||||||
|
|
||||||
|
public const STATUS_FAILED = 'failed';
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'attempts' => 'integer',
|
||||||
|
'context' => 'array',
|
||||||
|
'claimed_at' => 'datetime',
|
||||||
|
'lease_expires_at' => 'datetime',
|
||||||
|
'sent_at' => 'datetime',
|
||||||
|
'failed_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Notification\Services;
|
||||||
|
|
||||||
|
use App\Domains\Notification\Models\EmailDelivery;
|
||||||
|
use Closure;
|
||||||
|
use Illuminate\Database\Query\Expression;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class IdempotentEmailDeliveryService
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $context
|
||||||
|
* @param Closure(): void $send
|
||||||
|
*/
|
||||||
|
public function sendOnce(
|
||||||
|
string $key,
|
||||||
|
string $type,
|
||||||
|
?string $tenantCode,
|
||||||
|
array $context,
|
||||||
|
string $recipient,
|
||||||
|
Closure $send,
|
||||||
|
): bool {
|
||||||
|
$now = now();
|
||||||
|
|
||||||
|
EmailDelivery::query()->insertOrIgnore([
|
||||||
|
'idempotency_key' => $key,
|
||||||
|
'email_type' => $type,
|
||||||
|
'tenant_code' => $tenantCode,
|
||||||
|
'status' => EmailDelivery::STATUS_PENDING,
|
||||||
|
'attempts' => 0,
|
||||||
|
'context' => json_encode($context, JSON_THROW_ON_ERROR),
|
||||||
|
'recipient_fingerprint' => $this->recipientFingerprint($recipient),
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$claimToken = (string) Str::uuid();
|
||||||
|
$leaseExpiresAt = $now->copy()->addSeconds(
|
||||||
|
max(1, (int) config('mail.delivery_lease_seconds', 300)),
|
||||||
|
);
|
||||||
|
|
||||||
|
$claimed = EmailDelivery::query()
|
||||||
|
->where('idempotency_key', $key)
|
||||||
|
->where(function ($query) use ($now): void {
|
||||||
|
$query->whereIn('status', [
|
||||||
|
EmailDelivery::STATUS_PENDING,
|
||||||
|
EmailDelivery::STATUS_FAILED,
|
||||||
|
])->orWhere(function ($query) use ($now): void {
|
||||||
|
$query->where('status', EmailDelivery::STATUS_PROCESSING)
|
||||||
|
->where('lease_expires_at', '<=', $now);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->update([
|
||||||
|
'status' => EmailDelivery::STATUS_PROCESSING,
|
||||||
|
'attempts' => new Expression('attempts + 1'),
|
||||||
|
'context' => json_encode($context, JSON_THROW_ON_ERROR),
|
||||||
|
'recipient_fingerprint' => $this->recipientFingerprint($recipient),
|
||||||
|
'claim_token' => $claimToken,
|
||||||
|
'claimed_at' => $now,
|
||||||
|
'lease_expires_at' => $leaseExpiresAt,
|
||||||
|
'failed_at' => null,
|
||||||
|
'last_error' => null,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]) === 1;
|
||||||
|
|
||||||
|
if (! $claimed) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$send();
|
||||||
|
|
||||||
|
EmailDelivery::query()
|
||||||
|
->where('idempotency_key', $key)
|
||||||
|
->where('claim_token', $claimToken)
|
||||||
|
->update([
|
||||||
|
'status' => EmailDelivery::STATUS_SENT,
|
||||||
|
'claim_token' => null,
|
||||||
|
'lease_expires_at' => null,
|
||||||
|
'sent_at' => now(),
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
EmailDelivery::query()
|
||||||
|
->where('idempotency_key', $key)
|
||||||
|
->where('claim_token', $claimToken)
|
||||||
|
->update([
|
||||||
|
'status' => EmailDelivery::STATUS_FAILED,
|
||||||
|
'claim_token' => null,
|
||||||
|
'lease_expires_at' => null,
|
||||||
|
'failed_at' => now(),
|
||||||
|
'last_error' => Str::limit($exception::class, 2000, ''),
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
throw $exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function recipientFingerprint(string $recipient): string
|
||||||
|
{
|
||||||
|
return hash_hmac(
|
||||||
|
'sha256',
|
||||||
|
mb_strtolower(trim($recipient)),
|
||||||
|
(string) config('app.key'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ use App\Domains\Tenant\Models\Tenant;
|
|||||||
use App\Domains\Ticket\Models\Ticket;
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
use App\Domains\Ticket\Services\TicketPdfService;
|
use App\Domains\Ticket\Services\TicketPdfService;
|
||||||
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
||||||
|
use App\Domains\Ticket\Services\TicketValidityResolver;
|
||||||
use Closure;
|
use Closure;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\Log;
|
use Illuminate\Support\Facades\Log;
|
||||||
@@ -21,16 +22,25 @@ class NotificationMailService
|
|||||||
public function __construct(
|
public function __construct(
|
||||||
private readonly MailService $mailService,
|
private readonly MailService $mailService,
|
||||||
private readonly TicketPdfService $ticketPdfService,
|
private readonly TicketPdfService $ticketPdfService,
|
||||||
|
private readonly IdempotentEmailDeliveryService $emailDeliveryService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public function sendWelcome(int $userId, string $tenantCode): void
|
public function sendWelcome(int $userId, string $tenantCode): void
|
||||||
{
|
{
|
||||||
$this->sendLogged('welcome', [
|
$context = [
|
||||||
'user_id' => $userId,
|
'user_id' => $userId,
|
||||||
'tenant_code' => $tenantCode,
|
'tenant_code' => $tenantCode,
|
||||||
], function () use ($userId, $tenantCode): array {
|
];
|
||||||
$tenant = Tenant::query()->with('websiteType')->where('codigo', $tenantCode)->firstOrFail();
|
$tenant = Tenant::query()->with('websiteType')->where('codigo', $tenantCode)->firstOrFail();
|
||||||
$user = User::query()->findOrFail($userId);
|
$user = User::query()->findOrFail($userId);
|
||||||
|
|
||||||
|
$this->sendIdempotently(
|
||||||
|
"welcome:{$tenantCode}:{$userId}",
|
||||||
|
'welcome',
|
||||||
|
$tenantCode,
|
||||||
|
$context,
|
||||||
|
$user->email,
|
||||||
|
function () use ($user, $tenant, $tenantCode): array {
|
||||||
$brand = $tenant->websiteType ?? $tenant;
|
$brand = $tenant->websiteType ?? $tenant;
|
||||||
$tenantUrl = 'https://'.$tenant->dominio.$tenant->base_path;
|
$tenantUrl = 'https://'.$tenant->dominio.$tenant->base_path;
|
||||||
|
|
||||||
@@ -46,7 +56,8 @@ class NotificationMailService
|
|||||||
return [
|
return [
|
||||||
'brand_type' => $tenant->websiteType === null ? 'tenant' : 'website_type',
|
'brand_type' => $tenant->websiteType === null ? 'tenant' : 'website_type',
|
||||||
];
|
];
|
||||||
});
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function sendPasswordResetCode(
|
public function sendPasswordResetCode(
|
||||||
@@ -60,7 +71,6 @@ class NotificationMailService
|
|||||||
'channel' => $channel,
|
'channel' => $channel,
|
||||||
];
|
];
|
||||||
|
|
||||||
$this->sendLogged('password_reset', $context, function () use ($attemptId, $tenantCode, $channel, $context): ?array {
|
|
||||||
$tenant = Tenant::query()
|
$tenant = Tenant::query()
|
||||||
->with('websiteType')
|
->with('websiteType')
|
||||||
->where('codigo', $tenantCode)
|
->where('codigo', $tenantCode)
|
||||||
@@ -76,9 +86,16 @@ class NotificationMailService
|
|||||||
'user_id' => $attempt->user_id,
|
'user_id' => $attempt->user_id,
|
||||||
]));
|
]));
|
||||||
|
|
||||||
return null;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$this->sendIdempotently(
|
||||||
|
"password-reset:{$attemptId}",
|
||||||
|
'password_reset',
|
||||||
|
$tenantCode,
|
||||||
|
$context,
|
||||||
|
$attempt->user->email,
|
||||||
|
function () use ($attempt, $tenant, $tenantCode, $channel): array {
|
||||||
$recoveryDomain = match ($channel) {
|
$recoveryDomain = match ($channel) {
|
||||||
PasswordResetRequested::CHANNEL_ADMINAPP => $tenant->websiteType?->dominio,
|
PasswordResetRequested::CHANNEL_ADMINAPP => $tenant->websiteType?->dominio,
|
||||||
PasswordResetRequested::CHANNEL_SCANNER => $tenant->websiteType?->scanner_domain,
|
PasswordResetRequested::CHANNEL_SCANNER => $tenant->websiteType?->scanner_domain,
|
||||||
@@ -130,14 +147,14 @@ class NotificationMailService
|
|||||||
'user_id' => $attempt->user_id,
|
'user_id' => $attempt->user_id,
|
||||||
'recovery_domain_available' => $recoveryDomain !== null,
|
'recovery_domain_available' => $recoveryDomain !== null,
|
||||||
];
|
];
|
||||||
});
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function sendPurchaseConfirmed(int $purchaseId): void
|
public function sendPurchaseConfirmed(int $purchaseId): void
|
||||||
{
|
{
|
||||||
$context = ['purchase_id' => $purchaseId];
|
$context = ['purchase_id' => $purchaseId];
|
||||||
|
|
||||||
$this->sendLogged('purchase_confirmed', $context, function () use ($purchaseId, $context): ?array {
|
|
||||||
$purchase = Purchase::query()
|
$purchase = Purchase::query()
|
||||||
->with(['tenant', 'user', 'items'])
|
->with(['tenant', 'user', 'items'])
|
||||||
->find($purchaseId);
|
->find($purchaseId);
|
||||||
@@ -148,9 +165,23 @@ class NotificationMailService
|
|||||||
'missing_model' => Purchase::class,
|
'missing_model' => Purchase::class,
|
||||||
]));
|
]));
|
||||||
|
|
||||||
return null;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$recipient = $this->recipientFor($purchase);
|
||||||
|
if ($recipient === '') {
|
||||||
|
$this->logSkipped('purchase_confirmed', array_merge($context, ['reason' => 'missing_recipient']));
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->sendIdempotently(
|
||||||
|
"purchase-confirmed:{$purchaseId}",
|
||||||
|
'purchase_confirmed',
|
||||||
|
$purchase->tenant_codigo,
|
||||||
|
$context,
|
||||||
|
$recipient,
|
||||||
|
function () use ($purchase, $recipient): array {
|
||||||
/** @var Collection<int, Ticket> $tickets */
|
/** @var Collection<int, Ticket> $tickets */
|
||||||
$tickets = $purchase->tickets()
|
$tickets = $purchase->tickets()
|
||||||
->where('tenant_code', $purchase->tenant_codigo)
|
->where('tenant_code', $purchase->tenant_codigo)
|
||||||
@@ -167,7 +198,7 @@ class NotificationMailService
|
|||||||
$this->mailService
|
$this->mailService
|
||||||
->forTenant($purchase->tenant_codigo)
|
->forTenant($purchase->tenant_codigo)
|
||||||
->send(
|
->send(
|
||||||
$this->recipientFor($purchase),
|
$recipient,
|
||||||
"Compra confirmada - Compra #{$purchase->getKey()}",
|
"Compra confirmada - Compra #{$purchase->getKey()}",
|
||||||
view('mail.notifications.purchase-confirmed', compact('purchase', 'tickets'))->render(),
|
view('mail.notifications.purchase-confirmed', compact('purchase', 'tickets'))->render(),
|
||||||
attachments: $attachments,
|
attachments: $attachments,
|
||||||
@@ -181,7 +212,215 @@ class NotificationMailService
|
|||||||
'ticket_count' => $tickets->count(),
|
'ticket_count' => $tickets->count(),
|
||||||
'ticket_ids' => $tickets->modelKeys(),
|
'ticket_ids' => $tickets->modelKeys(),
|
||||||
];
|
];
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<array{purchase_id: int, ticket_ids: list<int>}> $purchaseTickets
|
||||||
|
*/
|
||||||
|
public function sendEventDateRescheduled(
|
||||||
|
string $tenantCode,
|
||||||
|
int $sourceEventDateId,
|
||||||
|
int $destinationEventDateId,
|
||||||
|
string $previousDate,
|
||||||
|
string $newDate,
|
||||||
|
array $purchaseTickets,
|
||||||
|
): void {
|
||||||
|
foreach ($purchaseTickets as $purchaseTicketGroup) {
|
||||||
|
$purchaseId = $purchaseTicketGroup['purchase_id'];
|
||||||
|
$ticketIds = $purchaseTicketGroup['ticket_ids'];
|
||||||
|
$context = [
|
||||||
|
'tenant_code' => $tenantCode,
|
||||||
|
'event_date_id' => $sourceEventDateId,
|
||||||
|
'destination_event_date_id' => $destinationEventDateId,
|
||||||
|
'purchase_id' => $purchaseId,
|
||||||
|
'ticket_ids' => $ticketIds,
|
||||||
|
];
|
||||||
|
$purchase = $this->eventDateNotificationPurchase($tenantCode, $purchaseId);
|
||||||
|
|
||||||
|
if ($purchase === null || $purchase->status !== Purchase::STATUS_PAID) {
|
||||||
|
$this->logSkipped('event_date_rescheduled', array_merge($context, [
|
||||||
|
'reason' => 'purchase_not_paid_or_not_found',
|
||||||
|
]));
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var Collection<int, Ticket> $tickets */
|
||||||
|
$tickets = $purchase->tickets()
|
||||||
|
->where('tenant_code', $tenantCode)
|
||||||
|
->whereKey($ticketIds)
|
||||||
|
->with([
|
||||||
|
...TicketPresentationResolver::RELATIONS,
|
||||||
|
...TicketValidityResolver::RELATIONS,
|
||||||
|
])
|
||||||
|
->get()
|
||||||
|
->filter(fn (Ticket $ticket): bool => $ticket->is_active())
|
||||||
|
->values();
|
||||||
|
|
||||||
|
if ($tickets->isEmpty()) {
|
||||||
|
$this->logSkipped('event_date_rescheduled', array_merge($context, [
|
||||||
|
'reason' => 'no_longer_active_tickets',
|
||||||
|
]));
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$recipient = $this->recipientFor($purchase);
|
||||||
|
if ($recipient === '') {
|
||||||
|
$this->logSkipped('event_date_rescheduled', array_merge($context, [
|
||||||
|
'reason' => 'missing_recipient',
|
||||||
|
]));
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$deliveryKey = "event-date-rescheduled:{$sourceEventDateId}:{$destinationEventDateId}:{$purchaseId}";
|
||||||
|
$this->sendIdempotently(
|
||||||
|
$deliveryKey,
|
||||||
|
'event_date_rescheduled',
|
||||||
|
$tenantCode,
|
||||||
|
$context,
|
||||||
|
$recipient,
|
||||||
|
function () use (
|
||||||
|
$tenantCode,
|
||||||
|
$purchase,
|
||||||
|
$recipient,
|
||||||
|
$previousDate,
|
||||||
|
$newDate,
|
||||||
|
$tickets,
|
||||||
|
): array {
|
||||||
|
$brand = $purchase->tenant->websiteType ?? $purchase->tenant;
|
||||||
|
|
||||||
|
$this->mailService
|
||||||
|
->forTenant($tenantCode)
|
||||||
|
->send(
|
||||||
|
$recipient,
|
||||||
|
"Tu evento fue reprogramado - N° de Orden #{$purchase->getKey()}",
|
||||||
|
view('mail.notifications.event-date-rescheduled', compact(
|
||||||
|
'purchase', 'previousDate', 'newDate', 'tickets'
|
||||||
|
))->render(),
|
||||||
|
$brand,
|
||||||
|
);
|
||||||
|
|
||||||
|
return ['ticket_count' => $tickets->count()];
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<array{purchase_id: int, ticket_ids: list<int>}> $purchaseTickets
|
||||||
|
*/
|
||||||
|
public function sendEventDateSuspended(
|
||||||
|
string $tenantCode,
|
||||||
|
int $eventDateId,
|
||||||
|
string $date,
|
||||||
|
array $purchaseTickets,
|
||||||
|
): void {
|
||||||
|
foreach ($purchaseTickets as $purchaseTicketGroup) {
|
||||||
|
$purchaseId = $purchaseTicketGroup['purchase_id'];
|
||||||
|
$ticketIds = $purchaseTicketGroup['ticket_ids'];
|
||||||
|
$context = [
|
||||||
|
'tenant_code' => $tenantCode,
|
||||||
|
'event_date_id' => $eventDateId,
|
||||||
|
'purchase_id' => $purchaseId,
|
||||||
|
'ticket_ids' => $ticketIds,
|
||||||
|
];
|
||||||
|
$purchase = $this->eventDateNotificationPurchase($tenantCode, $purchaseId);
|
||||||
|
|
||||||
|
if ($purchase === null || $purchase->status !== Purchase::STATUS_PAID) {
|
||||||
|
$this->logSkipped('event_date_suspended', array_merge($context, [
|
||||||
|
'reason' => 'purchase_not_paid_or_not_found',
|
||||||
|
]));
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var Collection<int, Ticket> $tickets */
|
||||||
|
$tickets = $purchase->tickets()
|
||||||
|
->where('tenant_code', $tenantCode)
|
||||||
|
->whereKey($ticketIds)
|
||||||
|
->with([
|
||||||
|
...TicketPresentationResolver::RELATIONS,
|
||||||
|
...TicketValidityResolver::RELATIONS,
|
||||||
|
])
|
||||||
|
->get()
|
||||||
|
->filter(fn (Ticket $ticket): bool => in_array($ticket->status, [
|
||||||
|
Ticket::STATUS_ACTIVE,
|
||||||
|
Ticket::STATUS_DISABLED,
|
||||||
|
], true))
|
||||||
|
->values();
|
||||||
|
|
||||||
|
if ($tickets->isEmpty()) {
|
||||||
|
$this->logSkipped('event_date_suspended', array_merge($context, [
|
||||||
|
'reason' => 'no_longer_relevant_tickets',
|
||||||
|
]));
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$recipient = $this->recipientFor($purchase);
|
||||||
|
if ($recipient === '') {
|
||||||
|
$this->logSkipped('event_date_suspended', array_merge($context, [
|
||||||
|
'reason' => 'missing_recipient',
|
||||||
|
]));
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$deliveryKey = "event-date-suspended:{$eventDateId}:{$purchaseId}";
|
||||||
|
$disabledTickets = $tickets
|
||||||
|
->filter(fn (Ticket $ticket): bool => $ticket->status === Ticket::STATUS_DISABLED)
|
||||||
|
->values();
|
||||||
|
$activeTickets = $tickets
|
||||||
|
->filter(fn (Ticket $ticket): bool => $ticket->status === Ticket::STATUS_ACTIVE)
|
||||||
|
->values();
|
||||||
|
|
||||||
|
$this->sendIdempotently(
|
||||||
|
$deliveryKey,
|
||||||
|
'event_date_suspended',
|
||||||
|
$tenantCode,
|
||||||
|
$context,
|
||||||
|
$recipient,
|
||||||
|
function () use (
|
||||||
|
$tenantCode,
|
||||||
|
$purchase,
|
||||||
|
$recipient,
|
||||||
|
$date,
|
||||||
|
$disabledTickets,
|
||||||
|
$activeTickets,
|
||||||
|
): array {
|
||||||
|
$brand = $purchase->tenant->websiteType ?? $purchase->tenant;
|
||||||
|
|
||||||
|
$this->mailService
|
||||||
|
->forTenant($tenantCode)
|
||||||
|
->send(
|
||||||
|
$recipient,
|
||||||
|
"Una fecha de tu evento fue suspendida - N° de Orden #{$purchase->getKey()}",
|
||||||
|
view('mail.notifications.event-date-suspended', compact(
|
||||||
|
'purchase', 'date', 'disabledTickets', 'activeTickets'
|
||||||
|
))->render(),
|
||||||
|
$brand,
|
||||||
|
);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'ticket_count' => $disabledTickets->count() + $activeTickets->count(),
|
||||||
|
'disabled_ticket_ids' => $disabledTickets->modelKeys(),
|
||||||
|
'active_ticket_ids' => $activeTickets->modelKeys(),
|
||||||
|
];
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function eventDateNotificationPurchase(string $tenantCode, int $purchaseId): ?Purchase
|
||||||
|
{
|
||||||
|
return Purchase::query()
|
||||||
|
->where('tenant_codigo', $tenantCode)
|
||||||
|
->with(['tenant.websiteType', 'user'])
|
||||||
|
->find($purchaseId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function recipientFor(Purchase $purchase): string
|
private function recipientFor(Purchase $purchase): string
|
||||||
@@ -189,6 +428,34 @@ class NotificationMailService
|
|||||||
return (string) ($purchase->email ?: $purchase->user?->email);
|
return (string) ($purchase->email ?: $purchase->user?->email);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $context
|
||||||
|
* @param Closure(): array<string, mixed> $send
|
||||||
|
*/
|
||||||
|
private function sendIdempotently(
|
||||||
|
string $key,
|
||||||
|
string $emailType,
|
||||||
|
?string $tenantCode,
|
||||||
|
array $context,
|
||||||
|
string $recipient,
|
||||||
|
Closure $send,
|
||||||
|
): void {
|
||||||
|
$sent = $this->emailDeliveryService->sendOnce(
|
||||||
|
$key,
|
||||||
|
$emailType,
|
||||||
|
$tenantCode,
|
||||||
|
$context,
|
||||||
|
$recipient,
|
||||||
|
function () use ($emailType, $context, $send): void {
|
||||||
|
$this->sendLogged($emailType, $context, $send);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (! $sent) {
|
||||||
|
$this->logSkipped($emailType, array_merge($context, ['reason' => 'already_claimed']));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<string, mixed> $context
|
* @param array<string, mixed> $context
|
||||||
* @param Closure(): (array<string, mixed>|null) $send
|
* @param Closure(): (array<string, mixed>|null) $send
|
||||||
|
|||||||
@@ -12,7 +12,19 @@ Orquesta notificaciones de negocio por correo a partir de eventos de otros domin
|
|||||||
|
|
||||||
## Componentes
|
## Componentes
|
||||||
|
|
||||||
Los listeners `SendWelcomeEmail`, `SendPasswordResetEmail` y `SendPurchaseConfirmedEmail` delegan en `NotificationMailService`. Este servicio carga el contexto necesario, renderiza las vistas y envía mediante `Integration/MailService`.
|
Los listeners delegan en `NotificationMailService`. Este servicio carga el contexto necesario, renderiza las vistas y envía mediante `Integration/MailService`.
|
||||||
|
|
||||||
|
`IdempotentEmailDeliveryService` coordina los envíos automáticos mediante la tabla
|
||||||
|
`email_deliveries`. Cada correo utiliza una clave de negocio única:
|
||||||
|
|
||||||
|
- bienvenida: `welcome:{tenant_code}:{user_id}`;
|
||||||
|
- recuperación: `password-reset:{attempt_id}`;
|
||||||
|
- compra confirmada: `purchase-confirmed:{purchase_id}`;
|
||||||
|
- reprogramación: `event-date-rescheduled:{source_event_date_id}:{destination_event_date_id}:{purchase_id}`;
|
||||||
|
- suspensión: `event-date-suspended:{event_date_id}:{purchase_id}`.
|
||||||
|
|
||||||
|
Los correos de prueba y de validación de una integración SMTP no usan esta capa,
|
||||||
|
porque su reenvío explícito es parte de su comportamiento esperado.
|
||||||
|
|
||||||
## API y dependencias
|
## API y dependencias
|
||||||
|
|
||||||
@@ -25,3 +37,12 @@ No expone rutas HTTP. Consume datos de `Auth`, `Tenant`, `Purchase` y `Ticket`,
|
|||||||
- Los correos de cuenta (bienvenida y recuperación de contraseña) usan la identidad visual del `WebsiteType` asociado al tenant, con fallback al tenant si no tiene uno configurado.
|
- Los correos de cuenta (bienvenida y recuperación de contraseña) usan la identidad visual del `WebsiteType` asociado al tenant, con fallback al tenant si no tiene uno configurado.
|
||||||
- El correo transaccional de compra confirmada usa la identidad visual del tenant y adjunta un único PDF cuando la compra generó tickets.
|
- El correo transaccional de compra confirmada usa la identidad visual del tenant y adjunta un único PDF cuando la compra generó tickets.
|
||||||
- Los handlers deben permanecer idempotentes o tolerantes a reintentos de cola.
|
- Los handlers deben permanecer idempotentes o tolerantes a reintentos de cola.
|
||||||
|
- Una entrega queda en estado `processing` mientras un worker posee su claim. Si
|
||||||
|
el worker se interrumpe, el claim vence según `EMAIL_DELIVERY_LEASE_SECONDS` y
|
||||||
|
otro intento puede recuperarlo.
|
||||||
|
- Los fallos quedan registrados como `failed` y pueden ser retomados por los
|
||||||
|
reintentos de la cola. Los envíos exitosos permanecen como `sent` y las llamadas
|
||||||
|
posteriores con la misma clave no vuelven a enviar el correo.
|
||||||
|
- SMTP no ofrece una confirmación transaccional junto con la base de datos. Una
|
||||||
|
interrupción ocurrida después de entregar el correo y antes de registrar
|
||||||
|
`sent` puede producir un duplicado excepcional al recuperar el claim.
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ use App\Domains\Attachable\Models\Attachment;
|
|||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
use App\Domains\Ticket\Models\Ticket;
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use App\Domains\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;
|
||||||
@@ -27,7 +28,6 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
|||||||
'discount_total',
|
'discount_total',
|
||||||
'tax_total',
|
'tax_total',
|
||||||
'total',
|
'total',
|
||||||
'refunded_amount',
|
|
||||||
])]
|
])]
|
||||||
class PurchaseItem extends Model
|
class PurchaseItem extends Model
|
||||||
{
|
{
|
||||||
@@ -48,7 +48,6 @@ class PurchaseItem extends Model
|
|||||||
'discount_total' => 'decimal:2',
|
'discount_total' => 'decimal:2',
|
||||||
'tax_total' => 'decimal:2',
|
'tax_total' => 'decimal:2',
|
||||||
'total' => 'decimal:2',
|
'total' => 'decimal:2',
|
||||||
'refunded_amount' => 'decimal:2',
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,6 +65,12 @@ class PurchaseItem extends Model
|
|||||||
return $this->hasMany(Ticket::class, 'source_purchase_item_id');
|
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
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ class PurchaseItemResource extends JsonResource
|
|||||||
'quantity' => (int) $this->cantidad,
|
'quantity' => (int) $this->cantidad,
|
||||||
'unit_price' => $this->formatMoney($this->precio_unitario),
|
'unit_price' => $this->formatMoney($this->precio_unitario),
|
||||||
'line_total' => $this->formatMoney($this->total),
|
'line_total' => $this->formatMoney($this->total),
|
||||||
'refunded_amount' => $this->formatMoney($this->refunded_amount),
|
|
||||||
'source_catalog_item_id' => $this->source_catalog_item_id,
|
'source_catalog_item_id' => $this->source_catalog_item_id,
|
||||||
'source_variant_id' => $this->source_variant_id,
|
'source_variant_id' => $this->source_variant_id,
|
||||||
'item_details' => [
|
'item_details' => [
|
||||||
|
|||||||
@@ -41,6 +41,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 +81,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',
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Domains\Purchase\Services\Checkout;
|
namespace App\Domains\Purchase\Services\Checkout;
|
||||||
|
|
||||||
use App\Domains\Cart\Models\Cart;
|
use App\Domains\Cart\Models\Cart;
|
||||||
|
use App\Domains\Cart\Models\CartItem;
|
||||||
use App\Domains\Catalog\Models\StockReservation;
|
use App\Domains\Catalog\Models\StockReservation;
|
||||||
use App\Domains\Catalog\Services\StockReservationService;
|
use App\Domains\Catalog\Services\StockReservationService;
|
||||||
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
||||||
@@ -91,7 +92,16 @@ class ReleaseCheckoutService
|
|||||||
Purchase::STATUS_CREATED,
|
Purchase::STATUS_CREATED,
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
], true)) {
|
], 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);
|
$this->reservations->returnToCart($purchase, $cart);
|
||||||
|
}
|
||||||
$purchase->update(['status' => Purchase::STATUS_CANCELLED]);
|
$purchase->update(['status' => Purchase::STATUS_CANCELLED]);
|
||||||
|
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
@@ -115,6 +125,17 @@ class ReleaseCheckoutService
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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(
|
private function releasePurchaseReservations(
|
||||||
Purchase $purchase,
|
Purchase $purchase,
|
||||||
string $targetStatus,
|
string $targetStatus,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace App\Domains\Purchase\Services\Checkout;
|
|||||||
|
|
||||||
use App\Domains\Cart\Models\Cart;
|
use App\Domains\Cart\Models\Cart;
|
||||||
use App\Domains\Cart\Models\CartItem;
|
use App\Domains\Cart\Models\CartItem;
|
||||||
|
use App\Domains\Cart\Services\CartVariantReplacementService;
|
||||||
use App\Domains\Catalog\Exceptions\StockReservationExpiredException;
|
use App\Domains\Catalog\Exceptions\StockReservationExpiredException;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
@@ -29,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 */
|
||||||
@@ -250,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()) {
|
||||||
|
|||||||
@@ -2,20 +2,20 @@
|
|||||||
|
|
||||||
namespace App\Domains\Purchase\Services;
|
namespace App\Domains\Purchase\Services;
|
||||||
|
|
||||||
use App\Domains\Purchase\Models\PurchaseItem;
|
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use App\Domains\Ticket\Models\TicketRefund;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
|
||||||
class PurchaseRefundSummaryService
|
class PurchaseRefundSummaryService
|
||||||
{
|
{
|
||||||
public function totalForTenant(Tenant $tenant): string
|
public function totalForTenant(Tenant $tenant): string
|
||||||
{
|
{
|
||||||
$total = PurchaseItem::query()
|
$total = TicketRefund::query()
|
||||||
->whereHas(
|
->whereHas(
|
||||||
'purchase',
|
'purchaseItem.purchase',
|
||||||
fn (Builder $query): Builder => $query->where('tenant_codigo', $tenant->codigo)
|
fn (Builder $query): Builder => $query->where('tenant_codigo', $tenant->codigo)
|
||||||
)
|
)
|
||||||
->sum('refunded_amount');
|
->sum('amount');
|
||||||
|
|
||||||
return number_format((float) $total, 2, '.', '');
|
return number_format((float) $total, 2, '.', '');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ class SaleDetailResource extends JsonResource
|
|||||||
'quantity' => (int) $item->cantidad,
|
'quantity' => (int) $item->cantidad,
|
||||||
'unit_price' => $this->formatMoney($item->precio_unitario),
|
'unit_price' => $this->formatMoney($item->precio_unitario),
|
||||||
'total' => $this->formatMoney($item->total),
|
'total' => $this->formatMoney($item->total),
|
||||||
'refunded_amount' => $this->formatMoney($item->refunded_amount),
|
|
||||||
])->values(),
|
])->values(),
|
||||||
'total' => $this->formatMoney($this->total),
|
'total' => $this->formatMoney($this->total),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ class AdminAppSaleService
|
|||||||
{
|
{
|
||||||
return $this->findForTenant($tenant, $saleId)
|
return $this->findForTenant($tenant, $saleId)
|
||||||
->tickets()
|
->tickets()
|
||||||
->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS])
|
->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS, 'refund'])
|
||||||
->orderBy('id')
|
->orderBy('id')
|
||||||
->get();
|
->get();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ use App\Domains\Catalog\Models\CatalogItem;
|
|||||||
use App\Domains\Catalog\Models\Category;
|
use App\Domains\Catalog\Models\Category;
|
||||||
use App\Domains\Client\Models\Client;
|
use App\Domains\Client\Models\Client;
|
||||||
use App\Domains\Event\Models\EventDate;
|
use App\Domains\Event\Models\EventDate;
|
||||||
|
use App\Domains\Event\Models\EventDateChange;
|
||||||
use App\Domains\Menu\Models\Menu;
|
use App\Domains\Menu\Models\Menu;
|
||||||
use App\Domains\Menu\Models\TenantMenu;
|
use App\Domains\Menu\Models\TenantMenu;
|
||||||
use App\Domains\Tenant\Enums\CartEditingPolicy;
|
use App\Domains\Tenant\Enums\CartEditingPolicy;
|
||||||
@@ -229,6 +230,14 @@ class Tenant extends Model
|
|||||||
->orderBy('time_start');
|
->orderBy('time_start');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return HasMany<EventDateChange, $this> */
|
||||||
|
public function eventDateChanges(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(EventDateChange::class, 'tenant_code', 'codigo')
|
||||||
|
->orderBy('created_at')
|
||||||
|
->orderBy('id');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return HasMany<Category, $this>
|
* @return HasMany<Category, $this>
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ use App\Domains\Attachable\Models\Attachment;
|
|||||||
use App\Domains\Attachable\Models\AttachmentCrop;
|
use App\Domains\Attachable\Models\AttachmentCrop;
|
||||||
use App\Domains\Catalog\Models\Category;
|
use App\Domains\Catalog\Models\Category;
|
||||||
use App\Domains\Event\Models\EventDate;
|
use App\Domains\Event\Models\EventDate;
|
||||||
|
use App\Domains\Event\Services\EventDateInfoFormatter;
|
||||||
use App\Domains\Menu\Models\Menu;
|
use App\Domains\Menu\Models\Menu;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -23,6 +24,10 @@ class TenantResource extends JsonResource
|
|||||||
*/
|
*/
|
||||||
public function toArray(Request $request): array
|
public function toArray(Request $request): array
|
||||||
{
|
{
|
||||||
|
$eventDateChanges = $this->relationLoaded('eventDateChanges')
|
||||||
|
? $this->eventDateChanges
|
||||||
|
: collect();
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => $this->id,
|
'id' => $this->id,
|
||||||
'client_id' => $this->client_id,
|
'client_id' => $this->client_id,
|
||||||
@@ -52,14 +57,17 @@ class TenantResource extends JsonResource
|
|||||||
'title' => $this->event_title,
|
'title' => $this->event_title,
|
||||||
'location' => $this->event_location,
|
'location' => $this->event_location,
|
||||||
'dates' => $this->eventDates
|
'dates' => $this->eventDates
|
||||||
->filter(fn (EventDate $eventDate): bool => $eventDate->rescheduled_to_event_date_id === null
|
->filter(fn (EventDate $eventDate): bool => $eventDate->rescheduled_to_event_date_id === null)
|
||||||
&& $eventDate->suspended_at === null
|
|
||||||
)
|
|
||||||
->map(fn (EventDate $eventDate): array => [
|
->map(fn (EventDate $eventDate): array => [
|
||||||
'id' => $eventDate->id,
|
'id' => $eventDate->id,
|
||||||
'date' => $eventDate->date->format('Y-m-d'),
|
'date' => $eventDate->date->format('Y-m-d'),
|
||||||
'time_start' => $eventDate->time_start,
|
'time_start' => $eventDate->time_start,
|
||||||
'time_end' => $eventDate->time_end,
|
'time_end' => $eventDate->time_end,
|
||||||
|
'info_text' => app(EventDateInfoFormatter::class)->format(
|
||||||
|
$eventDate,
|
||||||
|
$eventDateChanges,
|
||||||
|
),
|
||||||
|
'isCanceled' => $eventDate->suspended_at !== null,
|
||||||
])->values(),
|
])->values(),
|
||||||
]),
|
]),
|
||||||
'extras' => $this->whenLoaded(
|
'extras' => $this->whenLoaded(
|
||||||
|
|||||||
@@ -54,7 +54,12 @@ class TicketController extends Controller
|
|||||||
$tenant = $request->user()->tenant()->firstOrFail();
|
$tenant = $request->user()->tenant()->firstOrFail();
|
||||||
|
|
||||||
return new AdminAppTicketResource(
|
return new AdminAppTicketResource(
|
||||||
$this->ticketService->refund($tenant, $ticket, $request->validated('refund_type'))
|
$this->ticketService->refund(
|
||||||
|
$tenant,
|
||||||
|
$ticket,
|
||||||
|
$request->validated('refund_type'),
|
||||||
|
$request->user(),
|
||||||
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ 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\HasOne;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
@@ -219,6 +220,12 @@ class Ticket extends Model
|
|||||||
return $this->belongsTo(PurchaseItem::class, 'source_purchase_item_id');
|
return $this->belongsTo(PurchaseItem::class, 'source_purchase_item_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return HasOne<TicketRefund, $this> */
|
||||||
|
public function refund(): HasOne
|
||||||
|
{
|
||||||
|
return $this->hasOne(TicketRefund::class);
|
||||||
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<CatalogItem, $this> */
|
/** @return BelongsTo<CatalogItem, $this> */
|
||||||
public function sourceCatalogItem(): BelongsTo
|
public function sourceCatalogItem(): BelongsTo
|
||||||
{
|
{
|
||||||
@@ -284,6 +291,14 @@ class Ticket extends Model
|
|||||||
|
|
||||||
public function getStatusLabelAttribute(): string
|
public function getStatusLabelAttribute(): string
|
||||||
{
|
{
|
||||||
|
if ($this->status === self::STATUS_REFUNDED && $this->relationLoaded('refund')) {
|
||||||
|
$refund = $this->getRelation('refund');
|
||||||
|
|
||||||
|
if ($refund instanceof TicketRefund) {
|
||||||
|
return $refund->typeLabel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return self::statusLabel($this->status);
|
return self::statusLabel($this->status);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
66
app/Domains/Ticket/Models/TicketRefund.php
Normal file
66
app/Domains/Ticket/Models/TicketRefund.php
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Models;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Purchase\Models\PurchaseItem;
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'ticket_id',
|
||||||
|
'purchase_item_id',
|
||||||
|
'created_by_user_id',
|
||||||
|
'type',
|
||||||
|
'amount',
|
||||||
|
])]
|
||||||
|
class TicketRefund extends Model
|
||||||
|
{
|
||||||
|
public const TYPE_PARTIAL = 'partial';
|
||||||
|
|
||||||
|
public const TYPE_TOTAL = 'total';
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'ticket_id' => 'integer',
|
||||||
|
'purchase_item_id' => 'integer',
|
||||||
|
'created_by_user_id' => 'integer',
|
||||||
|
'amount' => 'decimal:2',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<string> */
|
||||||
|
public static function types(): array
|
||||||
|
{
|
||||||
|
return [self::TYPE_PARTIAL, self::TYPE_TOTAL];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function typeLabel(): string
|
||||||
|
{
|
||||||
|
return match ($this->type) {
|
||||||
|
self::TYPE_PARTIAL => 'Reembolso parcial',
|
||||||
|
self::TYPE_TOTAL => 'Reembolso total',
|
||||||
|
default => 'Reembolsado',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<Ticket, $this> */
|
||||||
|
public function ticket(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Ticket::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<PurchaseItem, $this> */
|
||||||
|
public function purchaseItem(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(PurchaseItem::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<User, $this> */
|
||||||
|
public function createdBy(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class, 'created_by_user_id')->withTrashed();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domains\Ticket\Requests;
|
namespace App\Domains\Ticket\Requests;
|
||||||
|
|
||||||
|
use App\Domains\Ticket\Models\TicketRefund;
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
|
|
||||||
@@ -16,7 +17,7 @@ class AdminAppTicketRefundRequest extends FormRequest
|
|||||||
public function rules(): array
|
public function rules(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'refund_type' => ['required', 'string', Rule::in(['partial', 'total'])],
|
'refund_type' => ['required', 'string', Rule::in(TicketRefund::types())],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,13 @@ class AdminAppTicketResource extends TicketResource
|
|||||||
'is_active' => $this->resource->is_active(),
|
'is_active' => $this->resource->is_active(),
|
||||||
'can_cancel' => $this->resource->can_cancel(),
|
'can_cancel' => $this->resource->can_cancel(),
|
||||||
'can_refund' => $this->resource->can_refund(),
|
'can_refund' => $this->resource->can_refund(),
|
||||||
|
'refund' => $this->resource->refund === null ? null : [
|
||||||
|
'type' => $this->resource->refund->type,
|
||||||
|
'type_label' => $this->resource->refund->typeLabel(),
|
||||||
|
'amount' => $this->resource->refund->amount,
|
||||||
|
'created_at' => $this->resource->refund->created_at,
|
||||||
|
'created_by' => $this->resource->refund->createdBy?->nombre_apellido,
|
||||||
|
],
|
||||||
'values' => $rowService->values($this->resource, $details),
|
'values' => $rowService->values($this->resource, $details),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,12 @@ class TicketResource extends JsonResource
|
|||||||
'ticket' => $this->ticket,
|
'ticket' => $this->ticket,
|
||||||
'status' => $this->status,
|
'status' => $this->status,
|
||||||
'status_label' => $this->status_label,
|
'status_label' => $this->status_label,
|
||||||
|
'refund' => $this->whenLoaded('refund', fn (): ?array => $this->refund === null ? null : [
|
||||||
|
'type' => $this->refund->type,
|
||||||
|
'type_label' => $this->refund->typeLabel(),
|
||||||
|
'amount' => $this->refund->amount,
|
||||||
|
'created_at' => $this->refund->created_at,
|
||||||
|
]),
|
||||||
'name' => $this->name,
|
'name' => $this->name,
|
||||||
'description' => $this->description,
|
'description' => $this->description,
|
||||||
'client' => $this->user?->nombre_apellido,
|
'client' => $this->user?->nombre_apellido,
|
||||||
|
|||||||
@@ -41,7 +41,9 @@ class AdminAppTicketExcelService
|
|||||||
$row = $index + 2;
|
$row = $index + 2;
|
||||||
foreach ($columns as $columnIndex => $column) {
|
foreach ($columns as $columnIndex => $column) {
|
||||||
$coordinate = Coordinate::stringFromColumnIndex($columnIndex + 1).$row;
|
$coordinate = Coordinate::stringFromColumnIndex($columnIndex + 1).$row;
|
||||||
$value = $ticket[$column['key']] ?? null;
|
$value = $column['type'] === 'status'
|
||||||
|
? ($ticket['status_label'] ?? $ticket[$column['key']] ?? null)
|
||||||
|
: ($ticket[$column['key']] ?? null);
|
||||||
|
|
||||||
if ($column['type'] === 'currency' && $value !== null) {
|
if ($column['type'] === 'currency' && $value !== null) {
|
||||||
$sheet->setCellValue($coordinate, (float) $value);
|
$sheet->setCellValue($coordinate, (float) $value);
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Domains\Ticket\Services;
|
namespace App\Domains\Ticket\Services;
|
||||||
|
|
||||||
use App\Domains\Catalog\Models\ItemAttribute;
|
use App\Domains\Catalog\Models\ItemAttribute;
|
||||||
|
use App\Domains\Event\Models\EventDate;
|
||||||
use App\Domains\Ticket\Models\Ticket;
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
@@ -11,18 +12,19 @@ class AdminAppTicketRowService
|
|||||||
private const FIESTA_FUTBOL_INFANTIL = 'fiesta_futbol_infantil';
|
private const FIESTA_FUTBOL_INFANTIL = 'fiesta_futbol_infantil';
|
||||||
|
|
||||||
private const CATEGORY_PRESENTATIONS = [
|
private const CATEGORY_PRESENTATIONS = [
|
||||||
'alojamientos' => ['category' => 'Camping', 'product' => 'tipo_alojamiento', 'type' => null, 'date' => null, 'size' => null],
|
'alojamientos' => ['category' => 'Camping', 'product' => 'tipo_alojamiento', 'type' => null, 'size' => null],
|
||||||
'camping' => ['category' => null, 'product' => 'tipo_alojamiento', 'type' => null, 'date' => null, 'size' => null],
|
'camping' => ['category' => null, 'product' => 'tipo_alojamiento', 'type' => null, 'size' => null],
|
||||||
'entradas' => ['category' => null, 'product' => 'product', 'type' => null, 'date' => null, 'size' => null],
|
'entradas' => ['category' => null, 'product' => 'product', 'type' => null, 'size' => null],
|
||||||
'comidas' => ['category' => 'Comida', 'product' => 'horario', 'type' => 'servicio', 'date' => 'event_date', 'size' => null],
|
'comidas' => ['category' => 'Comida', 'product' => 'horario', 'type' => 'servicio', 'size' => null],
|
||||||
'comida' => ['category' => null, 'product' => 'horario', 'type' => 'servicio', 'date' => 'event_date', 'size' => null],
|
'comida' => ['category' => null, 'product' => 'horario', 'type' => 'servicio', 'size' => null],
|
||||||
'merchandising' => ['category' => null, 'product' => 'product', 'type' => 'color', 'date' => null, 'size' => 'talle'],
|
'merchandising' => ['category' => null, 'product' => 'product', 'type' => 'color', 'size' => 'talle'],
|
||||||
];
|
];
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
public function details(Ticket $ticket): array
|
public function details(Ticket $ticket): array
|
||||||
{
|
{
|
||||||
$purchaseItem = $ticket->sourcePurchaseItem;
|
$purchaseItem = $ticket->sourcePurchaseItem;
|
||||||
|
$refund = $ticket->refund;
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'source_purchase_item_id' => $ticket->source_purchase_item_id,
|
'source_purchase_item_id' => $ticket->source_purchase_item_id,
|
||||||
@@ -31,7 +33,8 @@ class AdminAppTicketRowService
|
|||||||
?? $ticket->sourceCatalogItem?->nombre
|
?? $ticket->sourceCatalogItem?->nombre
|
||||||
?? $ticket->name,
|
?? $ticket->name,
|
||||||
'amount' => $purchaseItem?->precio_unitario,
|
'amount' => $purchaseItem?->precio_unitario,
|
||||||
'refunded_amount' => $purchaseItem?->refunded_amount,
|
'refund_type' => $refund?->type,
|
||||||
|
'refund_type_label' => $refund?->typeLabel(),
|
||||||
'client' => $purchaseItem?->purchase?->nombre_apellido ?? $ticket->user?->nombre_apellido,
|
'client' => $purchaseItem?->purchase?->nombre_apellido ?? $ticket->user?->nombre_apellido,
|
||||||
'status' => $ticket->status,
|
'status' => $ticket->status,
|
||||||
'scanned_by' => $ticket->scannerUser?->nombre_apellido,
|
'scanned_by' => $ticket->scannerUser?->nombre_apellido,
|
||||||
@@ -57,6 +60,7 @@ class AdminAppTicketRowService
|
|||||||
'client' => $details['client'] ?? 'Sin nombre',
|
'client' => $details['client'] ?? 'Sin nombre',
|
||||||
'id' => $ticket->id,
|
'id' => $ticket->id,
|
||||||
'status' => $details['status'],
|
'status' => $details['status'],
|
||||||
|
'status_label' => $ticket->status_label,
|
||||||
'scanned_by' => $details['scanned_by'] ?? '-',
|
'scanned_by' => $details['scanned_by'] ?? '-',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -80,7 +84,9 @@ class AdminAppTicketRowService
|
|||||||
return $rows->map(fn (array $row): array => collect($columns)
|
return $rows->map(fn (array $row): array => collect($columns)
|
||||||
->mapWithKeys(fn (array $column): array => [
|
->mapWithKeys(fn (array $column): array => [
|
||||||
$column['key'] => $this->displayValue(
|
$column['key'] => $this->displayValue(
|
||||||
$row[$column['key']] ?? null,
|
$column['type'] === 'status'
|
||||||
|
? ($row['status_label'] ?? $row[$column['key']] ?? null)
|
||||||
|
: ($row[$column['key']] ?? null),
|
||||||
$column['type'],
|
$column['type'],
|
||||||
$timeZone,
|
$timeZone,
|
||||||
),
|
),
|
||||||
@@ -106,13 +112,14 @@ class AdminAppTicketRowService
|
|||||||
private function presentation(Ticket $ticket, array $details): array
|
private function presentation(Ticket $ticket, array $details): array
|
||||||
{
|
{
|
||||||
$sourceCategory = trim((string) ($ticket->sourceCatalogItem?->category?->nombre ?? '')) ?: '-';
|
$sourceCategory = trim((string) ($ticket->sourceCatalogItem?->category?->nombre ?? '')) ?: '-';
|
||||||
|
$effectiveDates = $this->effectiveEventDateLabels($ticket) ?: '-';
|
||||||
|
|
||||||
if ($ticket->tenant_code !== self::FIESTA_FUTBOL_INFANTIL) {
|
if ($ticket->tenant_code !== self::FIESTA_FUTBOL_INFANTIL) {
|
||||||
return [
|
return [
|
||||||
'category' => $sourceCategory,
|
'category' => $sourceCategory,
|
||||||
'product' => (string) ($details['product'] ?: $ticket->name ?: '-'),
|
'product' => (string) ($details['product'] ?: $ticket->name ?: '-'),
|
||||||
'type' => $this->allPropertyLabels($details) ?: '-',
|
'type' => $this->allPropertyLabels($details) ?: '-',
|
||||||
'date' => '-',
|
'date' => $effectiveDates,
|
||||||
'size' => '-',
|
'size' => '-',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -123,7 +130,7 @@ class AdminAppTicketRowService
|
|||||||
'category' => $sourceCategory,
|
'category' => $sourceCategory,
|
||||||
'product' => (string) ($details['product'] ?: $ticket->name ?: '-'),
|
'product' => (string) ($details['product'] ?: $ticket->name ?: '-'),
|
||||||
'type' => $this->allPropertyLabels($details) ?: '-',
|
'type' => $this->allPropertyLabels($details) ?: '-',
|
||||||
'date' => '-',
|
'date' => $effectiveDates,
|
||||||
'size' => '-',
|
'size' => '-',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -136,29 +143,30 @@ class AdminAppTicketRowService
|
|||||||
'type' => $configuration['type'] === null
|
'type' => $configuration['type'] === null
|
||||||
? '-'
|
? '-'
|
||||||
: ($this->propertyLabels($details, $configuration['type']) ?: '-'),
|
: ($this->propertyLabels($details, $configuration['type']) ?: '-'),
|
||||||
'date' => $configuration['date'] === null
|
'date' => $effectiveDates,
|
||||||
? '-'
|
|
||||||
: ($this->propertyLabels($details, $configuration['date']) ?: '-'),
|
|
||||||
'size' => $configuration['size'] === null
|
'size' => $configuration['size'] === null
|
||||||
? '-'
|
? '-'
|
||||||
: ($this->propertyLabels($details, $configuration['size']) ?: '-'),
|
: ($this->propertyLabels($details, $configuration['size']) ?: '-'),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function effectiveEventDateLabels(Ticket $ticket): string
|
||||||
|
{
|
||||||
|
return $ticket->sourceVariant?->selectedEventDates()
|
||||||
|
->map(fn (EventDate $date): ?EventDate => $date->effectiveDate())
|
||||||
|
->filter()
|
||||||
|
->unique(fn (EventDate $date): int => $date->getKey())
|
||||||
|
->sortBy(fn (EventDate $date): string => $date->date->format('Y-m-d'))
|
||||||
|
->map(fn (EventDate $date): string => $date->date->format('d/m'))
|
||||||
|
->implode(', ') ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
/** @param array<string, mixed> $details */
|
/** @param array<string, mixed> $details */
|
||||||
private function propertyLabels(array $details, string $code): string
|
private function propertyLabels(array $details, string $code): string
|
||||||
{
|
{
|
||||||
$property = collect($details['variant_properties'] ?? [])->firstWhere('code', $code);
|
$property = collect($details['variant_properties'] ?? [])->firstWhere('code', $code);
|
||||||
$labels = collect($property['values'] ?? [])->pluck('label')->filter();
|
$labels = collect($property['values'] ?? [])->pluck('label')->filter();
|
||||||
|
|
||||||
if ($code === 'event_date') {
|
|
||||||
$labels = $labels->map(function (string $label): string {
|
|
||||||
[$day, $month] = array_pad(explode('/', $label), 2, null);
|
|
||||||
|
|
||||||
return $day !== null && $month !== null ? "{$day}/{$month}" : $label;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return $labels->implode(', ');
|
return $labels->implode(', ');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,14 @@
|
|||||||
namespace App\Domains\Ticket\Services;
|
namespace App\Domains\Ticket\Services;
|
||||||
|
|
||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
|
use App\Domains\Catalog\Models\Inventory;
|
||||||
|
use App\Domains\Catalog\Models\Variant;
|
||||||
use App\Domains\Purchase\Models\PurchaseItem;
|
use App\Domains\Purchase\Models\PurchaseItem;
|
||||||
use App\Domains\Purchase\Services\PurchaseRefundSummaryService;
|
use App\Domains\Purchase\Services\PurchaseRefundSummaryService;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use App\Domains\Ticket\Models\Ticket;
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use App\Domains\Ticket\Models\TicketRefund;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Pagination\LengthAwarePaginator;
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
@@ -23,6 +27,7 @@ class AdminAppTicketService
|
|||||||
'scannerUser',
|
'scannerUser',
|
||||||
'sourceCatalogItem.category',
|
'sourceCatalogItem.category',
|
||||||
'sourcePurchaseItem.purchase',
|
'sourcePurchaseItem.purchase',
|
||||||
|
'refund.createdBy',
|
||||||
];
|
];
|
||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
@@ -140,7 +145,7 @@ class AdminAppTicketService
|
|||||||
|
|
||||||
$unitPrice = (float) $purchaseItem->precio_unitario;
|
$unitPrice = (float) $purchaseItem->precio_unitario;
|
||||||
$itemTotal = (float) $purchaseItem->total;
|
$itemTotal = (float) $purchaseItem->total;
|
||||||
$itemRefundedAmount = (float) ($purchaseItem->refunded_amount ?? 0);
|
$itemRefundedAmount = $this->refundedAmountForPurchaseItem($purchaseItem);
|
||||||
$remainingItemAmount = max(0.0, round($itemTotal - $itemRefundedAmount, 2));
|
$remainingItemAmount = max(0.0, round($itemTotal - $itemRefundedAmount, 2));
|
||||||
|
|
||||||
$total = null;
|
$total = null;
|
||||||
@@ -162,11 +167,15 @@ class AdminAppTicketService
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
public function refund(Tenant $tenant, int $ticketId, string $refundType): Ticket
|
public function refund(
|
||||||
{
|
Tenant $tenant,
|
||||||
|
int $ticketId,
|
||||||
|
string $refundType,
|
||||||
|
?User $createdBy = null,
|
||||||
|
): Ticket {
|
||||||
$this->ensureRefundIsAllowed($tenant, $refundType);
|
$this->ensureRefundIsAllowed($tenant, $refundType);
|
||||||
|
|
||||||
return DB::transaction(function () use ($tenant, $ticketId, $refundType): Ticket {
|
return DB::transaction(function () use ($tenant, $ticketId, $refundType, $createdBy): Ticket {
|
||||||
$ticket = Ticket::query()
|
$ticket = Ticket::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
@@ -195,7 +204,10 @@ class AdminAppTicketService
|
|||||||
}
|
}
|
||||||
|
|
||||||
$refundAmount = $this->refundAmount($purchaseItem, $tenant, $refundType);
|
$refundAmount = $this->refundAmount($purchaseItem, $tenant, $refundType);
|
||||||
$refundedAmount = round((float) $purchaseItem->refunded_amount + $refundAmount, 2);
|
$refundedAmount = round(
|
||||||
|
$this->refundedAmountForPurchaseItem($purchaseItem) + $refundAmount,
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
|
||||||
if ($refundedAmount > (float) $purchaseItem->total) {
|
if ($refundedAmount > (float) $purchaseItem->total) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
@@ -206,19 +218,77 @@ class AdminAppTicketService
|
|||||||
$ticket->markAsRefunded();
|
$ticket->markAsRefunded();
|
||||||
$ticket->save();
|
$ticket->save();
|
||||||
|
|
||||||
$purchaseItem->update([
|
TicketRefund::query()->create([
|
||||||
'refunded_amount' => number_format($refundedAmount, 2, '.', ''),
|
'ticket_id' => $ticket->id,
|
||||||
|
'purchase_item_id' => $purchaseItem->id,
|
||||||
|
'created_by_user_id' => $createdBy?->id,
|
||||||
|
'type' => $refundType,
|
||||||
|
'amount' => number_format($refundAmount, 2, '.', ''),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
$this->restoreInventory($ticket, $purchaseItem);
|
||||||
|
|
||||||
return $ticket->refresh()->load(self::RELATIONS);
|
return $ticket->refresh()->load(self::RELATIONS);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function restoreInventory(Ticket $ticket, PurchaseItem $purchaseItem): void
|
||||||
|
{
|
||||||
|
$catalogItem = $ticket->sourceCatalogItem;
|
||||||
|
if ($catalogItem === null) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'ticket' => 'El ticket no tiene un producto con inventario reponible.',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bundle components need a per-ticket allocation before they can be restored.
|
||||||
|
if ($catalogItem->isBundle() || $purchaseItem->sourceCatalogItem?->isBundle()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$inventoryId = $catalogItem->inventory_id;
|
||||||
|
if ($ticket->source_variant_id !== null) {
|
||||||
|
$variant = Variant::withTrashed()->find($ticket->source_variant_id);
|
||||||
|
if ($variant === null) {
|
||||||
|
throw ValidationException::withMessages(['ticket' => 'No se encontró la variante del ticket.']);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A replacement can move the sellable inventory to a newer variant.
|
||||||
|
$visited = [];
|
||||||
|
while ($variant->replaced_by_variant_id !== null) {
|
||||||
|
if (isset($visited[$variant->id])) {
|
||||||
|
throw new \LogicException('La cadena de reemplazos de variantes es circular.');
|
||||||
|
}
|
||||||
|
$visited[$variant->id] = true;
|
||||||
|
$variant = Variant::withTrashed()->findOrFail($variant->replaced_by_variant_id);
|
||||||
|
}
|
||||||
|
$inventoryId = $variant->inventory_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
$inventory = Inventory::query()->lockForUpdate()->find($inventoryId);
|
||||||
|
if ($inventory === null) {
|
||||||
|
throw ValidationException::withMessages(['ticket' => 'No se encontró el inventario del ticket.']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($catalogItem->inventory_policy === InventoryPolicy::Tracked) {
|
||||||
|
$inventory->real_stock++;
|
||||||
|
}
|
||||||
|
$inventory->refunded_units++;
|
||||||
|
$inventory->save();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function refundedAmountForPurchaseItem(PurchaseItem $purchaseItem): float
|
||||||
|
{
|
||||||
|
return round((float) TicketRefund::query()
|
||||||
|
->where('purchase_item_id', $purchaseItem->id)
|
||||||
|
->sum('amount'), 2);
|
||||||
|
}
|
||||||
|
|
||||||
private function ensureRefundIsAllowed(Tenant $tenant, string $refundType): void
|
private function ensureRefundIsAllowed(Tenant $tenant, string $refundType): void
|
||||||
{
|
{
|
||||||
$isAllowed = match ($refundType) {
|
$isAllowed = match ($refundType) {
|
||||||
'partial' => $tenant->allow_refund() && $tenant->allow_partial_refund(),
|
TicketRefund::TYPE_PARTIAL => $tenant->allow_refund() && $tenant->allow_partial_refund(),
|
||||||
'total' => $tenant->allow_refund() && (bool) $tenant->allow_ticket_total_refund,
|
TicketRefund::TYPE_TOTAL => $tenant->allow_refund() && (bool) $tenant->allow_ticket_total_refund,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (! $isAllowed) {
|
if (! $isAllowed) {
|
||||||
@@ -233,8 +303,8 @@ class AdminAppTicketService
|
|||||||
$ticketAmount = (float) $purchaseItem->precio_unitario;
|
$ticketAmount = (float) $purchaseItem->precio_unitario;
|
||||||
|
|
||||||
return match ($refundType) {
|
return match ($refundType) {
|
||||||
'partial' => round($ticketAmount * (float) $tenant->ticket_partial_refund_percentage / 100, 2),
|
TicketRefund::TYPE_PARTIAL => round($ticketAmount * (float) $tenant->ticket_partial_refund_percentage / 100, 2),
|
||||||
'total' => $ticketAmount,
|
TicketRefund::TYPE_TOTAL => $ticketAmount,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
121
app/Domains/Ticket/Services/BackfillRefundedUnitsService.php
Normal file
121
app/Domains/Ticket/Services/BackfillRefundedUnitsService.php
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Services;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class BackfillRefundedUnitsService
|
||||||
|
{
|
||||||
|
/** @return array<string, int> */
|
||||||
|
public function run(): array
|
||||||
|
{
|
||||||
|
$summary = DB::transaction(function (): array {
|
||||||
|
if (DB::table('inventories')->where('refunded_units', '>', 0)->exists()) {
|
||||||
|
throw new RuntimeException('El backfill requiere que refunded_units sea cero en todos los inventarios.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$counts = [];
|
||||||
|
$variants = [];
|
||||||
|
$refundsSeen = 0;
|
||||||
|
$bundlesSkipped = 0;
|
||||||
|
|
||||||
|
DB::table('ticket_refunds as refunds')
|
||||||
|
->join('tickets', 'tickets.id', '=', 'refunds.ticket_id')
|
||||||
|
->join('compra_items as purchase_items', 'purchase_items.id', '=', 'refunds.purchase_item_id')
|
||||||
|
->leftJoin('catalog_items as purchase_catalog', 'purchase_catalog.id', '=', 'purchase_items.source_catalog_item_id')
|
||||||
|
->leftJoin('catalog_items as ticket_catalog', 'ticket_catalog.id', '=', 'tickets.source_catalog_item_id')
|
||||||
|
->select([
|
||||||
|
'refunds.id',
|
||||||
|
'refunds.ticket_id',
|
||||||
|
'tickets.source_variant_id',
|
||||||
|
'ticket_catalog.inventory_id',
|
||||||
|
'ticket_catalog.inventory_policy',
|
||||||
|
'ticket_catalog.type as ticket_catalog_type',
|
||||||
|
'purchase_catalog.type as purchase_catalog_type',
|
||||||
|
])
|
||||||
|
->chunkById(500, function ($refunds) use (&$counts, &$variants, &$refundsSeen, &$bundlesSkipped): void {
|
||||||
|
foreach ($refunds as $refund) {
|
||||||
|
$refundsSeen++;
|
||||||
|
if ($refund->ticket_catalog_type === 'bundle' || $refund->purchase_catalog_type === 'bundle') {
|
||||||
|
$bundlesSkipped++;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($refund->inventory_policy === null) {
|
||||||
|
throw new RuntimeException("El reembolso {$refund->id} no tiene un producto de catálogo asociado.");
|
||||||
|
}
|
||||||
|
|
||||||
|
$inventoryId = $refund->source_variant_id === null
|
||||||
|
? $refund->inventory_id
|
||||||
|
: $this->currentVariantInventoryId((int) $refund->source_variant_id, $variants);
|
||||||
|
|
||||||
|
if ($inventoryId === null) {
|
||||||
|
throw new RuntimeException("El reembolso {$refund->id} no tiene un inventario asociado.");
|
||||||
|
}
|
||||||
|
|
||||||
|
$counts[$inventoryId]['refunded'] = ($counts[$inventoryId]['refunded'] ?? 0) + 1;
|
||||||
|
if ($refund->inventory_policy === 'tracked') {
|
||||||
|
$counts[$inventoryId]['stock'] = ($counts[$inventoryId]['stock'] ?? 0) + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 'refunds.id', 'id');
|
||||||
|
|
||||||
|
foreach ($counts as $inventoryId => $count) {
|
||||||
|
$updates = ['refunded_units' => DB::raw('refunded_units + '.$count['refunded'])];
|
||||||
|
if (($count['stock'] ?? 0) > 0) {
|
||||||
|
$updates['real_stock'] = DB::raw('real_stock + '.$count['stock']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (DB::table('inventories')->where('id', $inventoryId)->update($updates) !== 1) {
|
||||||
|
throw new RuntimeException("No se encontró el inventario {$inventoryId} para reponerlo.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$refundedUnitsAdded = array_sum(array_column($counts, 'refunded'));
|
||||||
|
|
||||||
|
return [
|
||||||
|
'refunds_seen' => $refundsSeen,
|
||||||
|
'refunds_applied' => $refundedUnitsAdded,
|
||||||
|
'bundles_skipped' => $bundlesSkipped,
|
||||||
|
'inventories_updated' => count($counts),
|
||||||
|
'refunded_units_added' => $refundedUnitsAdded,
|
||||||
|
'real_stock_added' => array_sum(array_column($counts, 'stock')),
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
Log::info('inventory.refunded_units_backfill.completed', $summary);
|
||||||
|
|
||||||
|
return $summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<int, object|null> $variants */
|
||||||
|
private function currentVariantInventoryId(int $variantId, array &$variants): ?int
|
||||||
|
{
|
||||||
|
$visited = [];
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
if (isset($visited[$variantId])) {
|
||||||
|
throw new RuntimeException("La cadena de reemplazos de la variante {$variantId} es circular.");
|
||||||
|
}
|
||||||
|
$visited[$variantId] = true;
|
||||||
|
|
||||||
|
if (! array_key_exists($variantId, $variants)) {
|
||||||
|
$variants[$variantId] = DB::table('variantes')
|
||||||
|
->where('id', $variantId)
|
||||||
|
->first(['inventory_id', 'replaced_by_variant_id']);
|
||||||
|
}
|
||||||
|
$variant = $variants[$variantId];
|
||||||
|
if ($variant === null) {
|
||||||
|
throw new RuntimeException("No se encontró la variante {$variantId} de un ticket reembolsado.");
|
||||||
|
}
|
||||||
|
if ($variant->replaced_by_variant_id === null) {
|
||||||
|
return $variant->inventory_id === null ? null : (int) $variant->inventory_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
$variantId = (int) $variant->replaced_by_variant_id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,10 +2,14 @@
|
|||||||
|
|
||||||
namespace App\Domains\Ticket\Services;
|
namespace App\Domains\Ticket\Services;
|
||||||
|
|
||||||
|
use App\Domains\Event\Models\EventDate;
|
||||||
|
use App\Domains\Event\Services\EffectiveEventDateResolver;
|
||||||
use App\Domains\Ticket\Models\Ticket;
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
|
||||||
class TicketPresentationResolver
|
class TicketPresentationResolver
|
||||||
{
|
{
|
||||||
|
public function __construct(private readonly EffectiveEventDateResolver $effectiveEventDateResolver) {}
|
||||||
|
|
||||||
/** Relaciones necesarias para calcular nombre y descripción sin consultas N+1. */
|
/** Relaciones necesarias para calcular nombre y descripción sin consultas N+1. */
|
||||||
public const RELATIONS = [
|
public const RELATIONS = [
|
||||||
'sourceCatalogItem',
|
'sourceCatalogItem',
|
||||||
@@ -30,9 +34,15 @@ class TicketPresentationResolver
|
|||||||
}
|
}
|
||||||
|
|
||||||
$itemAttributes = $variant->catalogItem->itemAttributes;
|
$itemAttributes = $variant->catalogItem->itemAttributes;
|
||||||
|
$eventDateLabels = $variant->selectedEventDates()
|
||||||
|
->map(fn (EventDate $date): EventDate => $this->effectiveEventDateResolver->resolveLatest($date) ?? $date)
|
||||||
|
->unique(fn (EventDate $date): int => $date->getKey())
|
||||||
|
->map(fn (EventDate $date): string => $date->date->format('d/m/Y'))
|
||||||
|
->implode(', ');
|
||||||
|
|
||||||
$properties = $variant->selectionOptions($itemAttributes)
|
$properties = $variant->selectionOptions($itemAttributes)
|
||||||
->map(function (array $option, string $attributeCode) use ($itemAttributes): ?string {
|
->map(function (array $option, string $attributeCode) use ($itemAttributes, $eventDateLabels): ?string {
|
||||||
$labels = collect(array_is_list($option) ? $option : [$option])
|
$labels = $attributeCode === 'event_date' ? $eventDateLabels : collect(array_is_list($option) ? $option : [$option])
|
||||||
->pluck('label')
|
->pluck('label')
|
||||||
->filter(fn ($label): bool => is_string($label) && $label !== '')
|
->filter(fn ($label): bool => is_string($label) && $label !== '')
|
||||||
->implode(', ');
|
->implode(', ');
|
||||||
|
|||||||
@@ -2,10 +2,14 @@
|
|||||||
|
|
||||||
namespace App\Providers;
|
namespace App\Providers;
|
||||||
|
|
||||||
|
use App\Domains\Event\Events\EventDateRescheduled;
|
||||||
|
use App\Domains\Event\Events\EventDateSuspended;
|
||||||
use App\Domains\Integration\Models\Integration;
|
use App\Domains\Integration\Models\Integration;
|
||||||
use App\Domains\Integration\Policies\IntegrationPolicy;
|
use App\Domains\Integration\Policies\IntegrationPolicy;
|
||||||
use App\Domains\Notification\Events\PasswordResetRequested;
|
use App\Domains\Notification\Events\PasswordResetRequested;
|
||||||
use App\Domains\Notification\Events\UserRegistered;
|
use App\Domains\Notification\Events\UserRegistered;
|
||||||
|
use App\Domains\Notification\Listeners\SendEventDateRescheduledEmails;
|
||||||
|
use App\Domains\Notification\Listeners\SendEventDateSuspendedEmails;
|
||||||
use App\Domains\Notification\Listeners\SendPasswordResetEmail;
|
use App\Domains\Notification\Listeners\SendPasswordResetEmail;
|
||||||
use App\Domains\Notification\Listeners\SendPurchaseConfirmedEmail;
|
use App\Domains\Notification\Listeners\SendPurchaseConfirmedEmail;
|
||||||
use App\Domains\Notification\Listeners\SendWelcomeEmail;
|
use App\Domains\Notification\Listeners\SendWelcomeEmail;
|
||||||
@@ -40,6 +44,8 @@ class AppServiceProvider extends ServiceProvider
|
|||||||
);
|
);
|
||||||
Event::listen(PurchasePaid::class, GenerateTicketsForPaidPurchase::class);
|
Event::listen(PurchasePaid::class, GenerateTicketsForPaidPurchase::class);
|
||||||
Event::listen(PurchasePaid::class, SendPurchaseConfirmedEmail::class);
|
Event::listen(PurchasePaid::class, SendPurchaseConfirmedEmail::class);
|
||||||
|
Event::listen(EventDateRescheduled::class, SendEventDateRescheduledEmails::class);
|
||||||
|
Event::listen(EventDateSuspended::class, SendEventDateSuspendedEmails::class);
|
||||||
Event::listen(UserRegistered::class, SendWelcomeEmail::class);
|
Event::listen(UserRegistered::class, SendWelcomeEmail::class);
|
||||||
Event::listen(PasswordResetRequested::class, SendPasswordResetEmail::class);
|
Event::listen(PasswordResetRequested::class, SendPasswordResetEmail::class);
|
||||||
|
|
||||||
|
|||||||
@@ -52,8 +52,7 @@
|
|||||||
"npx concurrently -c \"#93c5fd,#c4b5fd,#a7f3d0,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --queue=emails,default --tries=1 --timeout=0\" \"php artisan schedule:work\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,scheduler,logs,vite --kill-others"
|
"npx concurrently -c \"#93c5fd,#c4b5fd,#a7f3d0,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --queue=emails,default --tries=1 --timeout=0\" \"php artisan schedule:work\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,scheduler,logs,vite --kill-others"
|
||||||
],
|
],
|
||||||
"test": [
|
"test": [
|
||||||
"@php artisan config:clear --ansi @no_additional_args",
|
"@php vendor/phpunit/phpunit/phpunit"
|
||||||
"@php artisan test"
|
|
||||||
],
|
],
|
||||||
"post-autoload-dump": [
|
"post-autoload-dump": [
|
||||||
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
|
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ return [
|
|||||||
|
|
||||||
'default' => env('MAIL_MAILER', 'log'),
|
'default' => env('MAIL_MAILER', 'log'),
|
||||||
|
|
||||||
|
'delivery_lease_seconds' => (int) env('EMAIL_DELIVERY_LEASE_SECONDS', 300),
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|--------------------------------------------------------------------------
|
|--------------------------------------------------------------------------
|
||||||
| Mailer Configurations
|
| Mailer Configurations
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('email_deliveries', function (Blueprint $table): void {
|
||||||
|
$table->id();
|
||||||
|
$table->string('idempotency_key')->unique();
|
||||||
|
$table->string('email_type')->index();
|
||||||
|
$table->string('tenant_code')->nullable()->index();
|
||||||
|
$table->string('status')->index();
|
||||||
|
$table->unsignedInteger('attempts')->default(0);
|
||||||
|
$table->json('context')->nullable();
|
||||||
|
$table->string('recipient_fingerprint', 64)->nullable();
|
||||||
|
$table->uuid('claim_token')->nullable()->index();
|
||||||
|
$table->timestamp('claimed_at')->nullable();
|
||||||
|
$table->timestamp('lease_expires_at')->nullable()->index();
|
||||||
|
$table->timestamp('sent_at')->nullable();
|
||||||
|
$table->timestamp('failed_at')->nullable();
|
||||||
|
$table->text('last_error')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('email_deliveries');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('ticket_refunds', function (Blueprint $table): void {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('ticket_id')->unique()->constrained('tickets')->cascadeOnDelete();
|
||||||
|
$table->foreignId('purchase_item_id')->constrained('compra_items')->restrictOnDelete();
|
||||||
|
$table->foreignId('created_by_user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||||
|
$table->string('type', 16);
|
||||||
|
$table->decimal('amount', 10, 2);
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->index(['purchase_item_id', 'type']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('ticket_refunds');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('event_date_reschedules', function (Blueprint $table): void {
|
||||||
|
$table->id();
|
||||||
|
$table->string('tenant_code');
|
||||||
|
$table->foreignId('source_event_date_id')->nullable()->constrained('event_dates')->nullOnDelete();
|
||||||
|
$table->foreignId('destination_event_date_id')->nullable()->constrained('event_dates')->nullOnDelete();
|
||||||
|
$table->foreignId('created_by_user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||||
|
$table->date('previous_date');
|
||||||
|
$table->date('new_date');
|
||||||
|
$table->timestamp('created_at')->useCurrent();
|
||||||
|
|
||||||
|
$table->foreign('tenant_code')
|
||||||
|
->references('codigo')
|
||||||
|
->on('tenants')
|
||||||
|
->cascadeOnUpdate()
|
||||||
|
->cascadeOnDelete();
|
||||||
|
$table->index(['tenant_code', 'created_at']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('event_date_reschedules');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
$requiresForeignKeyRecreation = in_array(DB::getDriverName(), ['mysql', 'mariadb'], true);
|
||||||
|
|
||||||
|
Schema::table('variantes', function (Blueprint $table) use ($requiresForeignKeyRecreation): void {
|
||||||
|
if ($requiresForeignKeyRecreation) {
|
||||||
|
$table->dropForeign(['inventory_id']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$table->dropUnique('variantes_inventory_id_unique');
|
||||||
|
$table->index('inventory_id');
|
||||||
|
|
||||||
|
if ($requiresForeignKeyRecreation) {
|
||||||
|
$table->foreign('inventory_id')->references('id')->on('inventories')->restrictOnDelete();
|
||||||
|
}
|
||||||
|
|
||||||
|
$table->foreignId('replaced_by_variant_id')
|
||||||
|
->nullable()
|
||||||
|
->after('inventory_id')
|
||||||
|
->constrained('variantes')
|
||||||
|
->nullOnDelete();
|
||||||
|
$table->timestamp('sales_disabled_at')
|
||||||
|
->nullable()
|
||||||
|
->after('replaced_by_variant_id');
|
||||||
|
$table->index(
|
||||||
|
['sales_disabled_at', 'replaced_by_variant_id'],
|
||||||
|
'variants_sellable_index',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
$requiresForeignKeyRecreation = in_array(DB::getDriverName(), ['mysql', 'mariadb'], true);
|
||||||
|
|
||||||
|
DB::table('variantes')
|
||||||
|
->orderBy('id')
|
||||||
|
->get()
|
||||||
|
->groupBy('inventory_id')
|
||||||
|
->each(function ($variants): void {
|
||||||
|
$variants->skip(1)->each(function (object $variant): void {
|
||||||
|
$inventory = DB::table('inventories')->where('id', $variant->inventory_id)->first();
|
||||||
|
|
||||||
|
if ($inventory === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$inventoryId = DB::table('inventories')->insertGetId([
|
||||||
|
'sold_units' => $inventory->sold_units,
|
||||||
|
'reserved_stock' => 0,
|
||||||
|
'real_stock' => $inventory->real_stock,
|
||||||
|
]);
|
||||||
|
|
||||||
|
DB::table('variantes')->where('id', $variant->id)->update([
|
||||||
|
'inventory_id' => $inventoryId,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('variantes', function (Blueprint $table) use ($requiresForeignKeyRecreation): void {
|
||||||
|
$table->dropIndex('variants_sellable_index');
|
||||||
|
$table->dropConstrainedForeignId('replaced_by_variant_id');
|
||||||
|
$table->dropColumn('sales_disabled_at');
|
||||||
|
|
||||||
|
if ($requiresForeignKeyRecreation) {
|
||||||
|
$table->dropForeign(['inventory_id']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$table->dropIndex(['inventory_id']);
|
||||||
|
$table->unique('inventory_id');
|
||||||
|
|
||||||
|
if ($requiresForeignKeyRecreation) {
|
||||||
|
$table->foreign('inventory_id')->references('id')->on('inventories')->restrictOnDelete();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
$this->createEventDateChangesTable();
|
||||||
|
|
||||||
|
DB::table('event_date_changes')->insertUsing(
|
||||||
|
[
|
||||||
|
'tenant_code',
|
||||||
|
'change_type',
|
||||||
|
'source_event_date_id',
|
||||||
|
'destination_event_date_id',
|
||||||
|
'created_by_user_id',
|
||||||
|
'previous_date',
|
||||||
|
'new_date',
|
||||||
|
'created_at',
|
||||||
|
],
|
||||||
|
DB::table('event_date_reschedules')->select([
|
||||||
|
'tenant_code',
|
||||||
|
DB::raw("'rescheduled'"),
|
||||||
|
'source_event_date_id',
|
||||||
|
'destination_event_date_id',
|
||||||
|
'created_by_user_id',
|
||||||
|
'previous_date',
|
||||||
|
'new_date',
|
||||||
|
'created_at',
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
Schema::drop('event_date_reschedules');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
$this->createEventDateReschedulesTable();
|
||||||
|
|
||||||
|
DB::table('event_date_reschedules')->insertUsing(
|
||||||
|
[
|
||||||
|
'tenant_code',
|
||||||
|
'source_event_date_id',
|
||||||
|
'destination_event_date_id',
|
||||||
|
'created_by_user_id',
|
||||||
|
'previous_date',
|
||||||
|
'new_date',
|
||||||
|
'created_at',
|
||||||
|
],
|
||||||
|
DB::table('event_date_changes')
|
||||||
|
->where('change_type', 'rescheduled')
|
||||||
|
->whereNotNull('destination_event_date_id')
|
||||||
|
->whereNotNull('new_date')
|
||||||
|
->select([
|
||||||
|
'tenant_code',
|
||||||
|
'source_event_date_id',
|
||||||
|
'destination_event_date_id',
|
||||||
|
'created_by_user_id',
|
||||||
|
'previous_date',
|
||||||
|
'new_date',
|
||||||
|
'created_at',
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
Schema::drop('event_date_changes');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createEventDateChangesTable(): void
|
||||||
|
{
|
||||||
|
Schema::create('event_date_changes', function (Blueprint $table): void {
|
||||||
|
$table->id();
|
||||||
|
$table->string('tenant_code');
|
||||||
|
$table->string('change_type', 16);
|
||||||
|
$table->foreignId('source_event_date_id')->nullable()->constrained('event_dates')->nullOnDelete();
|
||||||
|
$table->foreignId('destination_event_date_id')->nullable()->constrained('event_dates')->nullOnDelete();
|
||||||
|
$table->foreignId('created_by_user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||||
|
$table->date('previous_date');
|
||||||
|
$table->date('new_date')->nullable();
|
||||||
|
$table->timestamp('created_at')->useCurrent();
|
||||||
|
|
||||||
|
$table->foreign('tenant_code')
|
||||||
|
->references('codigo')
|
||||||
|
->on('tenants')
|
||||||
|
->cascadeOnUpdate()
|
||||||
|
->cascadeOnDelete();
|
||||||
|
$table->index(['tenant_code', 'created_at']);
|
||||||
|
$table->index(['source_event_date_id', 'change_type']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createEventDateReschedulesTable(): void
|
||||||
|
{
|
||||||
|
Schema::create('event_date_reschedules', function (Blueprint $table): void {
|
||||||
|
$table->id();
|
||||||
|
$table->string('tenant_code');
|
||||||
|
$table->foreignId('source_event_date_id')->nullable()->constrained('event_dates')->nullOnDelete();
|
||||||
|
$table->foreignId('destination_event_date_id')->nullable()->constrained('event_dates')->nullOnDelete();
|
||||||
|
$table->foreignId('created_by_user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||||
|
$table->date('previous_date');
|
||||||
|
$table->date('new_date');
|
||||||
|
$table->timestamp('created_at')->useCurrent();
|
||||||
|
|
||||||
|
$table->foreign('tenant_code')
|
||||||
|
->references('codigo')
|
||||||
|
->on('tenants')
|
||||||
|
->cascadeOnUpdate()
|
||||||
|
->cascadeOnDelete();
|
||||||
|
$table->index(['tenant_code', 'created_at']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
$this->backfillLegacyRefunds();
|
||||||
|
|
||||||
|
$mismatchedItem = DB::table('compra_items as purchase_items')
|
||||||
|
->leftJoin('ticket_refunds as refunds', 'refunds.purchase_item_id', '=', 'purchase_items.id')
|
||||||
|
->where('purchase_items.refunded_amount', '>', 0)
|
||||||
|
->groupBy('purchase_items.id', 'purchase_items.refunded_amount')
|
||||||
|
->selectRaw(
|
||||||
|
'purchase_items.id, purchase_items.refunded_amount, COALESCE(SUM(refunds.amount), 0) as refund_total'
|
||||||
|
)
|
||||||
|
->get()
|
||||||
|
->first(fn (object $item): bool => abs(
|
||||||
|
(float) $item->refunded_amount - (float) $item->refund_total
|
||||||
|
) > 0.005);
|
||||||
|
|
||||||
|
if ($mismatchedItem !== null) {
|
||||||
|
throw new RuntimeException(
|
||||||
|
"No se puede eliminar compra_items.refunded_amount: el ítem {$mismatchedItem->id} "
|
||||||
|
.'contiene un importe histórico que no se pudo respaldar con ticket_refunds.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Schema::table('compra_items', function (Blueprint $table): void {
|
||||||
|
$table->dropColumn('refunded_amount');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('compra_items', function (Blueprint $table): void {
|
||||||
|
$table->decimal('refunded_amount', 10, 2)->default(0)->after('total');
|
||||||
|
});
|
||||||
|
|
||||||
|
DB::table('ticket_refunds')
|
||||||
|
->selectRaw('purchase_item_id, SUM(amount) as refund_total')
|
||||||
|
->groupBy('purchase_item_id')
|
||||||
|
->orderBy('purchase_item_id')
|
||||||
|
->eachById(function (object $refund): void {
|
||||||
|
DB::table('compra_items')
|
||||||
|
->where('id', $refund->purchase_item_id)
|
||||||
|
->update(['refunded_amount' => $refund->refund_total]);
|
||||||
|
}, column: 'purchase_item_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function backfillLegacyRefunds(): void
|
||||||
|
{
|
||||||
|
$items = DB::table('compra_items as purchase_items')
|
||||||
|
->leftJoin('ticket_refunds as refunds', 'refunds.purchase_item_id', '=', 'purchase_items.id')
|
||||||
|
->where('purchase_items.refunded_amount', '>', 0)
|
||||||
|
->groupBy(
|
||||||
|
'purchase_items.id',
|
||||||
|
'purchase_items.refunded_amount',
|
||||||
|
'purchase_items.precio_unitario',
|
||||||
|
)
|
||||||
|
->selectRaw(
|
||||||
|
'purchase_items.id, purchase_items.refunded_amount, purchase_items.precio_unitario, '
|
||||||
|
.'COALESCE(SUM(refunds.amount), 0) as refund_total'
|
||||||
|
)
|
||||||
|
->orderBy('purchase_items.id')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
foreach ($items as $item) {
|
||||||
|
$legacyAmountInCents = (int) round(
|
||||||
|
((float) $item->refunded_amount - (float) $item->refund_total) * 100
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($legacyAmountInCents <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$tickets = DB::table('tickets as tickets')
|
||||||
|
->leftJoin('ticket_refunds as refunds', 'refunds.ticket_id', '=', 'tickets.id')
|
||||||
|
->where('tickets.source_purchase_item_id', $item->id)
|
||||||
|
->whereNotNull('tickets.refunded_at')
|
||||||
|
->whereNull('refunds.id')
|
||||||
|
->orderBy('tickets.refunded_at')
|
||||||
|
->orderBy('tickets.id')
|
||||||
|
->get(['tickets.id', 'tickets.refunded_at']);
|
||||||
|
|
||||||
|
$ticketCount = $tickets->count();
|
||||||
|
$unitPriceInCents = (int) round((float) $item->precio_unitario * 100);
|
||||||
|
|
||||||
|
if ($ticketCount === 0
|
||||||
|
|| $unitPriceInCents <= 0
|
||||||
|
|| $legacyAmountInCents > $ticketCount * $unitPriceInCents) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$baseAmountInCents = intdiv($legacyAmountInCents, $ticketCount);
|
||||||
|
$remainderInCents = $legacyAmountInCents % $ticketCount;
|
||||||
|
|
||||||
|
if ($baseAmountInCents === 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$refunds = $tickets->values()->map(function (object $ticket, int $index) use (
|
||||||
|
$item,
|
||||||
|
$baseAmountInCents,
|
||||||
|
$remainderInCents,
|
||||||
|
$unitPriceInCents,
|
||||||
|
): array {
|
||||||
|
$amountInCents = $baseAmountInCents + ($index < $remainderInCents ? 1 : 0);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'ticket_id' => $ticket->id,
|
||||||
|
'purchase_item_id' => $item->id,
|
||||||
|
'created_by_user_id' => null,
|
||||||
|
'type' => $amountInCents === $unitPriceInCents ? 'total' : 'partial',
|
||||||
|
'amount' => number_format($amountInCents / 100, 2, '.', ''),
|
||||||
|
'created_at' => $ticket->refunded_at,
|
||||||
|
'updated_at' => $ticket->refunded_at,
|
||||||
|
];
|
||||||
|
})->all();
|
||||||
|
|
||||||
|
DB::table('ticket_refunds')->insert($refunds);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('user_event_date_change_views', function (Blueprint $table): void {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
|
||||||
|
$table->foreignId('event_date_change_id')->constrained('event_date_changes')->cascadeOnDelete();
|
||||||
|
$table->unsignedTinyInteger('display_count')->default(0);
|
||||||
|
$table->timestamp('last_displayed_at')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->unique(['user_id', 'event_date_change_id']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('user_event_date_change_views');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('inventories', function (Blueprint $table): void {
|
||||||
|
$table->unsignedBigInteger('refunded_units')->default(0);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('inventories', function (Blueprint $table): void {
|
||||||
|
$table->dropColumn('refunded_units');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
// Historical reconciliation runs explicitly via tickets:backfill-refunded-units.
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
// Reconciliation cannot be reversed without auditing stock.
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -34,7 +34,10 @@ return [
|
|||||||
'max_quantity' => 'You can add a maximum of :max.',
|
'max_quantity' => 'You can add a maximum of :max.',
|
||||||
'bundle_variant_forbidden' => 'A bundle cannot have a variant.',
|
'bundle_variant_forbidden' => 'A bundle cannot have a variant.',
|
||||||
'empty_bundle' => 'The bundle has no components.',
|
'empty_bundle' => 'The bundle has no components.',
|
||||||
|
'bundle_component_unavailable' => 'The bundle contains a variant that is no longer available for sale.',
|
||||||
'variant_required' => 'You must select a variant for this item.',
|
'variant_required' => 'You must select a variant for this item.',
|
||||||
|
'variant_unavailable' => 'The selected variant was replaced or is no longer available for sale.',
|
||||||
|
'cart_variant_unavailable' => 'The cart contains a replaced variant or one that is no longer available for sale.',
|
||||||
'reservation_expired' => 'The stock reservation has expired. Use the active cart to continue.',
|
'reservation_expired' => 'The stock reservation has expired. Use the active cart to continue.',
|
||||||
],
|
],
|
||||||
'purchase' => [
|
'purchase' => [
|
||||||
|
|||||||
@@ -34,7 +34,10 @@ return [
|
|||||||
'max_quantity' => 'El máximo que se puede agregar es :max.',
|
'max_quantity' => 'El máximo que se puede agregar es :max.',
|
||||||
'bundle_variant_forbidden' => 'Un bundle no admite una variante.',
|
'bundle_variant_forbidden' => 'Un bundle no admite una variante.',
|
||||||
'empty_bundle' => 'El bundle no tiene componentes.',
|
'empty_bundle' => 'El bundle no tiene componentes.',
|
||||||
|
'bundle_component_unavailable' => 'El bundle contiene una variante que ya no está disponible para la venta.',
|
||||||
'variant_required' => 'Debe seleccionar una variante para este ítem.',
|
'variant_required' => 'Debe seleccionar una variante para este ítem.',
|
||||||
|
'variant_unavailable' => 'La variante seleccionada fue reemplazada o ya no está disponible para la venta.',
|
||||||
|
'cart_variant_unavailable' => 'El carrito contiene una variante reemplazada o que ya no está disponible para la venta.',
|
||||||
'reservation_expired' => 'La reserva de stock venció. Usá el carrito activo para continuar.',
|
'reservation_expired' => 'La reserva de stock venció. Usá el carrito activo para continuar.',
|
||||||
],
|
],
|
||||||
'purchase' => [
|
'purchase' => [
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
|
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
|
||||||
bootstrap="vendor/autoload.php"
|
bootstrap="tests/bootstrap.php"
|
||||||
colors="true"
|
colors="true"
|
||||||
>
|
>
|
||||||
<testsuites>
|
<testsuites>
|
||||||
@@ -19,7 +19,9 @@
|
|||||||
</source>
|
</source>
|
||||||
<php>
|
<php>
|
||||||
<env name="APP_ENV" value="testing" force="true"/>
|
<env name="APP_ENV" value="testing" force="true"/>
|
||||||
<env name="DB_DATABASE" value="shopit_test" force="true"/>
|
<env name="DB_CONNECTION" value="sqlite" force="true"/>
|
||||||
|
<env name="DB_DATABASE" value=":memory:" force="true"/>
|
||||||
|
<env name="DB_URL" value="null" force="true"/>
|
||||||
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
|
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
|
||||||
<env name="APP_CONFIG_CACHE" value="bootstrap/cache/phpunit-config.php"/>
|
<env name="APP_CONFIG_CACHE" value="bootstrap/cache/phpunit-config.php"/>
|
||||||
<env name="APP_EVENTS_CACHE" value="bootstrap/cache/phpunit-events.php"/>
|
<env name="APP_EVENTS_CACHE" value="bootstrap/cache/phpunit-events.php"/>
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<h1 style="margin: 0 0 20px;">Tu evento fue reprogramado</h1>
|
||||||
|
<p>Te informamos que la fecha de tu evento cambió.</p>
|
||||||
|
<p>
|
||||||
|
<strong>Fecha anterior:</strong> {{ $previousDate }}<br>
|
||||||
|
<strong>Nueva fecha:</strong> {{ $newDate }}
|
||||||
|
</p>
|
||||||
|
<p>Tus tickets continúan siendo válidos para la nueva fecha.</p>
|
||||||
|
<p><strong>Tickets afectados</strong></p>
|
||||||
|
<ul>
|
||||||
|
@foreach ($tickets as $ticket)
|
||||||
|
<li>{{ $ticket->name }} · N° de Ticket #{{ $ticket->id }}</li>
|
||||||
|
@endforeach
|
||||||
|
</ul>
|
||||||
|
<p style="color: #64748b; font-size: 13px;">N° de Orden #{{ $purchase->id }}</p>
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<h1 style="margin: 0 0 20px;">Actualización sobre tu evento</h1>
|
||||||
|
<p>La fecha <strong>{{ $date }}</strong> fue suspendida.</p>
|
||||||
|
|
||||||
|
@if ($disabledTickets->isNotEmpty())
|
||||||
|
<p>Los siguientes tickets quedaron inhabilitados porque no tienen otra fecha disponible:</p>
|
||||||
|
<ul>
|
||||||
|
@foreach ($disabledTickets as $ticket)
|
||||||
|
<li>{{ $ticket->name }} · N° de Ticket #{{ $ticket->id }}</li>
|
||||||
|
@endforeach
|
||||||
|
</ul>
|
||||||
|
<p>Para conocer las alternativas o condiciones de devolución, comunicate con la organización.</p>
|
||||||
|
@endif
|
||||||
|
|
||||||
|
@if ($activeTickets->isNotEmpty())
|
||||||
|
<p>Estos tickets conservan otras fechas disponibles:</p>
|
||||||
|
<ul>
|
||||||
|
@foreach ($activeTickets as $ticket)
|
||||||
|
<li>{{ $ticket->name }} · N° de Ticket #{{ $ticket->id }}</li>
|
||||||
|
@endforeach
|
||||||
|
</ul>
|
||||||
|
@endif
|
||||||
|
|
||||||
|
<p style="color: #64748b; font-size: 13px;">N° de Orden #{{ $purchase->id }}</p>
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
use App\Domains\Auth\Services\AdminCredentialVerifier;
|
use App\Domains\Auth\Services\AdminCredentialVerifier;
|
||||||
use App\Domains\Catalog\Services\ExpireStockReservationsService;
|
use App\Domains\Catalog\Services\ExpireStockReservationsService;
|
||||||
use App\Domains\Purchase\Services\TenantTransactionResetService;
|
use App\Domains\Purchase\Services\TenantTransactionResetService;
|
||||||
|
use App\Domains\Ticket\Services\BackfillRefundedUnitsService;
|
||||||
use App\Domains\Ticket\Services\LoadTestTicketDatasetService;
|
use App\Domains\Ticket\Services\LoadTestTicketDatasetService;
|
||||||
use Illuminate\Foundation\Inspiring;
|
use Illuminate\Foundation\Inspiring;
|
||||||
use Illuminate\Support\Facades\Artisan;
|
use Illuminate\Support\Facades\Artisan;
|
||||||
@@ -13,6 +14,27 @@ Artisan::command('inspire', function () {
|
|||||||
$this->comment(Inspiring::quote());
|
$this->comment(Inspiring::quote());
|
||||||
})->purpose('Display an inspiring quote');
|
})->purpose('Display an inspiring quote');
|
||||||
|
|
||||||
|
Artisan::command('tickets:backfill-refunded-units', function (BackfillRefundedUnitsService $service): int {
|
||||||
|
try {
|
||||||
|
$summary = $service->run();
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$this->error($exception->getMessage());
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->info(sprintf(
|
||||||
|
'Refund backfill: %d applied, %d bundles skipped, %d inventories updated, +%d refunded_units, +%d real_stock',
|
||||||
|
$summary['refunds_applied'],
|
||||||
|
$summary['bundles_skipped'],
|
||||||
|
$summary['inventories_updated'],
|
||||||
|
$summary['refunded_units_added'],
|
||||||
|
$summary['real_stock_added'],
|
||||||
|
));
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
})->purpose('Reconcile historical ticket refunds with inventory after reviewing existing refunded units');
|
||||||
|
|
||||||
Artisan::command('reservations:expire', function (): void {
|
Artisan::command('reservations:expire', function (): void {
|
||||||
$expired = app(ExpireStockReservationsService::class)->expireOverdue();
|
$expired = app(ExpireStockReservationsService::class)->expireOverdue();
|
||||||
|
|
||||||
|
|||||||
130
storage/framework/lsp-1ab91c4294c8e5da.php
Normal file
130
storage/framework/lsp-1ab91c4294c8e5da.php
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
<?php
|
||||||
|
error_reporting(error_reporting() & ~(E_WARNING | E_CORE_WARNING | E_COMPILE_WARNING | E_USER_WARNING | E_DEPRECATED | E_USER_DEPRECATED));
|
||||||
|
class LspHelper
|
||||||
|
{
|
||||||
|
public static function relativePath($path)
|
||||||
|
{
|
||||||
|
if (!str_contains($path, base_path())) {
|
||||||
|
return (string) $path;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ltrim(str_replace(base_path(), '', realpath($path) ?: $path), DIRECTORY_SEPARATOR);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function isVendor($path)
|
||||||
|
{
|
||||||
|
return str_contains($path, base_path('vendor'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function propertyDefault(ReflectionProperty $property, ?ReflectionParameter $parameter = null): array
|
||||||
|
{
|
||||||
|
if ($property->hasDefaultValue()) {
|
||||||
|
return ['default' => $property->getDefaultValue()];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($parameter?->isDefaultValueAvailable()) {
|
||||||
|
return ['default' => $parameter->getDefaultValue()];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function formatDefaultValue(mixed $value): mixed
|
||||||
|
{
|
||||||
|
return match (true) {
|
||||||
|
is_array($value) => 'array(...)',
|
||||||
|
$value instanceof UnitEnum => get_class($value) . '::' . $value->name,
|
||||||
|
$value instanceof Closure => 'Closure',
|
||||||
|
is_object($value) => get_class($value),
|
||||||
|
is_string($value) => var_export($value, true),
|
||||||
|
is_null($value) => 'null',
|
||||||
|
is_bool($value) => $value ? 'true' : 'false',
|
||||||
|
default => $value,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
use Pest\Expectation;
|
||||||
|
use Pest\TestSuite;
|
||||||
|
|
||||||
|
$pest = new class
|
||||||
|
{
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
if ($this->isInstalled()) {
|
||||||
|
$this->boot();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isInstalled(): bool
|
||||||
|
{
|
||||||
|
return class_exists(TestSuite::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function boot(): void
|
||||||
|
{
|
||||||
|
require_once base_path('vendor/pestphp/pest/overrides/Runner/TestSuiteLoader.php');
|
||||||
|
|
||||||
|
TestSuite::getInstance(base_path(), 'tests');
|
||||||
|
|
||||||
|
if (file_exists($pestFile = base_path('tests/Pest.php'))) {
|
||||||
|
require_once $pestFile;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function config(): ?array
|
||||||
|
{
|
||||||
|
if (!$this->isInstalled()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'uses' => $this->uses(),
|
||||||
|
'expectations' => $this->expectations(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function uses(): array
|
||||||
|
{
|
||||||
|
if (is_null($instance = TestSuite::getInstance())) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$reflection = new ReflectionProperty($instance->tests, 'uses');
|
||||||
|
$uses = $reflection->getValue($instance->tests);
|
||||||
|
|
||||||
|
return collect($uses)->map(function (array $use, string $path) {
|
||||||
|
[$classOrTraits] = $use;
|
||||||
|
|
||||||
|
return [
|
||||||
|
'path' => LspHelper::relativePath($path),
|
||||||
|
'classes' => array_values(array_filter($classOrTraits, fn ($c) => class_exists($c))),
|
||||||
|
'traits' => array_values(array_filter($classOrTraits, fn ($c) => trait_exists($c))),
|
||||||
|
];
|
||||||
|
})->values()->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function expectations(): array
|
||||||
|
{
|
||||||
|
$reflection = new ReflectionProperty(Expectation::class, 'extends');
|
||||||
|
$extends = $reflection->getValue();
|
||||||
|
|
||||||
|
return collect($extends)->map(function (Closure $closure, string $name) {
|
||||||
|
$parameters = collect((new ReflectionFunction($closure))->getParameters())
|
||||||
|
->map(function (ReflectionParameter $param) {
|
||||||
|
$type = $param->hasType() ? $param->getType() . ' ' : '';
|
||||||
|
|
||||||
|
$default = $param->isOptional() && $param->isDefaultValueAvailable()
|
||||||
|
? ' = ' . var_export($param->getDefaultValue(), true)
|
||||||
|
: '';
|
||||||
|
|
||||||
|
return $type . '$' . $param->getName() . $default;
|
||||||
|
})
|
||||||
|
->join(', ');
|
||||||
|
|
||||||
|
return compact('name', 'parameters');
|
||||||
|
})->values()->all();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
echo json_encode($pest->config());
|
||||||
@@ -220,6 +220,18 @@ class CatalogItemDetailControllerTest extends TestCase
|
|||||||
'time_start' => '10:00',
|
'time_start' => '10:00',
|
||||||
'time_end' => '19:00',
|
'time_end' => '19:00',
|
||||||
]);
|
]);
|
||||||
|
$rescheduledEventDate = $tenant->eventDates()->create([
|
||||||
|
'date' => '2026-10-08',
|
||||||
|
'time_start' => '10:00',
|
||||||
|
'time_end' => '19:00',
|
||||||
|
'rescheduled_to_event_date_id' => $unusedEventDate->id,
|
||||||
|
]);
|
||||||
|
$suspendedEventDate = $tenant->eventDates()->create([
|
||||||
|
'date' => '2026-10-11',
|
||||||
|
'time_start' => '10:00',
|
||||||
|
'time_end' => '19:00',
|
||||||
|
'suspended_at' => now(),
|
||||||
|
]);
|
||||||
$item = $this->createItem($tenant, 'Entry');
|
$item = $this->createItem($tenant, 'Entry');
|
||||||
$attribute = Attribute::query()->create([
|
$attribute = Attribute::query()->create([
|
||||||
'tenant_codigo' => $tenant->codigo,
|
'tenant_codigo' => $tenant->codigo,
|
||||||
@@ -245,6 +257,14 @@ class CatalogItemDetailControllerTest extends TestCase
|
|||||||
->assertJsonPath('data.attributes.0.options.0.validity_time.type', 'fixed_window')
|
->assertJsonPath('data.attributes.0.options.0.validity_time.type', 'fixed_window')
|
||||||
->assertJsonPath('data.attributes.0.options.1.id', $unusedEventDate->id)
|
->assertJsonPath('data.attributes.0.options.1.id', $unusedEventDate->id)
|
||||||
->assertJsonPath('data.attributes.0.options.1.value', (string) $unusedEventDate->id)
|
->assertJsonPath('data.attributes.0.options.1.value', (string) $unusedEventDate->id)
|
||||||
|
->assertJsonMissing([
|
||||||
|
'id' => $rescheduledEventDate->id,
|
||||||
|
'value' => (string) $rescheduledEventDate->id,
|
||||||
|
])
|
||||||
|
->assertJsonMissing([
|
||||||
|
'id' => $suspendedEventDate->id,
|
||||||
|
'value' => (string) $suspendedEventDate->id,
|
||||||
|
])
|
||||||
->assertJsonPath('data.variants.0.values.event_date.value', (string) $eventDate->id)
|
->assertJsonPath('data.variants.0.values.event_date.value', (string) $eventDate->id)
|
||||||
->assertJsonPath(
|
->assertJsonPath(
|
||||||
'data.variants.0.values.event_date.label',
|
'data.variants.0.values.event_date.label',
|
||||||
|
|||||||
@@ -200,10 +200,12 @@ class CatalogSchemaTest extends TestCase
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_variants_can_override_catalog_item_use_dates(): void
|
public function test_variants_support_event_dates_and_commercial_replacements(): void
|
||||||
{
|
{
|
||||||
$this->assertTrue(Schema::hasColumns('variantes', [
|
$this->assertTrue(Schema::hasColumns('variantes', [
|
||||||
'event_date_id',
|
'event_date_id',
|
||||||
|
'replaced_by_variant_id',
|
||||||
|
'sales_disabled_at',
|
||||||
]));
|
]));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,9 +6,15 @@ use App\Domains\Attachable\Enums\AttachmentType;
|
|||||||
use App\Domains\Attachable\Models\Attachment;
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Auth\Models\User;
|
||||||
use App\Domains\Authorization\Enums\RoleCode;
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
|
use App\Domains\Cart\Models\Cart;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Inventory;
|
use App\Domains\Catalog\Models\Inventory;
|
||||||
|
use App\Domains\Catalog\Models\StockReservation;
|
||||||
|
use App\Domains\Catalog\Models\StockReservationLine;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
|
use App\Domains\Event\Events\EventDateRescheduled;
|
||||||
|
use App\Domains\Event\Events\EventDateSuspended;
|
||||||
|
use App\Domains\Purchase\Services\Checkout\CatalogSelectionResolver;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use App\Domains\Tenant\Models\WebsiteType;
|
use App\Domains\Tenant\Models\WebsiteType;
|
||||||
use App\Domains\Ticket\Enums\ValidityTimeType;
|
use App\Domains\Ticket\Enums\ValidityTimeType;
|
||||||
@@ -16,8 +22,11 @@ use App\Domains\Ticket\Models\Ticket;
|
|||||||
use Database\Seeders\AuthorizationSeeder;
|
use Database\Seeders\AuthorizationSeeder;
|
||||||
use Database\Seeders\SocialMediaSeeder;
|
use Database\Seeders\SocialMediaSeeder;
|
||||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Illuminate\Support\Facades\Event;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
use Laravel\Sanctum\Sanctum;
|
use Laravel\Sanctum\Sanctum;
|
||||||
|
use PHPUnit\Framework\Attributes\DataProvider;
|
||||||
use Tests\TestCase;
|
use Tests\TestCase;
|
||||||
|
|
||||||
class AdminAppEventControllerTest extends TestCase
|
class AdminAppEventControllerTest extends TestCase
|
||||||
@@ -143,6 +152,52 @@ class AdminAppEventControllerTest extends TestCase
|
|||||||
->assertJsonMissing(['title' => 'Other Event']);
|
->assertJsonMissing(['title' => 'Other Event']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_dates_are_grouped_by_their_final_destination_and_ordered_by_active_date(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createActiveEvent($this->createTenant('acme'), 'Acme Event');
|
||||||
|
$source13 = $tenant->eventDates()->create([
|
||||||
|
'date' => '2026-10-13', 'time_start' => '00:00', 'time_end' => '23:59',
|
||||||
|
]);
|
||||||
|
$source22 = $tenant->eventDates()->create([
|
||||||
|
'date' => '2026-10-22', 'time_start' => '00:00', 'time_end' => '23:59',
|
||||||
|
]);
|
||||||
|
$middle24 = $tenant->eventDates()->create([
|
||||||
|
'date' => '2026-10-24', 'time_start' => '00:00', 'time_end' => '23:59',
|
||||||
|
]);
|
||||||
|
$active25 = $tenant->eventDates()->create([
|
||||||
|
'date' => '2026-10-25', 'time_start' => '00:00', 'time_end' => '23:59',
|
||||||
|
]);
|
||||||
|
$destination30 = $tenant->eventDates()->create([
|
||||||
|
'date' => '2026-10-30', 'time_start' => '00:00', 'time_end' => '23:59',
|
||||||
|
]);
|
||||||
|
$source13->update(['rescheduled_to_event_date_id' => $destination30->id]);
|
||||||
|
$source22->update(['rescheduled_to_event_date_id' => $middle24->id]);
|
||||||
|
$middle24->update(['rescheduled_to_event_date_id' => $destination30->id]);
|
||||||
|
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||||
|
|
||||||
|
$this->getJson('/api/v1/adminapp/tenant/event')
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonCount(2, 'data.dates')
|
||||||
|
->assertJsonPath('data.dates.0.id', $active25->id)
|
||||||
|
->assertJsonCount(0, 'data.dates.0.rescheduled_dates')
|
||||||
|
->assertJsonPath('data.dates.1.id', $destination30->id)
|
||||||
|
->assertJsonPath('data.dates.1.rescheduled_dates.0.id', $source13->id)
|
||||||
|
->assertJsonPath(
|
||||||
|
'data.dates.1.rescheduled_dates.0.rescheduled_to_event_date_id',
|
||||||
|
$destination30->id,
|
||||||
|
)
|
||||||
|
->assertJsonPath('data.dates.1.rescheduled_dates.1.id', $source22->id)
|
||||||
|
->assertJsonPath(
|
||||||
|
'data.dates.1.rescheduled_dates.1.rescheduled_to_event_date_id',
|
||||||
|
$destination30->id,
|
||||||
|
)
|
||||||
|
->assertJsonPath('data.dates.1.rescheduled_dates.2.id', $middle24->id)
|
||||||
|
->assertJsonPath(
|
||||||
|
'data.dates.1.rescheduled_dates.2.rescheduled_to_event_date_id',
|
||||||
|
$destination30->id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
public function test_reading_a_tenant_without_event_configuration_returns_empty_values(): void
|
public function test_reading_a_tenant_without_event_configuration_returns_empty_values(): void
|
||||||
{
|
{
|
||||||
$tenant = $this->createTenant('acme');
|
$tenant = $this->createTenant('acme');
|
||||||
@@ -230,6 +285,7 @@ class AdminAppEventControllerTest extends TestCase
|
|||||||
|
|
||||||
public function test_rescheduling_reuses_an_existing_date_and_tickets_resolve_its_validity(): void
|
public function test_rescheduling_reuses_an_existing_date_and_tickets_resolve_its_validity(): void
|
||||||
{
|
{
|
||||||
|
Event::fake([EventDateRescheduled::class]);
|
||||||
$tenant = $this->createActiveEvent($this->createTenant('acme'), 'Festival Acme');
|
$tenant = $this->createActiveEvent($this->createTenant('acme'), 'Festival Acme');
|
||||||
$admin = $this->createAdminAppUser($tenant);
|
$admin = $this->createAdminAppUser($tenant);
|
||||||
$original = $tenant->eventDates()->create([
|
$original = $tenant->eventDates()->create([
|
||||||
@@ -243,6 +299,17 @@ class AdminAppEventControllerTest extends TestCase
|
|||||||
'time_end' => '20:00',
|
'time_end' => '20:00',
|
||||||
]);
|
]);
|
||||||
$variant = $this->createVariant($tenant, $original->id);
|
$variant = $this->createVariant($tenant, $original->id);
|
||||||
|
$variant->inventory()->update(['real_stock' => 5, 'reserved_stock' => 2]);
|
||||||
|
$reservation = StockReservation::query()->create([
|
||||||
|
'status' => StockReservation::STATUS_ACTIVE,
|
||||||
|
'expires_at' => now()->addHour(),
|
||||||
|
]);
|
||||||
|
$reservationLine = StockReservationLine::query()->create([
|
||||||
|
'stock_reservation_id' => $reservation->id,
|
||||||
|
'inventory_id' => $variant->inventory_id,
|
||||||
|
'quantity' => 2,
|
||||||
|
'tracks_inventory' => true,
|
||||||
|
]);
|
||||||
$ticket = $this->createTicket($tenant, $admin, $variant);
|
$ticket = $this->createTicket($tenant, $admin, $variant);
|
||||||
Sanctum::actingAs($admin);
|
Sanctum::actingAs($admin);
|
||||||
|
|
||||||
@@ -253,12 +320,64 @@ class AdminAppEventControllerTest extends TestCase
|
|||||||
->assertJsonPath('data.status', 'rescheduled')
|
->assertJsonPath('data.status', 'rescheduled')
|
||||||
->assertJsonPath('data.rescheduled_to_event_date_id', $destination->id);
|
->assertJsonPath('data.rescheduled_to_event_date_id', $destination->id);
|
||||||
|
|
||||||
|
Event::assertDispatched(EventDateRescheduled::class, function (EventDateRescheduled $event) use ($tenant, $original, $destination): bool {
|
||||||
|
return $event->tenantCode === $tenant->codigo
|
||||||
|
&& $event->sourceEventDateId === $original->id
|
||||||
|
&& $event->destinationEventDateId === $destination->id
|
||||||
|
&& $event->previousDate === '09/10/2027'
|
||||||
|
&& $event->newDate === '20/10/2027'
|
||||||
|
&& $event->purchaseTickets === [];
|
||||||
|
});
|
||||||
|
|
||||||
$this->assertDatabaseCount('event_dates', 2);
|
$this->assertDatabaseCount('event_dates', 2);
|
||||||
|
$this->assertDatabaseHas('event_date_changes', [
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'change_type' => 'rescheduled',
|
||||||
|
'source_event_date_id' => $original->id,
|
||||||
|
'destination_event_date_id' => $destination->id,
|
||||||
|
'created_by_user_id' => $admin->id,
|
||||||
|
'previous_date' => '2027-10-09',
|
||||||
|
'new_date' => '2027-10-20',
|
||||||
|
]);
|
||||||
|
$variant->refresh();
|
||||||
|
$replacement = $variant->replacement()->firstOrFail();
|
||||||
|
$this->assertSame($original->id, $variant->event_date_id);
|
||||||
|
$this->assertSame($destination->id, $replacement->event_date_id);
|
||||||
|
$this->assertNotSame($variant->inventory_id, $replacement->inventory_id);
|
||||||
|
$this->assertSame(5, $variant->inventory->fresh()->real_stock);
|
||||||
|
$this->assertSame(0, $variant->inventory->fresh()->reserved_stock);
|
||||||
|
$this->assertSame(5, $replacement->inventory->real_stock);
|
||||||
|
$this->assertSame(2, $replacement->inventory->reserved_stock);
|
||||||
|
$this->assertSame($replacement->inventory_id, $reservationLine->fresh()->inventory_id);
|
||||||
|
$this->assertNotNull($variant->sales_disabled_at);
|
||||||
|
$this->assertSame($replacement->id, $variant->replaced_by_variant_id);
|
||||||
|
$this->assertSame(
|
||||||
|
[$replacement->id],
|
||||||
|
$variant->catalogItem->fresh(['variants.inventory'])->visibleVariants()->modelKeys(),
|
||||||
|
);
|
||||||
|
$this->assertSame($variant->id, $ticket->fresh()->source_variant_id);
|
||||||
|
|
||||||
|
try {
|
||||||
|
app(CatalogSelectionResolver::class)->resolve(
|
||||||
|
$tenant,
|
||||||
|
$variant->catalog_item_id,
|
||||||
|
$variant->id,
|
||||||
|
'direct_items.0',
|
||||||
|
);
|
||||||
|
$this->fail('The historical variant should not be sellable.');
|
||||||
|
} catch (ValidationException $exception) {
|
||||||
|
$this->assertArrayHasKey('direct_items.0.variant_id', $exception->errors());
|
||||||
|
}
|
||||||
|
|
||||||
$this->assertSame('20 de Octubre 2027', $tenant->fresh()->event_date_text);
|
$this->assertSame('20 de Octubre 2027', $tenant->fresh()->event_date_text);
|
||||||
$this->getJson('/api/tenants/bootstrap?dominio=acme.test&path=%2F')
|
$this->getJson('/api/tenants/bootstrap?dominio=acme.test&path=%2F')
|
||||||
->assertOk()
|
->assertOk()
|
||||||
->assertJsonCount(1, 'data.event.dates')
|
->assertJsonCount(1, 'data.event.dates')
|
||||||
->assertJsonPath('data.event.dates.0.id', $destination->id)
|
->assertJsonPath('data.event.dates.0.id', $destination->id)
|
||||||
|
->assertJsonPath('data.event.dates.0.info_text', '09/10/2027 se reprogramó para este día.')
|
||||||
|
->assertJsonPath('data.event.dates.0.isCanceled', false)
|
||||||
|
->assertJsonMissingPath('data.event.date_changes')
|
||||||
|
->assertJsonMissingPath('data.event.date_notices')
|
||||||
->assertJsonPath('data.event_date_text', '20 de Octubre 2027');
|
->assertJsonPath('data.event_date_text', '20 de Octubre 2027');
|
||||||
$this->assertSame(
|
$this->assertSame(
|
||||||
'2027-10-20 11:00:00',
|
'2027-10-20 11:00:00',
|
||||||
@@ -274,11 +393,29 @@ class AdminAppEventControllerTest extends TestCase
|
|||||||
])->assertOk()->assertJsonPath('data.status', 'rescheduled');
|
])->assertOk()->assertJsonPath('data.status', 'rescheduled');
|
||||||
|
|
||||||
$this->assertDatabaseCount('event_dates', 3);
|
$this->assertDatabaseCount('event_dates', 3);
|
||||||
|
$this->assertDatabaseCount('event_date_changes', 2);
|
||||||
|
$this->assertDatabaseHas('event_date_changes', [
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'change_type' => 'rescheduled',
|
||||||
|
'source_event_date_id' => $destination->id,
|
||||||
|
'created_by_user_id' => $admin->id,
|
||||||
|
'previous_date' => '2027-10-20',
|
||||||
|
'new_date' => '2027-10-25',
|
||||||
|
]);
|
||||||
|
$replacement->refresh();
|
||||||
|
$latestReplacement = $replacement->replacement()->firstOrFail();
|
||||||
|
$this->assertNotSame($replacement->inventory_id, $latestReplacement->inventory_id);
|
||||||
|
$this->assertSame(5, $latestReplacement->inventory->real_stock);
|
||||||
|
$this->assertSame('2027-10-25', $latestReplacement->eventDate->date->format('Y-m-d'));
|
||||||
|
$this->assertFalse($replacement->isSellable());
|
||||||
|
$this->assertTrue($latestReplacement->isSellable());
|
||||||
$this->assertSame('25 de Octubre 2027', $tenant->fresh()->event_date_text);
|
$this->assertSame('25 de Octubre 2027', $tenant->fresh()->event_date_text);
|
||||||
$this->getJson('/api/tenants/bootstrap?dominio=acme.test&path=%2F')
|
$this->getJson('/api/tenants/bootstrap?dominio=acme.test&path=%2F')
|
||||||
->assertOk()
|
->assertOk()
|
||||||
->assertJsonCount(1, 'data.event.dates')
|
->assertJsonCount(1, 'data.event.dates')
|
||||||
->assertJsonPath('data.event.dates.0.date', '2027-10-25')
|
->assertJsonPath('data.event.dates.0.date', '2027-10-25')
|
||||||
|
->assertJsonMissingPath('data.event.date_changes')
|
||||||
|
->assertJsonMissingPath('data.event.date_notices')
|
||||||
->assertJsonPath('data.event_date_text', '25 de Octubre 2027');
|
->assertJsonPath('data.event_date_text', '25 de Octubre 2027');
|
||||||
$this->assertSame(
|
$this->assertSame(
|
||||||
'2027-10-25 11:00:00',
|
'2027-10-25 11:00:00',
|
||||||
@@ -286,8 +423,92 @@ class AdminAppEventControllerTest extends TestCase
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static function cartInvalidatingDateChanges(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'reschedule' => ['reschedule', ['date' => '2027-10-20'], 'event_date_rescheduled'],
|
||||||
|
'suspend' => ['suspend', [], 'event_date_suspended'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
#[DataProvider('cartInvalidatingDateChanges')]
|
||||||
|
public function test_date_changes_invalidate_reserved_carts(string $action, array $payload, string $reason): void
|
||||||
|
{
|
||||||
|
Event::fake([EventDateRescheduled::class, EventDateSuspended::class]);
|
||||||
|
$tenant = $this->createActiveEvent($this->createTenant('acme'), 'Festival Acme');
|
||||||
|
$source = $tenant->eventDates()->create([
|
||||||
|
'date' => '2027-10-09', 'time_start' => '09:00', 'time_end' => '18:30',
|
||||||
|
]);
|
||||||
|
$variant = $this->createVariant($tenant, $source->id);
|
||||||
|
$variant->inventory->update(['real_stock' => 5, 'reserved_stock' => 2]);
|
||||||
|
$reservation = StockReservation::query()->create([
|
||||||
|
'status' => StockReservation::STATUS_ACTIVE, 'expires_at' => now()->addHour(),
|
||||||
|
]);
|
||||||
|
StockReservationLine::query()->create([
|
||||||
|
'stock_reservation_id' => $reservation->id, 'inventory_id' => $variant->inventory_id,
|
||||||
|
'quantity' => 2, 'tracks_inventory' => true,
|
||||||
|
]);
|
||||||
|
$admin = $this->createAdminAppUser($tenant);
|
||||||
|
$cart = Cart::query()->create([
|
||||||
|
'tenant_codigo' => $tenant->codigo, 'user_id' => $admin->id,
|
||||||
|
'status' => Cart::STATUS_ACTIVE, 'origin' => Cart::ORIGIN_USER,
|
||||||
|
'current_stock_reservation_id' => $reservation->id,
|
||||||
|
]);
|
||||||
|
$cart->items()->create([
|
||||||
|
'catalog_item_id' => $variant->catalog_item_id, 'variant_id' => $variant->id, 'cantidad' => 2,
|
||||||
|
]);
|
||||||
|
Sanctum::actingAs($admin);
|
||||||
|
|
||||||
|
$this->postJson("/api/v1/adminapp/tenant/event-dates/{$source->id}/{$action}", $payload)->assertOk();
|
||||||
|
|
||||||
|
$this->assertSame(Cart::STATUS_EXPIRED, $cart->fresh()->status);
|
||||||
|
$this->assertSame(StockReservation::STATUS_RELEASED, $reservation->fresh()->status);
|
||||||
|
$this->assertSame($reason, $reservation->fresh()->release_reason);
|
||||||
|
$this->assertSame(0, $variant->fresh()->inventory->reserved_stock);
|
||||||
|
if ($action === 'reschedule') {
|
||||||
|
$this->assertSame(0, $variant->fresh()->replacement->inventory->reserved_stock);
|
||||||
|
}
|
||||||
|
$this->getJson('/api/tenants/acme/cart')->assertOk()->assertJsonCount(0, 'data.items');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_rescheduling_reuses_an_equivalent_destination_variant(): void
|
||||||
|
{
|
||||||
|
Event::fake([EventDateRescheduled::class]);
|
||||||
|
$tenant = $this->createActiveEvent($this->createTenant('acme'), 'Festival Acme');
|
||||||
|
$original = $tenant->eventDates()->create([
|
||||||
|
'date' => '2027-10-09',
|
||||||
|
'time_start' => '09:00',
|
||||||
|
'time_end' => '18:30',
|
||||||
|
]);
|
||||||
|
$destination = $tenant->eventDates()->create([
|
||||||
|
'date' => '2027-10-20',
|
||||||
|
'time_start' => '09:00',
|
||||||
|
'time_end' => '18:30',
|
||||||
|
]);
|
||||||
|
$historicalVariant = $this->createVariant($tenant, $original->id);
|
||||||
|
$destinationVariant = Variant::query()->create([
|
||||||
|
'catalog_item_id' => $historicalVariant->catalog_item_id,
|
||||||
|
'inventory_id' => Inventory::query()->create(['real_stock' => 5])->id,
|
||||||
|
'event_date_id' => $destination->id,
|
||||||
|
]);
|
||||||
|
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||||
|
|
||||||
|
$this->postJson("/api/v1/adminapp/tenant/event-dates/{$original->id}/reschedule", [
|
||||||
|
'date' => '2027-10-20',
|
||||||
|
])->assertOk();
|
||||||
|
|
||||||
|
$this->assertSame(2, Variant::query()->count());
|
||||||
|
$this->assertSame(
|
||||||
|
$destinationVariant->id,
|
||||||
|
$historicalVariant->fresh()->replaced_by_variant_id,
|
||||||
|
);
|
||||||
|
$this->assertSame($original->id, $historicalVariant->fresh()->event_date_id);
|
||||||
|
$this->assertTrue($destinationVariant->fresh()->isSellable());
|
||||||
|
}
|
||||||
|
|
||||||
public function test_suspending_disables_only_tickets_without_another_usable_date(): void
|
public function test_suspending_disables_only_tickets_without_another_usable_date(): void
|
||||||
{
|
{
|
||||||
|
Event::fake([EventDateSuspended::class]);
|
||||||
$tenant = $this->createActiveEvent($this->createTenant('acme'), 'Festival Acme');
|
$tenant = $this->createActiveEvent($this->createTenant('acme'), 'Festival Acme');
|
||||||
$admin = $this->createAdminAppUser($tenant);
|
$admin = $this->createAdminAppUser($tenant);
|
||||||
$suspendedDate = $tenant->eventDates()->create([
|
$suspendedDate = $tenant->eventDates()->create([
|
||||||
@@ -303,6 +524,13 @@ class AdminAppEventControllerTest extends TestCase
|
|||||||
$singleDateVariant = $this->createVariant($tenant, $suspendedDate->id);
|
$singleDateVariant = $this->createVariant($tenant, $suspendedDate->id);
|
||||||
$multipleDateVariant = $this->createVariant($tenant);
|
$multipleDateVariant = $this->createVariant($tenant);
|
||||||
$multipleDateVariant->eventDates()->sync([$suspendedDate->id, $otherDate->id]);
|
$multipleDateVariant->eventDates()->sync([$suspendedDate->id, $otherDate->id]);
|
||||||
|
$remainingDateVariant = Variant::query()->create([
|
||||||
|
'catalog_item_id' => $multipleDateVariant->catalog_item_id,
|
||||||
|
'inventory_id' => Inventory::query()->create()->id,
|
||||||
|
'event_date_id' => $otherDate->id,
|
||||||
|
]);
|
||||||
|
$singleDateVariant->inventory->update(['real_stock' => 5]);
|
||||||
|
$multipleDateVariant->inventory->update(['real_stock' => 5]);
|
||||||
$singleDateTicket = $this->createTicket($tenant, $admin, $singleDateVariant);
|
$singleDateTicket = $this->createTicket($tenant, $admin, $singleDateVariant);
|
||||||
$multipleDateTicket = $this->createTicket($tenant, $admin, $multipleDateVariant);
|
$multipleDateTicket = $this->createTicket($tenant, $admin, $multipleDateVariant);
|
||||||
Sanctum::actingAs($admin);
|
Sanctum::actingAs($admin);
|
||||||
@@ -312,18 +540,60 @@ class AdminAppEventControllerTest extends TestCase
|
|||||||
->assertJsonPath('data.status', 'suspended')
|
->assertJsonPath('data.status', 'suspended')
|
||||||
->assertJsonPath('data.suspended_at', fn ($value) => is_string($value));
|
->assertJsonPath('data.suspended_at', fn ($value) => is_string($value));
|
||||||
|
|
||||||
|
Event::assertDispatched(EventDateSuspended::class, function (EventDateSuspended $event) use ($tenant, $suspendedDate): bool {
|
||||||
|
return $event->tenantCode === $tenant->codigo
|
||||||
|
&& $event->eventDateId === $suspendedDate->id
|
||||||
|
&& $event->date === '09/10/2027'
|
||||||
|
&& $event->purchaseTickets === [];
|
||||||
|
});
|
||||||
|
|
||||||
|
$this->assertDatabaseHas('event_date_changes', [
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'change_type' => 'suspended',
|
||||||
|
'source_event_date_id' => $suspendedDate->id,
|
||||||
|
'destination_event_date_id' => null,
|
||||||
|
'created_by_user_id' => $admin->id,
|
||||||
|
'previous_date' => '2027-10-09',
|
||||||
|
'new_date' => null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->postJson("/api/v1/adminapp/tenant/event-dates/{$suspendedDate->id}/suspend")
|
||||||
|
->assertOk();
|
||||||
|
$this->assertDatabaseCount('event_date_changes', 1);
|
||||||
|
|
||||||
$this->assertNotNull($singleDateTicket->fresh()->disabled_at);
|
$this->assertNotNull($singleDateTicket->fresh()->disabled_at);
|
||||||
$this->assertNull($multipleDateTicket->fresh()->disabled_at);
|
$this->assertNull($multipleDateTicket->fresh()->disabled_at);
|
||||||
|
$this->assertNotNull($singleDateVariant->fresh()->sales_disabled_at);
|
||||||
|
$this->assertNotNull($multipleDateVariant->fresh()->sales_disabled_at);
|
||||||
|
$replacement = $multipleDateVariant->fresh()->replacement;
|
||||||
|
$this->assertNotNull($replacement);
|
||||||
|
$this->assertSame($remainingDateVariant->id, $replacement->id);
|
||||||
|
$this->assertTrue($replacement->isSellable());
|
||||||
|
$this->assertSame([$otherDate->id], $replacement->selectedEventDates()->pluck('id')->all());
|
||||||
|
$this->assertSame(5, $replacement->inventory->fresh()->availableStock());
|
||||||
|
$this->assertTrue(CatalogItem::query()->whereKey($multipleDateVariant->catalog_item_id)->whereAvailable()->exists());
|
||||||
|
$this->assertFalse(CatalogItem::query()->whereKey($singleDateVariant->catalog_item_id)->whereAvailable()->exists());
|
||||||
$this->assertSame('10 de Octubre 2027', $tenant->fresh()->event_date_text);
|
$this->assertSame('10 de Octubre 2027', $tenant->fresh()->event_date_text);
|
||||||
$this->getJson('/api/tenants/bootstrap?dominio=acme.test&path=%2F')
|
$this->getJson('/api/tenants/bootstrap?dominio=acme.test&path=%2F')
|
||||||
->assertOk()
|
->assertOk()
|
||||||
->assertJsonCount(1, 'data.event.dates')
|
->assertJsonCount(2, 'data.event.dates')
|
||||||
->assertJsonPath('data.event.dates.0.id', $otherDate->id)
|
->assertJsonPath('data.event.dates.0.id', $suspendedDate->id)
|
||||||
|
->assertJsonPath('data.event.dates.0.info_text', 'Esta fecha fue cancelada.')
|
||||||
|
->assertJsonPath('data.event.dates.0.isCanceled', true)
|
||||||
|
->assertJsonPath('data.event.dates.1.id', $otherDate->id)
|
||||||
|
->assertJsonPath('data.event.dates.1.info_text', null)
|
||||||
|
->assertJsonPath('data.event.dates.1.isCanceled', false)
|
||||||
|
->assertJsonMissingPath('data.event.date_changes')
|
||||||
|
->assertJsonMissingPath('data.event.date_notices')
|
||||||
->assertJsonPath('data.event_date_text', '10 de Octubre 2027');
|
->assertJsonPath('data.event_date_text', '10 de Octubre 2027');
|
||||||
$this->assertSame(
|
$this->assertSame(
|
||||||
'2027-10-10 09:00:00',
|
'2027-10-10 09:00:00',
|
||||||
$multipleDateTicket->fresh()->resolvedValidity()->effectiveStartsAt()?->format('Y-m-d H:i:s'),
|
$multipleDateTicket->fresh()->resolvedValidity()->effectiveStartsAt()?->format('Y-m-d H:i:s'),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
$this->postJson("/api/v1/adminapp/tenant/event-dates/{$otherDate->id}/suspend")
|
||||||
|
->assertOk();
|
||||||
|
$this->assertFalse(CatalogItem::query()->whereKey($multipleDateVariant->catalog_item_id)->whereAvailable()->exists());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_suspending_a_reschedule_destination_disables_tickets_from_predecessor_dates(): void
|
public function test_suspending_a_reschedule_destination_disables_tickets_from_predecessor_dates(): void
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user