From 28ab6c9ae4656668e35a7904a1f4fadaed9b89d6 Mon Sep 17 00:00:00 2001 From: ncoronel Date: Mon, 14 Sep 2026 12:31:03 -0300 Subject: [PATCH] fix(ticket): guard legacy refund amount removal --- ...ve_refunded_amount_from_purchase_items.php | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/database/migrations/2026_09_14_040000_remove_refunded_amount_from_purchase_items.php b/database/migrations/2026_09_14_040000_remove_refunded_amount_from_purchase_items.php index f331d8c..8c7c7a8 100644 --- a/database/migrations/2026_09_14_040000_remove_refunded_amount_from_purchase_items.php +++ b/database/migrations/2026_09_14_040000_remove_refunded_amount_from_purchase_items.php @@ -2,12 +2,32 @@ 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 { + $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 está respaldado por ticket_refunds.' + ); + } + Schema::table('compra_items', function (Blueprint $table): void { $table->dropColumn('refunded_amount'); }); @@ -18,5 +38,15 @@ return new class extends Migration 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'); } };