Compare commits
2 Commits
f8a3296821
...
a46bf905e8
| Author | SHA1 | Date | |
|---|---|---|---|
| a46bf905e8 | |||
| 353fd34db2 |
@@ -10,6 +10,7 @@ use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
|
||||
#[Fillable([
|
||||
'sold_units',
|
||||
'refunded_units',
|
||||
'reserved_stock',
|
||||
'real_stock',
|
||||
])]
|
||||
@@ -23,6 +24,7 @@ class Inventory extends Model
|
||||
|
||||
protected $attributes = [
|
||||
'sold_units' => 0,
|
||||
'refunded_units' => 0,
|
||||
'reserved_stock' => 0,
|
||||
'real_stock' => 0,
|
||||
];
|
||||
@@ -31,6 +33,7 @@ class Inventory extends Model
|
||||
{
|
||||
return [
|
||||
'sold_units' => 'integer',
|
||||
'refunded_units' => 'integer',
|
||||
'reserved_stock' => 'integer',
|
||||
'real_stock' => 'integer',
|
||||
];
|
||||
|
||||
@@ -188,6 +188,7 @@ class VariantReplacementService
|
||||
|
||||
$replacementInventory = Inventory::query()->create([
|
||||
'sold_units' => $sourceInventory->sold_units,
|
||||
'refunded_units' => $sourceInventory->refunded_units,
|
||||
'reserved_stock' => $reservedStock,
|
||||
'real_stock' => $sourceInventory->real_stock,
|
||||
]);
|
||||
@@ -235,6 +236,7 @@ class VariantReplacementService
|
||||
'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()
|
||||
@@ -245,6 +247,7 @@ class VariantReplacementService
|
||||
'real_stock' => 0,
|
||||
'reserved_stock' => 0,
|
||||
'sold_units' => 0,
|
||||
'refunded_units' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -177,6 +177,7 @@ class FoodService
|
||||
|
||||
$historicalInventory = Inventory::query()->create([
|
||||
'sold_units' => $inventory->sold_units,
|
||||
'refunded_units' => $inventory->refunded_units,
|
||||
'reserved_stock' => 0,
|
||||
'real_stock' => $inventory->real_stock,
|
||||
]);
|
||||
|
||||
@@ -65,9 +65,10 @@ class TenantTransactionResetService
|
||||
DB::table('inventories')
|
||||
->whereIn('id', $scope['inventory_ids'])
|
||||
->update([
|
||||
'real_stock' => DB::raw('real_stock + sold_units'),
|
||||
'real_stock' => DB::raw('real_stock + sold_units - refunded_units'),
|
||||
'reserved_stock' => 0,
|
||||
'sold_units' => 0,
|
||||
'refunded_units' => 0,
|
||||
]);
|
||||
|
||||
return $summary;
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
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\Services\PurchaseRefundSummaryService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
@@ -223,10 +226,57 @@ class AdminAppTicketService
|
||||
'amount' => number_format($refundAmount, 2, '.', ''),
|
||||
]);
|
||||
|
||||
$this->restoreInventory($ticket, $purchaseItem);
|
||||
|
||||
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()
|
||||
|
||||
@@ -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,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.');
|
||||
}
|
||||
};
|
||||
@@ -23,6 +23,7 @@ use Database\Seeders\AttributeSeeder;
|
||||
use Database\Seeders\AuthorizationSeeder;
|
||||
use Database\Seeders\FiestaFutbolInfantilProductSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use Tests\TestCase;
|
||||
@@ -186,6 +187,7 @@ class AdminAppTicketControllerTest extends TestCase
|
||||
$this->grantTicketsMenu($tenant);
|
||||
Sanctum::actingAs($admin);
|
||||
[$ticket, $purchaseItem] = $this->createRefundableTicket($tenant, $admin, '100.00');
|
||||
$inventory = $ticket->sourceCatalogItem->inventory;
|
||||
|
||||
$this->postJson("/api/v1/adminapp/tenant/tickets/{$ticket->id}/refund", [
|
||||
'refund_type' => 'total',
|
||||
@@ -201,6 +203,9 @@ class AdminAppTicketControllerTest extends TestCase
|
||||
->assertJsonPath('data.refund.created_by', $admin->nombre_apellido);
|
||||
|
||||
$this->assertNotNull($ticket->fresh()->refunded_at);
|
||||
$this->assertSame(1, $inventory->fresh()->real_stock);
|
||||
$this->assertSame(1, $inventory->fresh()->sold_units);
|
||||
$this->assertSame(1, $inventory->fresh()->refunded_units);
|
||||
$this->assertDatabaseHas('ticket_refunds', [
|
||||
'ticket_id' => $ticket->id,
|
||||
'purchase_item_id' => $purchaseItem->id,
|
||||
@@ -208,6 +213,13 @@ class AdminAppTicketControllerTest extends TestCase
|
||||
'type' => TicketRefund::TYPE_TOTAL,
|
||||
'amount' => '100.00',
|
||||
]);
|
||||
|
||||
$this->postJson("/api/v1/adminapp/tenant/tickets/{$ticket->id}/refund", [
|
||||
'refund_type' => 'total',
|
||||
])->assertUnprocessable();
|
||||
$this->assertSame(1, $inventory->fresh()->real_stock);
|
||||
$this->assertSame(1, $inventory->fresh()->refunded_units);
|
||||
$this->assertSame(1, $purchaseItem->ticketRefunds()->count());
|
||||
}
|
||||
|
||||
public function test_it_partially_refunds_a_ticket_using_the_tenant_percentage(): void
|
||||
@@ -222,6 +234,7 @@ class AdminAppTicketControllerTest extends TestCase
|
||||
$this->grantTicketsMenu($tenant);
|
||||
Sanctum::actingAs($admin);
|
||||
[$ticket, $purchaseItem] = $this->createRefundableTicket($tenant, $admin, '100.00');
|
||||
$inventory = $ticket->sourceCatalogItem->inventory;
|
||||
|
||||
$this->postJson("/api/v1/adminapp/tenant/tickets/{$ticket->id}/refund", [
|
||||
'refund_type' => 'partial',
|
||||
@@ -238,6 +251,61 @@ class AdminAppTicketControllerTest extends TestCase
|
||||
'type' => TicketRefund::TYPE_PARTIAL,
|
||||
'amount' => '25.50',
|
||||
]);
|
||||
$this->assertSame(1, $inventory->fresh()->real_stock);
|
||||
$this->assertSame(1, $inventory->fresh()->refunded_units);
|
||||
}
|
||||
|
||||
public function test_backfill_restores_existing_refunds_before_new_refunds(): void
|
||||
{
|
||||
$tenant = $this->createTenant('ticket-historical-refund');
|
||||
$tenant->update([
|
||||
'allow_ticket_refund' => true,
|
||||
'allow_ticket_total_refund' => true,
|
||||
]);
|
||||
$admin = $this->createAdminAppUser($tenant);
|
||||
$this->grantTicketsMenu($tenant);
|
||||
Sanctum::actingAs($admin);
|
||||
[$historicalTicket, $purchaseItem] = $this->createRefundableTicket($tenant, $admin, '100.00');
|
||||
$inventory = $historicalTicket->sourceCatalogItem->inventory;
|
||||
$inventory->update(['sold_units' => 2]);
|
||||
$purchaseItem->update(['cantidad' => 2, 'total' => '200.00']);
|
||||
$historicalTicket->markAsRefunded();
|
||||
$historicalTicket->save();
|
||||
TicketRefund::query()->create([
|
||||
'ticket_id' => $historicalTicket->id,
|
||||
'purchase_item_id' => $purchaseItem->id,
|
||||
'type' => TicketRefund::TYPE_TOTAL,
|
||||
'amount' => '100.00',
|
||||
]);
|
||||
|
||||
$this->assertSame(0, $inventory->fresh()->refunded_units);
|
||||
$this->assertSame(0, $inventory->fresh()->real_stock);
|
||||
|
||||
Log::shouldReceive('info')->once()->with('inventory.refunded_units_backfill.completed', [
|
||||
'refunds_seen' => 1,
|
||||
'refunds_applied' => 1,
|
||||
'bundles_skipped' => 0,
|
||||
'inventories_updated' => 1,
|
||||
'refunded_units_added' => 1,
|
||||
'real_stock_added' => 1,
|
||||
]);
|
||||
$backfill = require database_path('migrations/2026_09_16_000100_backfill_refunded_units.php');
|
||||
$backfill->up();
|
||||
|
||||
$this->assertSame(1, $inventory->fresh()->refunded_units);
|
||||
$this->assertSame(1, $inventory->fresh()->real_stock);
|
||||
|
||||
$newTicket = $this->createTicket($tenant, $admin, [
|
||||
'source_purchase_item_id' => $purchaseItem->id,
|
||||
'source_catalog_item_id' => $historicalTicket->source_catalog_item_id,
|
||||
]);
|
||||
$this->postJson("/api/v1/adminapp/tenant/tickets/{$newTicket->id}/refund", [
|
||||
'refund_type' => TicketRefund::TYPE_TOTAL,
|
||||
])->assertOk();
|
||||
|
||||
$this->assertSame(2, $inventory->fresh()->sold_units);
|
||||
$this->assertSame(2, $inventory->fresh()->refunded_units);
|
||||
$this->assertSame(2, $inventory->fresh()->real_stock);
|
||||
}
|
||||
|
||||
public function test_it_records_different_refund_types_for_tickets_from_the_same_purchase_item(): void
|
||||
@@ -1089,8 +1157,10 @@ class AdminAppTicketControllerTest extends TestCase
|
||||
/** @return array{Ticket, PurchaseItem} */
|
||||
private function createRefundableTicket(Tenant $tenant, User $admin, string $amount): array
|
||||
{
|
||||
$inventory = Inventory::query()->create(['sold_units' => 1]);
|
||||
$catalogItem = CatalogItem::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'inventory_id' => $inventory->id,
|
||||
'slug' => 'ticket-reembolsable-'.Str::uuid(),
|
||||
'nombre' => 'Ticket reembolsable',
|
||||
'precio' => $amount,
|
||||
|
||||
Reference in New Issue
Block a user