fix(ticket): guard legacy refund amount removal
This commit is contained in:
@@ -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');
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user