feat(refund): enhance refund process by adding backfill for refunded_units and updating inventory restoration logic

This commit is contained in:
2026-09-16 15:00:41 -03:00
parent 353fd34db2
commit a46bf905e8
4 changed files with 168 additions and 7 deletions

View File

@@ -11,7 +11,6 @@ return new class extends Migration
Schema::table('inventories', function (Blueprint $table): void {
$table->unsignedBigInteger('refunded_units')->default(0);
});
}
public function down(): void

View File

@@ -0,0 +1,147 @@
<?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;
}
}
public function down(): void
{
throw new RuntimeException('El backfill de reembolsos históricos no se puede revertir sin reconciliar el stock.');
}
};