Merge branch 'refactor/inventory_stock' of https://gitea.quo.ar/tbianchini/shopit-back into refactor/inventory_stock

This commit is contained in:
2026-09-29 08:23:09 -03:00
parent c5aeb19735
commit 96378a6c2e
596 changed files with 239 additions and 7622 deletions

View File

@@ -1,18 +0,0 @@
<?php
namespace App\Domains\Commerce\Catalog\Enums;
enum InventoryMovementOperation: string
{
case StockInitialized = 'stock_initialized';
case StockIncreased = 'stock_increased';
case StockDecreased = 'stock_decreased';
case StockReserved = 'stock_reserved';
case StockReleased = 'stock_released';
case PurchaseCommitted = 'purchase_committed';
case StockRefunded = 'stock_refunded';
case EntryStockReserved = 'entry_stock_reserved';
case EntryStockReleased = 'entry_stock_released';
case InventoryReset = 'inventory_reset';
case InventoryTransferred = 'inventory_transferred';
}

View File

@@ -19,7 +19,6 @@ use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;
#[Fillable([
'tenant_code',
@@ -214,14 +213,10 @@ class CatalogItem extends Model
/** @param Builder<CatalogItem> $query */
public function scopeWhereAvailable(Builder $query): Builder
{
$availableInventory = static fn (Builder $inventoryQuery): Builder => Schema::hasColumn('inventories', 'available_stock')
? $inventoryQuery->where('inventories.available_stock', '>', 0)
: $inventoryQuery->whereRaw('inventories.real_stock > inventories.reserved_stock + inventories.entry_reserved_stock');
return $query->where(function (Builder $query): void {
$query->whereNull('catalog_items.sales_end_at')
->orWhere('catalog_items.sales_end_at', '>', now());
})->where(function (Builder $query) use ($availableInventory): void {
})->where(function (Builder $query): void {
$query
->where(function (Builder $unlimitedQuery): void {
$unlimitedQuery
@@ -241,18 +236,20 @@ class CatalogItem extends Model
->whereNull('replaced_by_variant_id')
->whereHas(
'inventory',
$availableInventory
fn (Builder $inventoryQuery): Builder => $inventoryQuery
->whereRaw('inventories.real_stock > inventories.reserved_stock + inventories.entry_reserved_stock')
)
)
->orWhere(function (Builder $directItemQuery) use ($availableInventory): void {
->orWhere(function (Builder $directItemQuery): void {
$directItemQuery
->whereDoesntHave('variants')
->where(function (Builder $inventoryQuery) use ($availableInventory): void {
->where(function (Builder $inventoryQuery): void {
$inventoryQuery
->whereNull('catalog_items.inventory_id')
->orWhereHas(
'inventory',
$availableInventory
fn (Builder $availableInventoryQuery): Builder => $availableInventoryQuery
->whereRaw('inventories.real_stock > inventories.reserved_stock + inventories.entry_reserved_stock')
);
});
});

View File

@@ -2,17 +2,11 @@
namespace App\Domains\Commerce\Catalog\Models;
use App\Domains\Commerce\Catalog\Enums\InventoryMovementOperation;
use App\Domains\Core\Auth\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
#[Fillable([
'sold_units',
@@ -44,7 +38,6 @@ class Inventory extends Model
'reserved_stock' => 'integer',
'entry_reserved_stock' => 'integer',
'real_stock' => 'integer',
'available_stock' => 'integer',
];
}
@@ -66,295 +59,70 @@ class Inventory extends Model
return $this->hasMany(StockReservationLine::class);
}
/** @return HasMany<InventoryMovement, $this> */
public function movements(): HasMany
{
return $this->hasMany(InventoryMovement::class);
}
public function availableStock(): int
{
if (! array_key_exists('available_stock', $this->attributes)) {
return max(0, $this->real_stock - $this->reserved_stock - ($this->entry_reserved_stock ?? 0));
}
return (int) $this->getAttribute('available_stock');
return max(0, $this->real_stock - $this->reserved_stock - $this->entry_reserved_stock);
}
public function reserveEntry(int $amount, bool $tracksInventory): void
{
$this->mutate(
InventoryMovementOperation::EntryStockReserved,
['entry_reserved_stock' => $amount],
function (self $inventory) use ($amount, $tracksInventory): void {
if ($amount < 1 || ($tracksInventory && $inventory->availableStock() < $amount)) {
throw new \InvalidArgumentException('No hay stock disponible para la reserva de entradas.');
}
},
);
if ($amount < 1 || ($tracksInventory && $this->availableStock() < $amount)) {
throw new \InvalidArgumentException('No hay stock disponible para la reserva de entradas.');
}
$this->entry_reserved_stock += $amount;
$this->save();
}
public function releaseEntry(int $amount): void
{
$this->mutate(
InventoryMovementOperation::EntryStockReleased,
['entry_reserved_stock' => -$amount],
function (self $inventory) use ($amount): void {
if ($amount < 1 || $inventory->entry_reserved_stock < $amount) {
throw new \InvalidArgumentException('La cantidad de entradas reservadas no es válida.');
}
},
);
if ($amount < 1 || $this->entry_reserved_stock < $amount) {
throw new \InvalidArgumentException('La cantidad de entradas reservadas no es válida.');
}
$this->entry_reserved_stock -= $amount;
$this->save();
}
public function reserve(int $amount, bool $tracksInventory): void
{
$this->mutate(
InventoryMovementOperation::StockReserved,
['reserved_stock' => $amount],
function (self $inventory) use ($amount, $tracksInventory): void {
if ($amount < 0) {
throw new \InvalidArgumentException('La cantidad a reservar debe ser positiva.');
}
if ($tracksInventory && $inventory->availableStock() < $amount) {
throw new \InvalidArgumentException('No hay suficiente stock disponible para reservar.');
}
},
);
if ($amount < 0) {
throw new \InvalidArgumentException('La cantidad a reservar debe ser positiva.');
}
if ($tracksInventory && $this->availableStock() < $amount) {
throw new \InvalidArgumentException('No hay suficiente stock disponible para reservar.');
}
$this->reserved_stock += $amount;
$this->save();
}
public function release(int $amount): void
{
$this->mutate(
InventoryMovementOperation::StockReleased,
['reserved_stock' => -$amount],
function (self $inventory) use ($amount): void {
if ($amount < 0 || $inventory->reserved_stock < $amount) {
throw new \InvalidArgumentException('La cantidad reservada no es válida.');
}
},
);
if ($amount < 0 || $this->reserved_stock < $amount) {
throw new \InvalidArgumentException('La cantidad reservada no es válida.');
}
$this->reserved_stock -= $amount;
$this->save();
}
public function buy(int $amount, bool $tracksInventory): void
{
$counterDeltas = ['reserved_stock' => -$amount, 'sold_units' => $amount];
if (! array_key_exists('available_stock', $this->attributes) && $tracksInventory) {
$counterDeltas['real_stock'] = -$amount;
if ($amount < 0 || $this->reserved_stock < $amount) {
throw new \InvalidArgumentException('La cantidad reservada no alcanza para confirmar la compra.');
}
$this->mutate(
InventoryMovementOperation::PurchaseCommitted,
$counterDeltas,
function (self $inventory) use ($amount, $tracksInventory): void {
if ($amount < 0 || $inventory->reserved_stock < $amount) {
throw new \InvalidArgumentException('La cantidad reservada no alcanza para confirmar la compra.');
}
if ($tracksInventory && $inventory->availableStock() < 0) {
throw new \InvalidArgumentException('No hay suficiente stock real para confirmar la compra.');
}
},
);
}
public function adjustAvailableStock(
int $delta,
?User $responsibleUser = null,
?string $idempotencyKey = null,
): void {
if ($delta === 0) {
return;
if ($tracksInventory && $this->real_stock - $this->entry_reserved_stock < $amount) {
throw new \InvalidArgumentException('No hay suficiente stock real para confirmar la compra.');
}
$operation = $delta > 0
? InventoryMovementOperation::StockIncreased
: InventoryMovementOperation::StockDecreased;
$this->mutate(
$operation,
['real_stock' => $delta],
function (self $inventory) use ($delta): void {
if ($inventory->real_stock + $delta < 0 || $inventory->availableStock() + $delta < 0) {
throw ValidationException::withMessages([
'stock_difference' => ['El ajuste dejaría el stock en un valor inválido.'],
]);
}
},
$responsibleUser,
$idempotencyKey,
);
}
public function refundStock(int $amount, ?User $responsibleUser = null): void
{
$counterDeltas = ['refunded_units' => $amount];
if (! array_key_exists('available_stock', $this->attributes)) {
$counterDeltas['real_stock'] = $amount;
if ($tracksInventory) {
$this->real_stock -= $amount;
}
$this->mutate(
InventoryMovementOperation::StockRefunded,
$counterDeltas,
function () use ($amount): void {
if ($amount < 1) {
throw new \InvalidArgumentException('La cantidad devuelta debe ser positiva.');
}
},
$responsibleUser,
);
}
public function commitDirectSale(int $amount, bool $tracksInventory = true): void
{
$this->mutate(
InventoryMovementOperation::PurchaseCommitted,
['sold_units' => $amount],
function (self $inventory) use ($amount, $tracksInventory): void {
if ($amount < 1 || ($tracksInventory && $inventory->availableStock() < $amount)) {
throw new \InvalidArgumentException('No hay suficiente stock para confirmar la compra.');
}
},
);
}
public function recordInitialization(?User $responsibleUser = null): void
{
$this->recordCurrentState(InventoryMovementOperation::StockInitialized, $responsibleUser);
}
public function recordTransferInitialization(?User $responsibleUser = null): void
{
$this->recordCurrentState(InventoryMovementOperation::InventoryTransferred, $responsibleUser);
}
/** @param array<string, int> $counterDeltas */
public function transferCounters(array $counterDeltas, ?User $responsibleUser = null): void
{
$counterDeltas = array_filter($counterDeltas, fn (int $delta): bool => $delta !== 0);
if ($counterDeltas === []) {
return;
}
$this->mutate(
InventoryMovementOperation::InventoryTransferred,
$counterDeltas,
function (self $inventory) use ($counterDeltas): void {
foreach ($counterDeltas as $counter => $delta) {
if ((int) $inventory->getAttribute($counter) + $delta < 0) {
throw new \LogicException("El traslado dejaría {$counter} en un valor negativo.");
}
}
},
$responsibleUser,
);
}
private function recordCurrentState(
InventoryMovementOperation $operation,
?User $responsibleUser,
): void {
if (! Schema::hasTable('inventory_movements')) {
return;
}
$this->refresh();
$counterDeltas = array_filter([
'real_stock' => $this->real_stock,
'sold_units' => $this->sold_units,
'reserved_stock' => $this->reserved_stock,
'entry_reserved_stock' => $this->entry_reserved_stock,
'refunded_units' => $this->refunded_units,
], fn (int $delta): bool => $delta !== 0);
$this->movements()->create([
'operation' => $operation,
'available_stock_delta' => $this->availableStock(),
'available_stock_before' => 0,
'available_stock_after' => $this->availableStock(),
'counter_deltas' => $counterDeltas,
'responsible_user_id' => $responsibleUser?->getKey() ?? Auth::id(),
]);
}
public function resetTransactionCounters(?User $responsibleUser = null): void
{
$this->refresh();
$counterDeltas = array_filter([
'sold_units' => -$this->sold_units,
'reserved_stock' => -$this->reserved_stock,
'entry_reserved_stock' => -$this->entry_reserved_stock,
'refunded_units' => -$this->refunded_units,
], fn (int $delta): bool => $delta !== 0);
if ($counterDeltas === []) {
return;
}
$this->mutate(
InventoryMovementOperation::InventoryReset,
$counterDeltas,
static function (): void {},
$responsibleUser,
);
}
/**
* @param array<string, int> $counterDeltas
* @param callable(self): void $validate
*/
private function mutate(
InventoryMovementOperation $operation,
array $counterDeltas,
callable $validate,
?User $responsibleUser = null,
?string $idempotencyKey = null,
): void {
DB::transaction(function () use ($operation, $counterDeltas, $validate, $responsibleUser, $idempotencyKey): void {
/** @var self $inventory */
$inventory = self::query()->lockForUpdate()->findOrFail($this->getKey());
$this->setRawAttributes($inventory->getAttributes(), true);
$recordsMovements = Schema::hasTable('inventory_movements');
if ($recordsMovements && $idempotencyKey !== null) {
$existing = $this->movements()
->where('idempotency_key', $idempotencyKey)
->first();
if ($existing !== null) {
if ($existing->counter_deltas !== $counterDeltas) {
throw ValidationException::withMessages([
'stock_adjustment_id' => ['La operación ya fue utilizada con otro ajuste.'],
]);
}
return;
}
}
$validate($this);
$counterDeltas = array_filter($counterDeltas, fn (int $delta): bool => $delta !== 0);
if ($counterDeltas === []) {
return;
}
$availableBefore = $this->availableStock();
foreach ($counterDeltas as $counter => $delta) {
$this->setAttribute($counter, (int) $this->getAttribute($counter) + $delta);
}
$this->save();
$this->refresh();
$availableAfter = $this->availableStock();
if ($recordsMovements) {
$this->movements()->create([
'operation' => $operation,
'available_stock_delta' => $availableAfter - $availableBefore,
'available_stock_before' => $availableBefore,
'available_stock_after' => $availableAfter,
'counter_deltas' => $counterDeltas,
'responsible_user_id' => $responsibleUser?->getKey() ?? Auth::id(),
'idempotency_key' => $idempotencyKey,
]);
}
});
$this->reserved_stock -= $amount;
$this->sold_units += $amount;
$this->save();
}
}

View File

@@ -1,45 +0,0 @@
<?php
namespace App\Domains\Commerce\Catalog\Models;
use App\Domains\Commerce\Catalog\Enums\InventoryMovementOperation;
use App\Domains\Core\Auth\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'inventory_id',
'operation',
'available_stock_delta',
'available_stock_before',
'available_stock_after',
'counter_deltas',
'responsible_user_id',
'idempotency_key',
])]
class InventoryMovement extends Model
{
protected function casts(): array
{
return [
'operation' => InventoryMovementOperation::class,
'available_stock_delta' => 'integer',
'available_stock_before' => 'integer',
'available_stock_after' => 'integer',
'counter_deltas' => 'array',
];
}
/** @return BelongsTo<Inventory, $this> */
public function inventory(): BelongsTo
{
return $this->belongsTo(Inventory::class);
}
/** @return BelongsTo<User, $this> */
public function responsibleUser(): BelongsTo
{
return $this->belongsTo(User::class, 'responsible_user_id');
}
}

View File

@@ -64,7 +64,6 @@ class CatalogInventoryService
$selection->loadMissing('variants.inventory');
return $selection->variants
->each(fn (Variant $variant) => $variant->setRelation('catalogItem', $selection))
->filter(fn (Variant $variant): bool => $variant->isSellable())
->unique(fn (Variant $variant): string => $variant->inventory_id === null
? 'object:'.spl_object_id($variant->inventory)
@@ -154,7 +153,7 @@ class CatalogInventoryService
if ($operation === 'commit'
&& $requirement['tracks_inventory']
&& $inventory->availableStock() < 0) {
&& $inventory->real_stock - $inventory->entry_reserved_stock < $requiredQuantity) {
throw new \InvalidArgumentException('No hay suficiente stock real para confirmar la compra.');
}
}

View File

@@ -2,6 +2,8 @@
namespace App\Domains\Commerce\Catalog\Services;
use App\Shared\Attachable\Models\Attachment;
use App\Shared\Attachable\Services\AttachmentService;
use App\Domains\Commerce\Catalog\Enums\CatalogItemType;
use App\Domains\Commerce\Catalog\Models\Attribute;
use App\Domains\Commerce\Catalog\Models\CatalogItem;
@@ -9,10 +11,8 @@ use App\Domains\Commerce\Catalog\Models\Category;
use App\Domains\Commerce\Catalog\Models\Inventory;
use App\Domains\Commerce\Catalog\Models\ItemAttribute;
use App\Domains\Commerce\Catalog\Models\Variant;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Event\Models\EventDate;
use App\Shared\Attachable\Models\Attachment;
use App\Shared\Attachable\Services\AttachmentService;
use App\Domains\Core\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
@@ -286,11 +286,9 @@ class CatalogService
int $perPage,
int $page,
): LengthAwarePaginator {
$categoryIds = $this->categoryAndDescendantIds($tenant, $category);
return CatalogItem::query()
->forTenantCatalog($tenant)
->whereIn('category_id', $categoryIds)
->where('category_id', $category->id)
->whereAvailable()
->with([
'attachments',
@@ -308,34 +306,6 @@ class CatalogService
->paginate(perPage: $perPage, pageName: 'page', page: $page);
}
/** @return array<int, int> */
private function categoryAndDescendantIds(Tenant $tenant, Category $category): array
{
$childrenByParent = Category::query()
->where('tenant_code', $tenant->codigo)
->get(['id', 'categoria_id'])
->groupBy('categoria_id');
$categoryIds = [];
$pendingIds = [$category->id];
while ($pendingIds !== []) {
$categoryId = array_shift($pendingIds);
if (isset($categoryIds[$categoryId])) {
continue;
}
$categoryIds[$categoryId] = $categoryId;
foreach ($childrenByParent->get($categoryId, collect()) as $child) {
$pendingIds[] = $child->id;
}
}
return array_values($categoryIds);
}
public function delete(CatalogItem $catalogItem): void
{
DB::transaction(function () use ($catalogItem): void {
@@ -370,12 +340,9 @@ class CatalogService
private function createInventory(int $realStock): Inventory
{
$inventory = Inventory::query()->create([
return Inventory::query()->create([
'real_stock' => $realStock,
]);
$inventory->recordInitialization();
return $inventory;
}
/**

View File

@@ -225,7 +225,7 @@ class StockReservationService
$inventory = $inventories->get($line->inventory_id)
?? throw new \InvalidArgumentException('No se encontró el inventario reservado.');
if ($inventory->reserved_stock < $line->quantity
|| ($line->tracks_inventory && $inventory->availableStock() < 0)) {
|| ($line->tracks_inventory && $inventory->real_stock - $inventory->entry_reserved_stock < $line->quantity)) {
throw new \InvalidArgumentException('La reserva de stock no alcanza para confirmar la compra.');
}
}

View File

@@ -194,7 +194,6 @@ class VariantReplacementService
'entry_reserved_stock' => $sourceInventory->entry_reserved_stock,
'real_stock' => $sourceInventory->real_stock,
]);
$replacementInventory->recordTransferInitialization();
if ($activeLines->isNotEmpty()) {
StockReservationLine::query()
@@ -203,10 +202,7 @@ class VariantReplacementService
}
EntryReservation::query()->where('inventory_id', $sourceInventory->id)
->update(['inventory_id' => $replacementInventory->id]);
$sourceInventory->transferCounters([
'reserved_stock' => -$sourceInventory->reserved_stock,
'entry_reserved_stock' => -$sourceInventory->entry_reserved_stock,
]);
$sourceInventory->update(['reserved_stock' => 0, 'entry_reserved_stock' => 0]);
return $replacementInventory;
}
@@ -240,14 +236,13 @@ class VariantReplacementService
throw new \LogicException('El inventario reservado de la variante es inconsistente.');
}
$transferredCounters = [
'real_stock' => $sourceInventory->real_stock,
'reserved_stock' => $sourceInventory->reserved_stock,
'entry_reserved_stock' => $sourceInventory->entry_reserved_stock,
'sold_units' => $sourceInventory->sold_units,
'refunded_units' => $sourceInventory->refunded_units,
];
$destinationInventory->transferCounters($transferredCounters);
$destinationInventory->update([
'real_stock' => $destinationInventory->real_stock + $sourceInventory->real_stock,
'reserved_stock' => $destinationInventory->reserved_stock + $sourceInventory->reserved_stock,
'entry_reserved_stock' => $destinationInventory->entry_reserved_stock + $sourceInventory->entry_reserved_stock,
'sold_units' => $destinationInventory->sold_units + $sourceInventory->sold_units,
'refunded_units' => $destinationInventory->refunded_units + $sourceInventory->refunded_units,
]);
if ($activeLines->isNotEmpty()) {
StockReservationLine::query()
->whereKey($activeLines->modelKeys())
@@ -255,10 +250,13 @@ class VariantReplacementService
}
EntryReservation::query()->where('inventory_id', $sourceInventory->id)
->update(['inventory_id' => $destinationInventory->id]);
$sourceInventory->transferCounters(array_map(
fn (int $value): int => -$value,
$transferredCounters,
));
$sourceInventory->update([
'real_stock' => 0,
'reserved_stock' => 0,
'entry_reserved_stock' => 0,
'sold_units' => 0,
'refunded_units' => 0,
]);
}
/** @return list<string> */