feat(inventory): add refunded_units to inventory model and update related services
This commit is contained in:
@@ -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);
|
||||
|
||||
return $ticket->refresh()->load(self::RELATIONS);
|
||||
});
|
||||
}
|
||||
|
||||
private function restoreInventory(Ticket $ticket): 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()) {
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user