Compare commits
6 Commits
a46bf905e8
...
feature/re
| Author | SHA1 | Date | |
|---|---|---|---|
| 5503559899 | |||
| 830f65c402 | |||
| df6892c662 | |||
| de08ee4ac7 | |||
| 1269ebcda0 | |||
| 04e54fefad |
@@ -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]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,10 @@ class StockReservationService
|
||||
|
||||
public const REASON_CART_CHANGED = 'cart_changed';
|
||||
|
||||
public const REASON_EVENT_DATE_RESCHEDULED = 'event_date_rescheduled';
|
||||
|
||||
public const REASON_EVENT_DATE_SUSPENDED = 'event_date_suspended';
|
||||
|
||||
public const REASON_PURCHASE_SUPERSEDED = 'purchase_superseded';
|
||||
|
||||
public const REASON_PURCHASE_CANCELLED = 'purchase_cancelled';
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
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\Services\StockReservationService;
|
||||
use App\Domains\Catalog\Services\VariantReplacementService;
|
||||
use App\Domains\Event\Enums\EventDateChangeType;
|
||||
use App\Domains\Event\Events\EventDateRescheduled;
|
||||
@@ -28,6 +30,7 @@ class EventService
|
||||
private readonly EffectiveEventDateResolver $effectiveEventDateResolver,
|
||||
private readonly AffectedEventDatePurchaseResolver $affectedPurchaseResolver,
|
||||
private readonly VariantReplacementService $variantReplacementService,
|
||||
private readonly InvalidateEventDateCartsService $invalidateEventDateCarts,
|
||||
) {}
|
||||
|
||||
public function forTenant(Tenant $tenant): Tenant
|
||||
@@ -125,9 +128,11 @@ class EventService
|
||||
]);
|
||||
}
|
||||
|
||||
$affectedDateIds = $this->affectedDateIds($tenant, $source);
|
||||
$this->invalidateEventDateCarts->invalidate($tenant, $affectedDateIds);
|
||||
$purchaseTickets = $this->affectedPurchaseResolver->resolve(
|
||||
$tenant,
|
||||
$this->affectedDateIds($tenant, $source),
|
||||
$affectedDateIds,
|
||||
);
|
||||
$source->update(['rescheduled_to_event_date_id' => $destination->getKey()]);
|
||||
$this->variantReplacementService->replaceEventDate($source, $effectiveDestination);
|
||||
@@ -173,10 +178,13 @@ class EventService
|
||||
return $date->load('validityTime');
|
||||
}
|
||||
|
||||
$purchaseTickets = $this->affectedPurchaseResolver->resolve(
|
||||
$affectedDateIds = $this->affectedDateIds($tenant, $date);
|
||||
$this->invalidateEventDateCarts->invalidate(
|
||||
$tenant,
|
||||
$this->affectedDateIds($tenant, $date),
|
||||
$affectedDateIds,
|
||||
StockReservationService::REASON_EVENT_DATE_SUSPENDED,
|
||||
);
|
||||
$purchaseTickets = $this->affectedPurchaseResolver->resolve($tenant, $affectedDateIds);
|
||||
$date->update(['suspended_at' => now()]);
|
||||
$this->variantReplacementService->disableForSuspension($date);
|
||||
$this->disableTicketsWithoutUsableDates($tenant, $date);
|
||||
|
||||
@@ -124,7 +124,10 @@ class TicketFilterFormService
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
'placeholder' => 'Estado',
|
||||
'options' => Ticket::statusOptions(),
|
||||
'options' => array_values(array_filter(
|
||||
Ticket::statusOptions(),
|
||||
fn (array $option): bool => $option['value'] !== Ticket::STATUS_CANCELLED,
|
||||
)),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -398,7 +398,7 @@ class NotificationMailService
|
||||
->forTenant($tenantCode)
|
||||
->send(
|
||||
$recipient,
|
||||
"Una fecha de tu evento fue suspendida - Compra #{$purchase->getKey()}",
|
||||
"Una fecha de tu evento fue suspendida - N° de Orden #{$purchase->getKey()}",
|
||||
view('mail.notifications.event-date-suspended', compact(
|
||||
'purchase', 'date', 'disabledTickets', 'activeTickets'
|
||||
))->render(),
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domains\Purchase\Services\Checkout;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\StockReservation;
|
||||
use App\Domains\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
||||
@@ -91,7 +92,16 @@ class ReleaseCheckoutService
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)) {
|
||||
$this->reservations->returnToCart($purchase, $cart);
|
||||
if ($this->hasUnavailableVariants($cart)) {
|
||||
$this->releasePurchaseReservations($purchase, $targetStatus, $cart);
|
||||
$cart->update([
|
||||
'status' => Cart::STATUS_EXPIRED,
|
||||
'current_purchase_id' => null,
|
||||
'current_stock_reservation_id' => null,
|
||||
]);
|
||||
} else {
|
||||
$this->reservations->returnToCart($purchase, $cart);
|
||||
}
|
||||
$purchase->update(['status' => Purchase::STATUS_CANCELLED]);
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
@@ -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(
|
||||
Purchase $purchase,
|
||||
string $targetStatus,
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,147 +1,16 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Events\MigrationsEnded;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Symfony\Component\Console\Output\ConsoleOutput;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
$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++;
|
||||
// Bundle purchases need a component allocation that is outside this backfill.
|
||||
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'));
|
||||
$realStockAdded = array_sum(array_column($counts, 'stock'));
|
||||
|
||||
return [
|
||||
'refunds_seen' => $refundsSeen,
|
||||
'refunds_applied' => $refundedUnitsAdded,
|
||||
'bundles_skipped' => $bundlesSkipped,
|
||||
'inventories_updated' => count($counts),
|
||||
'refunded_units_added' => $refundedUnitsAdded,
|
||||
'real_stock_added' => $realStockAdded,
|
||||
];
|
||||
});
|
||||
|
||||
Log::info('inventory.refunded_units_backfill.completed', $summary);
|
||||
|
||||
// The migrator prints DONE after up() returns. Emit the summary once the
|
||||
// whole migration run ends so it appears below that line in the console.
|
||||
if (app()->runningInConsole()) {
|
||||
$printed = false;
|
||||
Event::listen(MigrationsEnded::class, static function (MigrationsEnded $event) use ($summary, &$printed): void {
|
||||
if ($printed || $event->method !== 'up') {
|
||||
return;
|
||||
}
|
||||
$printed = true;
|
||||
|
||||
(new ConsoleOutput)->writeln(sprintf(
|
||||
' <info>Refund backfill:</info> %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'],
|
||||
));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** @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;
|
||||
}
|
||||
// Historical reconciliation runs explicitly via tickets:backfill-refunded-units.
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
throw new RuntimeException('El backfill de reembolsos históricos no se puede revertir sin reconciliar el stock.');
|
||||
// Reconciliation cannot be reversed without auditing stock.
|
||||
}
|
||||
};
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<p>Los siguientes tickets quedaron inhabilitados porque no tienen otra fecha disponible:</p>
|
||||
<ul>
|
||||
@foreach ($disabledTickets as $ticket)
|
||||
<li>{{ $ticket->name }} · #{{ $ticket->id }}</li>
|
||||
<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>
|
||||
@@ -15,9 +15,9 @@
|
||||
<p>Estos tickets conservan otras fechas disponibles:</p>
|
||||
<ul>
|
||||
@foreach ($activeTickets as $ticket)
|
||||
<li>{{ $ticket->name }} · #{{ $ticket->id }}</li>
|
||||
<li>{{ $ticket->name }} · N° de Ticket #{{ $ticket->id }}</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
|
||||
<p style="color: #64748b; font-size: 13px;">Compra #{{ $purchase->id }}</p>
|
||||
<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\Catalog\Services\ExpireStockReservationsService;
|
||||
use App\Domains\Purchase\Services\TenantTransactionResetService;
|
||||
use App\Domains\Ticket\Services\BackfillRefundedUnitsService;
|
||||
use App\Domains\Ticket\Services\LoadTestTicketDatasetService;
|
||||
use Illuminate\Foundation\Inspiring;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
@@ -13,6 +14,27 @@ Artisan::command('inspire', function () {
|
||||
$this->comment(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 {
|
||||
$expired = app(ExpireStockReservationsService::class)->expireOverdue();
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\StockReservation;
|
||||
@@ -25,6 +26,7 @@ use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AdminAppEventControllerTest extends TestCase
|
||||
@@ -421,6 +423,54 @@ 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]);
|
||||
|
||||
@@ -79,7 +79,6 @@ class AdminAppTicketFilterFormControllerTest extends TestCase
|
||||
['value' => 'used', 'label' => 'Usado'],
|
||||
['value' => 'expired', 'label' => 'Vencido'],
|
||||
['value' => 'disabled', 'label' => 'Inhabilitado'],
|
||||
['value' => 'cancelled', 'label' => 'Cancelado'],
|
||||
['value' => 'refunded', 'label' => 'Reembolsado'],
|
||||
],
|
||||
],
|
||||
|
||||
@@ -11,7 +11,9 @@ use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
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 App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
||||
@@ -20,6 +22,7 @@ use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
class StorePurchaseTest extends TestCase
|
||||
@@ -642,6 +645,80 @@ class StorePurchaseTest extends TestCase
|
||||
$this->assertSame(1, $activeCart->items()->count());
|
||||
}
|
||||
|
||||
/** @return array<string, array{string, string}> */
|
||||
public static function unavailableCancellationCases(): array
|
||||
{
|
||||
return [
|
||||
'created with disabled variant' => [Purchase::STATUS_CREATED, 'disabled'],
|
||||
'pending payment with replaced variant' => [Purchase::STATUS_PENDING_PAYMENT, 'replaced'],
|
||||
'pending payment with suspended date' => [Purchase::STATUS_PENDING_PAYMENT, 'suspended'],
|
||||
];
|
||||
}
|
||||
|
||||
#[DataProvider('unavailableCancellationCases')]
|
||||
public function test_cancelling_a_purchase_with_unavailable_variants_invalidates_the_whole_cart(
|
||||
string $purchaseStatus,
|
||||
string $change,
|
||||
): void {
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$otherVariant = $this->createVariantForTenant('sonder', 10, '25.00', 'other');
|
||||
$cart = Cart::query()->create([
|
||||
'tenant_codigo' => $tenant->codigo, 'user_id' => $user->id,
|
||||
'status' => Cart::STATUS_ACTIVE, 'origin' => Cart::ORIGIN_USER,
|
||||
]);
|
||||
$cart->addItem($variant->catalog_item_id, $variant->id, 2);
|
||||
$cart->addItem($otherVariant->catalog_item_id, $otherVariant->id, 1);
|
||||
$purchase = app(CheckoutService::class)->startCheckout($tenant, $user->id, ['cart_id' => $cart->id]);
|
||||
$purchase->update(['status' => $purchaseStatus]);
|
||||
$reservedInventoryId = $variant->inventory_id;
|
||||
|
||||
if ($change === 'replaced') {
|
||||
// A reprogramming can move reservation lines away from the original variant.
|
||||
$replacementInventory = Inventory::query()->create(['real_stock' => 10, 'reserved_stock' => 2]);
|
||||
$replacement = Variant::query()->create([
|
||||
'catalog_item_id' => $variant->catalog_item_id, 'inventory_id' => $replacementInventory->id,
|
||||
]);
|
||||
StockReservationLine::query()->where('stock_reservation_id', $purchase->stock_reservation_id)
|
||||
->where('inventory_id', $variant->inventory_id)
|
||||
->update(['inventory_id' => $replacementInventory->id]);
|
||||
$variant->inventory->update(['reserved_stock' => 0]);
|
||||
$variant->update(['replaced_by_variant_id' => $replacement->id, 'sales_disabled_at' => now()]);
|
||||
$reservedInventoryId = $replacementInventory->id;
|
||||
} elseif ($change === 'suspended') {
|
||||
$date = EventDate::query()->create([
|
||||
'tenant_code' => $tenant->codigo, 'date' => '2027-10-09',
|
||||
'time_start' => '09:00', 'time_end' => '18:00', 'suspended_at' => now(),
|
||||
]);
|
||||
$variant->eventDates()->sync([$date->id]);
|
||||
} else {
|
||||
$variant->update(['sales_disabled_at' => now()]);
|
||||
}
|
||||
|
||||
$this->actingAs($user, 'sanctum');
|
||||
for ($attempt = 0; $attempt < 2; $attempt++) {
|
||||
$this->postJson("/api/tenants/sonder/compras/{$purchase->id}/cancel")
|
||||
->assertOk()->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);
|
||||
}
|
||||
|
||||
$this->assertDatabaseHas('carritos', [
|
||||
'id' => $cart->id, 'status' => Cart::STATUS_EXPIRED,
|
||||
'current_purchase_id' => null, 'current_stock_reservation_id' => null,
|
||||
]);
|
||||
$this->assertDatabaseHas('stock_reservations', [
|
||||
'id' => $purchase->stock_reservation_id, 'status' => StockReservation::STATUS_RELEASED,
|
||||
'release_reason' => 'purchase_cancelled',
|
||||
]);
|
||||
foreach ([$reservedInventoryId, $otherVariant->inventory_id] as $inventoryId) {
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $inventoryId, 'real_stock' => 10, 'reserved_stock' => 0,
|
||||
]);
|
||||
}
|
||||
$this->getJson('/api/tenants/sonder/cart')->assertOk()->assertJsonCount(0, 'data.items');
|
||||
$this->assertSame(Cart::STATUS_ABANDONED, $cart->fresh()->status);
|
||||
}
|
||||
|
||||
public function test_it_reuses_the_cart_reservation_for_a_new_checkout_and_rejects_a_late_confirmation(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
|
||||
@@ -289,8 +289,7 @@ class AdminAppTicketControllerTest extends TestCase
|
||||
'refunded_units_added' => 1,
|
||||
'real_stock_added' => 1,
|
||||
]);
|
||||
$backfill = require database_path('migrations/2026_09_16_000100_backfill_refunded_units.php');
|
||||
$backfill->up();
|
||||
$this->artisan('tickets:backfill-refunded-units')->assertSuccessful();
|
||||
|
||||
$this->assertSame(1, $inventory->fresh()->refunded_units);
|
||||
$this->assertSame(1, $inventory->fresh()->real_stock);
|
||||
@@ -308,6 +307,19 @@ class AdminAppTicketControllerTest extends TestCase
|
||||
$this->assertSame(2, $inventory->fresh()->real_stock);
|
||||
}
|
||||
|
||||
public function test_backfill_command_fails_without_changing_existing_refunded_units(): void
|
||||
{
|
||||
$inventory = Inventory::query()->create([
|
||||
'real_stock' => 3,
|
||||
'refunded_units' => 1,
|
||||
]);
|
||||
|
||||
$this->artisan('tickets:backfill-refunded-units')->assertFailed();
|
||||
|
||||
$this->assertSame(1, $inventory->fresh()->refunded_units);
|
||||
$this->assertSame(3, $inventory->fresh()->real_stock);
|
||||
}
|
||||
|
||||
public function test_it_records_different_refund_types_for_tickets_from_the_same_purchase_item(): void
|
||||
{
|
||||
$tenant = $this->createTenant('ticket-mixed-refunds');
|
||||
|
||||
175
tests/Unit/Cart/InvalidateEventDateCartsServiceTest.php
Normal file
175
tests/Unit/Cart/InvalidateEventDateCartsServiceTest.php
Normal file
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Cart;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Cart\Services\InvalidateEventDateCartsService;
|
||||
use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\StockReservation;
|
||||
use App\Domains\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvalidateEventDateCartsServiceTest extends TestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
// Minimal service schema, still using the guarded SQLite :memory: connection.
|
||||
Schema::create('carritos', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('tenant_codigo');
|
||||
$table->string('status');
|
||||
$table->unsignedBigInteger('current_purchase_id')->nullable();
|
||||
$table->unsignedBigInteger('current_stock_reservation_id')->nullable();
|
||||
$table->timestamps();
|
||||
$table->softDeletes();
|
||||
});
|
||||
Schema::create('carrito_items', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->unsignedBigInteger('cart_id');
|
||||
$table->unsignedBigInteger('variant_id');
|
||||
});
|
||||
Schema::create('variantes', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->unsignedBigInteger('event_date_id')->nullable();
|
||||
$table->softDeletes();
|
||||
});
|
||||
Schema::create('event_dates', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->date('date')->nullable();
|
||||
$table->time('time_start')->nullable();
|
||||
});
|
||||
Schema::create('variant_event_dates', function (Blueprint $table): void {
|
||||
$table->unsignedBigInteger('variant_id');
|
||||
$table->unsignedBigInteger('event_date_id');
|
||||
});
|
||||
Schema::create('compras', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->unsignedBigInteger('stock_reservation_id');
|
||||
});
|
||||
Schema::create('inventories', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->integer('real_stock')->default(10);
|
||||
$table->integer('reserved_stock')->default(2);
|
||||
$table->integer('sold_units')->default(0);
|
||||
$table->integer('refunded_units')->default(0);
|
||||
});
|
||||
Schema::create('stock_reservations', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('status');
|
||||
$table->timestamp('expires_at')->nullable();
|
||||
$table->timestamp('released_at')->nullable();
|
||||
$table->timestamp('expired_at')->nullable();
|
||||
$table->string('release_reason')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
Schema::create('stock_reservation_lines', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->unsignedBigInteger('stock_reservation_id');
|
||||
$table->unsignedBigInteger('inventory_id');
|
||||
$table->integer('quantity');
|
||||
});
|
||||
DB::table('event_dates')->insert([['id' => 1], ['id' => 2]]);
|
||||
DB::table('variantes')->insert([
|
||||
['id' => 1, 'event_date_id' => 1],
|
||||
['id' => 2, 'event_date_id' => 2],
|
||||
['id' => 3, 'event_date_id' => null],
|
||||
]);
|
||||
DB::table('variant_event_dates')->insert(['variant_id' => 3, 'event_date_id' => 1]);
|
||||
}
|
||||
|
||||
public static function releaseReasons(): array
|
||||
{
|
||||
return [
|
||||
[StockReservationService::REASON_EVENT_DATE_RESCHEDULED],
|
||||
[StockReservationService::REASON_EVENT_DATE_SUSPENDED],
|
||||
];
|
||||
}
|
||||
|
||||
#[DataProvider('releaseReasons')]
|
||||
public function test_invalidates_whole_cart_and_releases_all_its_stock_only_once(string $reason): void
|
||||
{
|
||||
$cart = $this->cart(1);
|
||||
$otherInventory = DB::table('inventories')->insertGetId([]);
|
||||
DB::table('carrito_items')->insert(['cart_id' => $cart->id, 'variant_id' => 2]);
|
||||
DB::table('stock_reservation_lines')->insert([
|
||||
'stock_reservation_id' => $cart->current_stock_reservation_id,
|
||||
'inventory_id' => $otherInventory,
|
||||
'quantity' => 2,
|
||||
]);
|
||||
$reservationId = $cart->current_stock_reservation_id;
|
||||
$this->invalidate($reason);
|
||||
$this->invalidate($reason);
|
||||
|
||||
$this->assertSame(Cart::STATUS_EXPIRED, $cart->fresh()->status);
|
||||
$this->assertNull($cart->fresh()->current_stock_reservation_id);
|
||||
$this->assertSame(0, (int) Inventory::query()->sum('reserved_stock'));
|
||||
$this->assertSame(20, (int) Inventory::query()->sum('real_stock'));
|
||||
$this->assertDatabaseHas('stock_reservations', [
|
||||
'id' => $reservationId, 'status' => StockReservation::STATUS_RELEASED,
|
||||
'release_reason' => $reason,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_preserves_other_dates_tenants_and_purchase_reservations(): void
|
||||
{
|
||||
$otherDate = $this->cart(2);
|
||||
$otherTenant = $this->cart(1, 'other');
|
||||
$purchaseCart = $this->cart(1);
|
||||
DB::table('compras')->insert(['stock_reservation_id' => $purchaseCart->current_stock_reservation_id]);
|
||||
$currentPurchaseCart = $this->cart(1);
|
||||
$currentPurchaseCart->update(['current_purchase_id' => 99]);
|
||||
$affected = $this->cart(3);
|
||||
|
||||
$this->invalidate();
|
||||
|
||||
foreach ([$otherDate, $otherTenant, $purchaseCart, $currentPurchaseCart] as $cart) {
|
||||
$this->assertSame(Cart::STATUS_ACTIVE, $cart->fresh()->status);
|
||||
$this->assertSame(StockReservation::STATUS_ACTIVE, $cart->fresh()->currentStockReservation->status);
|
||||
}
|
||||
$this->assertSame(Cart::STATUS_EXPIRED, $affected->fresh()->status);
|
||||
$this->assertSame(8, (int) Inventory::query()->sum('reserved_stock'));
|
||||
}
|
||||
|
||||
public function test_rolls_back_invalidation_when_the_date_change_fails(): void
|
||||
{
|
||||
$cart = $this->cart(1);
|
||||
DB::beginTransaction();
|
||||
$this->invalidate();
|
||||
DB::rollBack();
|
||||
|
||||
$this->assertSame(Cart::STATUS_ACTIVE, $cart->fresh()->status);
|
||||
$this->assertSame(StockReservation::STATUS_ACTIVE, $cart->fresh()->currentStockReservation->status);
|
||||
$this->assertSame(2, (int) Inventory::query()->sum('reserved_stock'));
|
||||
}
|
||||
|
||||
private function invalidate(string $reason = StockReservationService::REASON_EVENT_DATE_RESCHEDULED): void
|
||||
{
|
||||
app(InvalidateEventDateCartsService::class)->invalidate(new Tenant(['codigo' => 'acme']), collect([1]), $reason);
|
||||
}
|
||||
|
||||
private function cart(int $variantId, string $tenantCode = 'acme'): Cart
|
||||
{
|
||||
$reservation = StockReservation::query()->create([
|
||||
'status' => StockReservation::STATUS_ACTIVE, 'expires_at' => now()->addHour(),
|
||||
]);
|
||||
$cart = Cart::query()->create([
|
||||
'tenant_codigo' => $tenantCode, 'status' => Cart::STATUS_ACTIVE,
|
||||
'current_stock_reservation_id' => $reservation->id,
|
||||
]);
|
||||
DB::table('carrito_items')->insert(['cart_id' => $cart->id, 'variant_id' => $variantId]);
|
||||
DB::table('stock_reservation_lines')->insert([
|
||||
'stock_reservation_id' => $reservation->id,
|
||||
'inventory_id' => DB::table('inventories')->insertGetId([]),
|
||||
'quantity' => 2,
|
||||
]);
|
||||
|
||||
return $cart;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user