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> */

View File

@@ -2,6 +2,7 @@
namespace App\Domains\Commerce\Purchase\Controllers;
use App\Shared\Integration\Services\TelepagosIntegrationService;
use App\Domains\Commerce\Purchase\Models\Purchase;
use App\Domains\Commerce\Purchase\Requests\PaymentIntentRequest;
use App\Domains\Commerce\Purchase\Requests\StartCheckoutRequest;
@@ -12,7 +13,6 @@ use App\Domains\Commerce\Purchase\Services\CheckoutService;
use App\Domains\Commerce\Purchase\Services\PurchaseStateGuard;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Http\Controllers\Controller;
use App\Shared\Integration\Services\TelepagosIntegrationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
@@ -151,14 +151,11 @@ class PurchaseController extends Controller
}
$compra->refresh();
$compra->loadMissing('event');
$totalAmount = (float) $compra->total;
if ($method === 'transfer') {
$telepagosService = new TelepagosIntegrationService;
$compra->event
? $telepagosService->forEvent($compra->event)
: $telepagosService->forTenant($tenant->codigo);
$telepagosService->forTenant($tenant->codigo);
try {
$accountInfo = $telepagosService->getAccountInfo();
@@ -194,9 +191,7 @@ class PurchaseController extends Controller
if ($method === 'qr') {
$telepagosService = new TelepagosIntegrationService;
$compra->event
? $telepagosService->forEvent($compra->event)
: $telepagosService->forTenant($tenant->codigo);
$telepagosService->forTenant($tenant->codigo);
try {
Log::channel('telepagos')->info('Generating Telepagos QR.', [

View File

@@ -2,14 +2,13 @@
namespace App\Domains\Commerce\Purchase\Models;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Commerce\Cart\Models\Cart;
use App\Domains\Commerce\Catalog\Models\StockReservation;
use App\Domains\Commerce\Purchase\Events\PurchasePaid;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Event\Models\Event;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use App\Shared\Logging\Models\Concerns\LogsValueChanges;
use App\Domains\Commerce\Purchase\Events\PurchasePaid;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -22,7 +21,6 @@ use Illuminate\Support\Facades\DB;
#[Fillable([
'cart_id',
'stock_reservation_id',
'event_id',
'tenant_codigo',
'user_id',
'status',
@@ -151,7 +149,6 @@ class Purchase extends Model
return [
'cart_id' => 'integer',
'stock_reservation_id' => 'integer',
'event_id' => 'integer',
'user_id' => 'integer',
'total' => 'decimal:2',
];
@@ -165,12 +162,6 @@ class Purchase extends Model
return $this->belongsTo(Tenant::class, 'tenant_codigo', 'codigo');
}
/** @return BelongsTo<Event, $this> */
public function event(): BelongsTo
{
return $this->belongsTo(Event::class);
}
/**
* @return BelongsTo<User, $this>
*/

View File

@@ -36,11 +36,11 @@ class PurchaseResource extends JsonResource
=== StorefrontWebsiteType::CHECKOUT_SUMMARY_EVENT;
/** @var Event|null $checkoutEvent */
$checkoutEvent = $usesEventSummary
? ($this->event ?? $items
? $items
->map(fn (PurchaseItem $item) => $item->sourceCatalogItem?->event)
->filter()
->unique('id')
->first())
->first()
: null;
$subtotal = $items->isNotEmpty()
@@ -62,7 +62,6 @@ class PurchaseResource extends JsonResource
return [
'id' => $this->id,
'cart_id' => $this->cart_id,
'event_id' => $this->event_id,
'tenant_codigo' => $this->tenant_codigo,
'user_id' => $this->user_id,
'created_at' => $this->created_at,

View File

@@ -14,7 +14,6 @@ class PurchaseResponseLoader
=== StorefrontWebsiteType::CHECKOUT_SUMMARY_EVENT;
$relations = [
'tenant',
'event.attachment',
'items.sourceCatalogItem.event.attachment',
'stockReservation',
];

View File

@@ -206,7 +206,6 @@ class StartCheckoutService
fn (array $line): float => $line['selection']->getPrice() * $line['quantity'],
),
$cart->getKey(),
$cartItems->first()?->catalogItem?->event_id,
);
$cart->update(['current_purchase_id' => $purchase->getKey()]);
$this->reservations->attachToPurchase($cart, $purchase, $this->checkoutExpiration());
@@ -274,7 +273,6 @@ class StartCheckoutService
$purchaseData,
$cart->getTotalAmount(),
$cart->getKey(),
$cartItems->first()?->catalogItem?->event_id,
);
$cart->update(['current_purchase_id' => $purchase->getKey()]);
$this->reservations->attachToPurchase($cart, $purchase, $this->checkoutExpiration());
@@ -412,12 +410,10 @@ class StartCheckoutService
array $purchaseData,
float $total,
?int $cartId,
?int $eventId,
): Purchase {
return Purchase::query()->create([
...$purchaseData,
'cart_id' => $cartId,
'event_id' => $eventId,
'tenant_codigo' => $tenant->codigo,
'user_id' => $userId,
'status' => Purchase::STATUS_CREATED,

View File

@@ -2,7 +2,6 @@
namespace App\Domains\Commerce\Purchase\Services;
use App\Domains\Commerce\Catalog\Models\Inventory;
use App\Domains\Commerce\Purchase\Models\Purchase;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Collection;
@@ -70,12 +69,15 @@ class TenantTransactionResetService
'users_preserved' => DB::table('users')->where('tenant_codigo', $tenantCode)->count(),
];
Inventory::query()
->whereKey($scope['inventory_ids'])
->orderBy('id')
->lockForUpdate()
->get()
->each(fn (Inventory $inventory) => $inventory->resetTransactionCounters());
DB::table('inventories')
->whereIn('id', $scope['inventory_ids'])
->update([
'real_stock' => DB::raw('real_stock + sold_units - refunded_units'),
'reserved_stock' => 0,
'entry_reserved_stock' => 0,
'sold_units' => 0,
'refunded_units' => 0,
]);
return $summary;
});

View File

@@ -2,9 +2,8 @@
namespace App\Domains\Core\Client\Models;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Event\Models\Event;
use App\Shared\Integration\Models\ClientIntegration;
use App\Domains\Core\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
@@ -23,12 +22,6 @@ class Client extends Model
return $this->hasMany(Tenant::class);
}
/** @return HasMany<Event, $this> */
public function events(): HasMany
{
return $this->hasMany(Event::class);
}
/** @return HasMany<ClientIntegration, $this> */
public function integrations(): HasMany
{

View File

@@ -2,7 +2,6 @@
namespace App\Domains\Ticketing\Desfile\Services;
use App\Domains\Commerce\Catalog\Models\Inventory;
use DateTimeInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
@@ -394,22 +393,14 @@ class InvitationPurchaseProvisioner
$inventory = DB::table('inventories')->where('id', $variant->inventory_id)->lockForUpdate()->first();
$available = $inventory?->available_stock
?? ($inventory === null ? 0 : $inventory->real_stock - $inventory->reserved_stock - ($inventory->entry_reserved_stock ?? 0));
if ($available < 1) {
if ($inventory === null || $inventory->real_stock < 1 || $inventory->reserved_stock > 0 || ($inventory->entry_reserved_stock ?? 0) > 0) {
throw new RuntimeException("El asiento {$variant->descripcion} ya no está disponible.");
}
if (property_exists($inventory, 'available_stock')) {
Inventory::query()->findOrFail($inventory->id)->commitDirectSale(1);
} else {
// This provisioner is also used by historical migrations that run
// before generated availability and the movement ledger exist.
DB::table('inventories')->where('id', $inventory->id)->update([
'real_stock' => $inventory->real_stock - 1,
'sold_units' => $inventory->sold_units + 1,
]);
}
DB::table('inventories')->where('id', $inventory->id)->update([
'real_stock' => $inventory->real_stock - 1,
'sold_units' => $inventory->sold_units + 1,
]);
$reservationId = DB::table('compras')->where('id', $purchaseId)->value('stock_reservation_id');
if ($reservationId === null) {

View File

@@ -3,7 +3,6 @@
namespace App\Domains\Ticketing\Event\Models;
use App\Domains\Commerce\Catalog\Models\CatalogItem;
use App\Domains\Core\Client\Models\Client;
use App\Domains\Core\Tenant\Models\SocialMedia;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Ticket\Models\Ticket;
@@ -15,14 +14,14 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['client_id', 'tenant_code', 'slug', 'event_category_id', 'title', 'subtitle', 'description', 'location', 'exact_location', 'date_text', 'published_at', 'attachment_id'])]
#[Fillable(['tenant_code', 'slug', 'event_category_id', 'title', 'subtitle', 'description', 'location', 'exact_location', 'date_text', 'published_at', 'attachment_id'])]
class Event extends Model
{
use HasFactory;
protected function casts(): array
{
return ['client_id' => 'integer', 'published_at' => 'datetime', 'exact_location' => 'array'];
return ['published_at' => 'datetime', 'exact_location' => 'array'];
}
/** @return BelongsTo<Tenant, $this> */
@@ -31,17 +30,6 @@ class Event extends Model
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
}
/** @return BelongsTo<Client, $this> */
public function client(): BelongsTo
{
return $this->belongsTo(Client::class);
}
public function effectiveClient(): Client
{
return $this->client ?? $this->tenant->client;
}
/** @return BelongsTo<EventCategory, $this> */
public function eventCategory(): BelongsTo
{

View File

@@ -28,7 +28,6 @@ class AccommodationController extends Controller
$this->accommodationService->upsertMany(
$tenant,
$request->validated('variants'),
$request->validated('stock_adjustment_id'),
)
);
}

View File

@@ -29,7 +29,6 @@ class EntryController extends Controller
$entries = $this->entryService->upsertMany(
$tenant,
$request->validated('entries'),
$request->validated('stock_adjustment_id'),
);
return EntryResource::collection($entries)

View File

@@ -29,7 +29,6 @@ class FoodController extends Controller
$this->foodService->upsertMany(
$tenant,
$request->validated('variants'),
$request->validated('stock_adjustment_id'),
)
);
}
@@ -40,7 +39,6 @@ class FoodController extends Controller
$this->foodService->updateHistoricalStock(
$request->user()->tenant()->firstOrFail(),
$request->validated('variants'),
$request->validated('stock_adjustment_id'),
)
);
}

View File

@@ -28,7 +28,6 @@ class MerchandiseController extends Controller
$items = $this->merchandiseService->upsertMany(
$tenant,
$request->validated('items'),
$request->validated('stock_adjustment_id'),
);
return MerchandiseResource::collection($items)

View File

@@ -16,10 +16,9 @@ class UpdateHistoricalFoodStockRequest extends FormRequest
{
return [
'variants' => ['required', 'array', 'min:1', 'max:500'],
'stock_adjustment_id' => ['nullable', 'uuid'],
'variants.*' => ['required', 'array:id,stock_difference'],
'variants.*' => ['required', 'array:id,stock'],
'variants.*.id' => ['required', 'integer', 'distinct'],
'variants.*.stock_difference' => ['required', 'integer'],
'variants.*.stock' => ['required', 'integer', 'min:0'],
];
}
}

View File

@@ -3,7 +3,6 @@
namespace App\Domains\Ticketing\FiestaFutbolInfantil\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;
class UpsertAccommodationVariantsRequest extends FormRequest
{
@@ -17,42 +16,12 @@ class UpsertAccommodationVariantsRequest extends FormRequest
{
return [
'variants' => ['required', 'array', 'min:1', 'max:500'],
'stock_adjustment_id' => ['nullable', 'uuid'],
'variants.*' => ['required', 'array:id,title,description,stock,stock_difference,price'],
'variants.*' => ['required', 'array:id,title,description,stock,price'],
'variants.*.id' => ['sometimes', 'nullable', 'integer', 'distinct'],
'variants.*.title' => ['required', 'string', 'max:255'],
'variants.*.description' => ['sometimes', 'nullable', 'string'],
'variants.*.stock' => ['sometimes', 'integer', 'min:0'],
'variants.*.stock_difference' => ['sometimes', 'integer'],
'variants.*.stock' => ['required', 'integer', 'min:0'],
'variants.*.price' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
];
}
/** @return array<int, callable> */
public function after(): array
{
return [
function (Validator $validator): void {
foreach ($this->input('variants', []) as $index => $variant) {
if (! is_array($variant)) {
continue;
}
if (isset($variant['id']) && ! array_key_exists('stock_difference', $variant)) {
$validator->errors()->add(
"variants.{$index}.stock_difference",
'La diferencia de stock es obligatoria al actualizar una variante.',
);
}
if (! isset($variant['id']) && ! array_key_exists('stock', $variant)) {
$validator->errors()->add(
"variants.{$index}.stock",
'El stock inicial es obligatorio al crear una variante.',
);
}
}
},
];
}
}

View File

@@ -20,8 +20,7 @@ class UpsertEntriesRequest extends FormRequest
return [
'entries' => ['required', 'array', 'min:1', 'max:100'],
'stock_adjustment_id' => ['nullable', 'uuid'],
'entries.*' => ['required', 'array:id,title,description,event_date_ids,stock,stock_difference,price'],
'entries.*' => ['required', 'array:id,title,description,event_date_ids,stock,price'],
'entries.*.id' => [
'sometimes',
'nullable',
@@ -47,8 +46,7 @@ class UpsertEntriesRequest extends FormRequest
fn ($query) => $query->where('tenant_code', $tenantCode)
),
],
'entries.*.stock' => ['sometimes', 'integer', 'min:0'],
'entries.*.stock_difference' => ['sometimes', 'integer'],
'entries.*.stock' => ['required', 'integer', 'min:0'],
'entries.*.price' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
];
}
@@ -63,20 +61,6 @@ class UpsertEntriesRequest extends FormRequest
continue;
}
if (isset($entry['id']) && ! array_key_exists('stock_difference', $entry)) {
$validator->errors()->add(
"entries.{$index}.stock_difference",
'La diferencia de stock es obligatoria al actualizar una entrada.',
);
}
if (! isset($entry['id']) && ! array_key_exists('stock', $entry)) {
$validator->errors()->add(
"entries.{$index}.stock",
'El stock inicial es obligatorio al crear una entrada.',
);
}
$dateIds = $entry['event_date_ids'] ?? [];
if (! is_array($dateIds)) {

View File

@@ -20,8 +20,7 @@ class UpsertFoodVariantsRequest extends FormRequest
return [
'variants' => ['required', 'array', 'min:1', 'max:500'],
'stock_adjustment_id' => ['nullable', 'uuid'],
'variants.*' => ['required', 'array:id,event_date_id,schedule,service,description,stock,stock_difference,price'],
'variants.*' => ['required', 'array:id,event_date_id,schedule,service,description,stock,price'],
'variants.*.id' => ['sometimes', 'nullable', 'integer', 'distinct'],
'variants.*.event_date_id' => [
'required',
@@ -33,8 +32,7 @@ class UpsertFoodVariantsRequest extends FormRequest
'variants.*.schedule' => ['required', 'string', 'max:255'],
'variants.*.service' => ['required', 'string', 'max:255'],
'variants.*.description' => ['sometimes', 'nullable', 'string'],
'variants.*.stock' => ['sometimes', 'integer', 'min:0'],
'variants.*.stock_difference' => ['sometimes', 'integer'],
'variants.*.stock' => ['required', 'integer', 'min:0'],
'variants.*.price' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
];
}
@@ -51,20 +49,6 @@ class UpsertFoodVariantsRequest extends FormRequest
continue;
}
if (isset($variant['id']) && ! array_key_exists('stock_difference', $variant)) {
$validator->errors()->add(
"variants.{$index}.stock_difference",
'La diferencia de stock es obligatoria al actualizar una variante.',
);
}
if (! isset($variant['id']) && ! array_key_exists('stock', $variant)) {
$validator->errors()->add(
"variants.{$index}.stock",
'El stock inicial es obligatorio al crear una variante.',
);
}
$key = implode('|', [
$variant['event_date_id'] ?? '',
mb_strtolower(trim((string) ($variant['schedule'] ?? ''))),

View File

@@ -4,7 +4,6 @@ namespace App\Domains\Ticketing\FiestaFutbolInfantil\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;
class UpsertMerchandiseRequest extends FormRequest
{
@@ -40,49 +39,12 @@ class UpsertMerchandiseRequest extends FormRequest
'items.*.description' => ['sometimes', 'nullable', 'string'],
'items.*.max_units_per_user' => ['required', 'integer', 'min:1'],
'items.*.variants' => ['required', 'array', 'min:1', 'max:500'],
'stock_adjustment_id' => ['nullable', 'uuid'],
'items.*.variants.*' => ['required', 'array:id,color,size,stock,stock_difference,price'],
'items.*.variants.*' => ['required', 'array:id,color,size,stock,price'],
'items.*.variants.*.id' => ['sometimes', 'nullable', 'integer', 'distinct'],
'items.*.variants.*.color' => ['required', 'string', 'max:255'],
'items.*.variants.*.size' => ['required', 'string', 'max:255'],
'items.*.variants.*.stock' => ['sometimes', 'integer', 'min:0'],
'items.*.variants.*.stock_difference' => ['sometimes', 'integer'],
'items.*.variants.*.stock' => ['required', 'integer', 'min:0'],
'items.*.variants.*.price' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
];
}
/** @return array<int, callable> */
public function after(): array
{
return [
function (Validator $validator): void {
foreach ($this->input('items', []) as $itemIndex => $item) {
if (! is_array($item)) {
continue;
}
foreach ($item['variants'] ?? [] as $variantIndex => $variant) {
if (! is_array($variant)) {
continue;
}
$prefix = "items.{$itemIndex}.variants.{$variantIndex}";
if (isset($variant['id']) && ! array_key_exists('stock_difference', $variant)) {
$validator->errors()->add(
"{$prefix}.stock_difference",
'La diferencia de stock es obligatoria al actualizar una variante.',
);
}
if (! isset($variant['id']) && ! array_key_exists('stock', $variant)) {
$validator->errors()->add(
"{$prefix}.stock",
'El stock inicial es obligatorio al crear una variante.',
);
}
}
}
},
];
}
}

View File

@@ -37,7 +37,7 @@ class AccommodationResource extends JsonResource
'title' => $options->get($value)?->label ?? $value,
'value' => $value,
'description' => $variant->descripcion,
'stock' => $variant->inventory->availableStock(),
'stock' => $variant->inventory->real_stock,
'price' => number_format($variant->getPrice(), 2, '.', ''),
];
})->values(),

View File

@@ -33,7 +33,7 @@ class EntryResource extends JsonResource
'title' => $this->nombre,
'description' => $this->descripcion,
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'stock' => $variant->inventory->availableStock(),
'stock' => $variant->inventory->real_stock,
'price' => $this->precio,
];
}

View File

@@ -81,7 +81,7 @@ class FoodResource extends JsonResource
'schedule' => $values->get('horario'),
'service' => $values->get('servicio'),
'description' => $variant->descripcion,
'stock' => $variant->inventory->availableStock(),
'stock' => $variant->inventory->real_stock,
'price' => number_format($variant->getPrice(), 2, '.', ''),
];
}

View File

@@ -44,7 +44,7 @@ class MerchandiseResource extends JsonResource
'color_value' => $colorValue,
'size' => $sizeOptions->get($sizeValue)?->label ?? $sizeValue,
'size_value' => $sizeValue,
'stock' => $variant->inventory->availableStock(),
'stock' => $variant->inventory->real_stock,
'price' => number_format($variant->getPrice(), 2, '.', ''),
];
})->values(),

View File

@@ -39,9 +39,9 @@ class AccommodationService
/**
* @param array<int, array<string, mixed>> $variants
*/
public function upsertMany(Tenant $tenant, array $variants, ?string $stockAdjustmentId = null): CatalogItem
public function upsertMany(Tenant $tenant, array $variants): CatalogItem
{
return DB::transaction(function () use ($tenant, $variants, $stockAdjustmentId): CatalogItem {
return DB::transaction(function () use ($tenant, $variants): CatalogItem {
$attribute = $this->attribute($tenant);
$accommodation = $this->accommodation($tenant, $variants);
$itemAttribute = $accommodation->itemAttributes()->firstOrCreate(
@@ -70,7 +70,7 @@ class AccommodationService
if ($variant === null) {
$this->createVariant($attribute, $accommodation, $itemAttribute, $data);
} else {
$this->updateVariant($attribute, $variant, $itemAttribute, $data, $index, $stockAdjustmentId);
$this->updateVariant($attribute, $variant, $itemAttribute, $data, $index);
}
}
@@ -169,7 +169,7 @@ class AccommodationService
'title' => trim($variant['title']),
'value' => $this->valueCode($variant['title']),
'description' => $variant['description'] ?? null,
...(array_key_exists('stock', $variant) ? ['stock' => (int) $variant['stock']] : []),
'stock' => (int) $variant['stock'],
])->all();
}
@@ -212,7 +212,6 @@ class AccommodationService
$this->createOption($attribute, $data['value'], $data['title']);
$inventory = Inventory::query()->create(['real_stock' => $data['stock']]);
$inventory->recordInitialization();
$variant = $accommodation->variants()->create([
'inventory_id' => $inventory->id,
'descripcion' => $data['description'],
@@ -231,13 +230,20 @@ class AccommodationService
ItemAttribute $itemAttribute,
array $data,
int $index,
?string $stockAdjustmentId,
): void {
$inventory = Inventory::query()
->whereKey($variant->inventory_id)
->lockForUpdate()
->firstOrFail();
if ($data['stock'] < $inventory->reserved_stock) {
throw ValidationException::withMessages([
"variants.{$index}.stock" => [
'El stock no puede ser menor que la cantidad actualmente reservada.',
],
]);
}
$definition = $variant->definitions
->firstWhere('item_attribute_id', $itemAttribute->id);
$option = $definition === null
@@ -257,10 +263,7 @@ class AccommodationService
'descripcion' => $data['description'],
'precio' => $data['price'],
]);
$inventory->adjustAvailableStock(
(int) $data['stock_difference'],
idempotencyKey: $stockAdjustmentId,
);
$inventory->update(['real_stock' => $data['stock']]);
$variant->definitions()->updateOrCreate(
['item_attribute_id' => $itemAttribute->id],
['value' => $data['value']],

View File

@@ -43,18 +43,18 @@ class EntryService
* @param array<int, array<string, mixed>> $entries
* @return Collection<int, CatalogItem>
*/
public function upsertMany(Tenant $tenant, array $entries, ?string $stockAdjustmentId = null): Collection
public function upsertMany(Tenant $tenant, array $entries): Collection
{
return DB::transaction(function () use ($tenant, $entries, $stockAdjustmentId): Collection {
return DB::transaction(function () use ($tenant, $entries): Collection {
$reservedSlugs = [];
$category = Category::query()->firstOrCreate([
'tenant_code' => $tenant->codigo,
'nombre' => 'Entradas',
]);
return collect($entries)->map(function (array $entry, int $index) use ($tenant, $category, $stockAdjustmentId, &$reservedSlugs): CatalogItem {
return collect($entries)->map(function (array $entry, int $index) use ($tenant, $category, &$reservedSlugs): CatalogItem {
if (isset($entry['id'])) {
return $this->update($tenant, $category, $entry, $index, $stockAdjustmentId);
return $this->update($tenant, $category, $entry, $index);
}
$slug = $this->uniqueSlug($tenant, $entry['title'], $reservedSlugs);
@@ -92,7 +92,7 @@ class EntryService
}
/** @param array<string, mixed> $entry */
private function update(Tenant $tenant, Category $category, array $entry, int $index, ?string $stockAdjustmentId): CatalogItem
private function update(Tenant $tenant, Category $category, array $entry, int $index): CatalogItem
{
$catalogItem = CatalogItem::query()
->whereKey($entry['id'])
@@ -121,6 +121,14 @@ class EntryService
->lockForUpdate()
->firstOrFail();
if ((int) $entry['stock'] < $inventory->reserved_stock) {
throw ValidationException::withMessages([
"entries.{$index}.stock" => [
'El stock no puede ser menor que la cantidad actualmente reservada.',
],
]);
}
$eventDateIds = collect($entry['event_date_ids'])
->map(fn ($id): int => (int) $id)
->unique()
@@ -141,10 +149,7 @@ class EntryService
$catalogItem->itemAttributes()
->whereHas('attribute', fn ($query) => $query->where('codigo', 'event_date'))
->update(['allow_multi_select' => true]);
$inventory->adjustAvailableStock(
(int) $entry['stock_difference'],
idempotencyKey: $stockAdjustmentId,
);
$inventory->update(['real_stock' => $entry['stock']]);
return $catalogItem->load([
'variants.inventory',

View File

@@ -11,9 +11,9 @@ use App\Domains\Commerce\Catalog\Models\Inventory;
use App\Domains\Commerce\Catalog\Models\ItemAttribute;
use App\Domains\Commerce\Catalog\Models\Variant;
use App\Domains\Commerce\Catalog\Services\CatalogService;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Event\Enums\EventDateStatus;
use App\Domains\Ticketing\Event\Models\EventDate;
use App\Domains\Core\Tenant\Models\Tenant;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
@@ -50,9 +50,9 @@ class FoodService
/**
* @param array<int, array<string, mixed>> $variants
*/
public function upsertMany(Tenant $tenant, array $variants, ?string $stockAdjustmentId = null): CatalogItem
public function upsertMany(Tenant $tenant, array $variants): CatalogItem
{
return DB::transaction(function () use ($tenant, $variants, $stockAdjustmentId): CatalogItem {
return DB::transaction(function () use ($tenant, $variants): CatalogItem {
$attributes = $this->attributes($tenant);
$food = $this->food($tenant, $variants);
$itemAttributes = $this->itemAttributes($food, $attributes);
@@ -85,7 +85,7 @@ class FoodService
if ($variant === null) {
$this->createVariant($food, $itemAttributes, $data);
} else {
$this->updateVariant($variant, $itemAttributes, $data, $index, $stockAdjustmentId);
$this->updateVariant($variant, $itemAttributes, $data, $index);
}
}
@@ -113,11 +113,11 @@ class FoodService
}
/**
* @param array<int, array{id: int, stock_difference: int}> $variants
* @param array<int, array{id: int, stock: int}> $variants
*/
public function updateHistoricalStock(Tenant $tenant, array $variants, ?string $stockAdjustmentId = null): CatalogItem
public function updateHistoricalStock(Tenant $tenant, array $variants): CatalogItem
{
return DB::transaction(function () use ($tenant, $variants, $stockAdjustmentId): CatalogItem {
return DB::transaction(function () use ($tenant, $variants): CatalogItem {
$food = CatalogItem::query()
->forTenantCatalog($tenant)
->where('slug', 'comida')
@@ -142,11 +142,17 @@ class FoodService
]);
}
$stock = (int) $data['stock'];
$inventory = $this->inventoryForHistoricalStockUpdate($variant);
$inventory->adjustAvailableStock(
(int) $data['stock_difference'],
idempotencyKey: $stockAdjustmentId,
);
if ($stock < $inventory->reserved_stock) {
throw ValidationException::withMessages([
"variants.{$index}.stock" => [
'El stock no puede ser menor que la cantidad actualmente reservada.',
],
]);
}
$inventory->update(['real_stock' => $stock]);
}
return $this->current($tenant) ?? $food;
@@ -175,7 +181,6 @@ class FoodService
'reserved_stock' => 0,
'real_stock' => $inventory->real_stock,
]);
$historicalInventory->recordTransferInitialization();
$variant->update(['inventory_id' => $historicalInventory->getKey()]);
return $historicalInventory;
@@ -296,7 +301,7 @@ class FoodService
'schedule' => $schedule->value,
'service' => $service->value,
'description' => (string) ($variant['description'] ?? ''),
...(array_key_exists('stock', $variant) ? ['stock' => (int) $variant['stock']] : []),
'stock' => (int) $variant['stock'],
];
})->all();
}
@@ -379,7 +384,6 @@ class FoodService
private function createVariant(CatalogItem $food, Collection $itemAttributes, array $data): void
{
$inventory = Inventory::query()->create(['real_stock' => $data['stock']]);
$inventory->recordInitialization();
$variant = $food->variants()->create([
'event_date_id' => $data['event_date_id'],
'inventory_id' => $inventory->id,
@@ -396,23 +400,27 @@ class FoodService
Collection $itemAttributes,
array $data,
int $index,
?string $stockAdjustmentId,
): void {
$inventory = Inventory::query()
->whereKey($variant->inventory_id)
->lockForUpdate()
->firstOrFail();
if ($data['stock'] < $inventory->reserved_stock) {
throw ValidationException::withMessages([
"variants.{$index}.stock" => [
'El stock no puede ser menor que la cantidad actualmente reservada.',
],
]);
}
$variant->update([
'event_date_id' => $data['event_date_id'],
'descripcion' => $data['description'],
'precio' => $data['price'],
]);
$variant->eventDates()->sync([$data['event_date_id']]);
$inventory->adjustAvailableStock(
(int) $data['stock_difference'],
idempotencyKey: $stockAdjustmentId,
);
$inventory->update(['real_stock' => $data['stock']]);
$this->syncDefinitions($variant, $itemAttributes, $data);
}

View File

@@ -43,9 +43,9 @@ class MerchandiseService
* @param array<int, array<string, mixed>> $items
* @return Collection<int, CatalogItem>
*/
public function upsertMany(Tenant $tenant, array $items, ?string $stockAdjustmentId = null): Collection
public function upsertMany(Tenant $tenant, array $items): Collection
{
return DB::transaction(function () use ($tenant, $items, $stockAdjustmentId): Collection {
return DB::transaction(function () use ($tenant, $items): Collection {
$attributes = $this->attributes($tenant);
$category = Category::query()->firstOrCreate([
'tenant_code' => $tenant->codigo,
@@ -57,7 +57,6 @@ class MerchandiseService
$tenant,
$attributes,
$category,
$stockAdjustmentId,
&$reservedSlugs,
): CatalogItem {
$item = isset($data['id'])
@@ -102,7 +101,7 @@ class MerchandiseService
if ($variant === null) {
$this->createVariant($item, $itemAttributes, $variantData);
} else {
$this->updateVariant($variant, $itemAttributes, $variantData, $index, $variantIndex, $stockAdjustmentId);
$this->updateVariant($variant, $itemAttributes, $variantData, $index, $variantIndex);
}
}
@@ -245,7 +244,7 @@ class MerchandiseService
...$variant,
'color' => $color->value,
'size' => $size->value,
...(array_key_exists('stock', $variant) ? ['stock' => (int) $variant['stock']] : []),
'stock' => (int) $variant['stock'],
];
})->all();
}
@@ -343,7 +342,6 @@ class MerchandiseService
array $data,
): void {
$inventory = Inventory::query()->create(['real_stock' => $data['stock']]);
$inventory->recordInitialization();
$variant = $item->variants()->create([
'inventory_id' => $inventory->id,
'precio' => $data['price'],
@@ -361,18 +359,22 @@ class MerchandiseService
array $data,
int $itemIndex,
int $variantIndex,
?string $stockAdjustmentId,
): void {
$inventory = Inventory::query()
->whereKey($variant->inventory_id)
->lockForUpdate()
->firstOrFail();
if ($data['stock'] < $inventory->reserved_stock) {
throw ValidationException::withMessages([
"items.{$itemIndex}.variants.{$variantIndex}.stock" => [
'El stock no puede ser menor que la cantidad actualmente reservada.',
],
]);
}
$variant->update(['precio' => $data['price']]);
$inventory->adjustAvailableStock(
(int) $data['stock_difference'],
idempotencyKey: $stockAdjustmentId,
);
$inventory->update(['real_stock' => $data['stock']]);
$this->syncDefinitions($variant, $itemAttributes, $data);
}

View File

@@ -228,13 +228,13 @@ class AdminAppTicketService
'amount' => number_format($refundAmount, 2, '.', ''),
]);
$this->restoreInventory($ticket, $purchaseItem, $createdBy);
$this->restoreInventory($ticket, $purchaseItem);
return $ticket->refresh()->load(self::RELATIONS);
});
}
private function restoreInventory(Ticket $ticket, PurchaseItem $purchaseItem, ?User $createdBy): void
private function restoreInventory(Ticket $ticket, PurchaseItem $purchaseItem): void
{
$catalogItem = $ticket->sourceCatalogItem;
if ($catalogItem === null) {
@@ -272,7 +272,11 @@ class AdminAppTicketService
throw ValidationException::withMessages(['ticket' => 'No se encontró el inventario del ticket.']);
}
$inventory->refundStock(1, $createdBy);
if ($catalogItem->inventory_policy === InventoryPolicy::Tracked) {
$inventory->real_stock++;
}
$inventory->refunded_units++;
$inventory->save();
}
private function refundedAmountForPurchaseItem(PurchaseItem $purchaseItem): float

View File

@@ -2,7 +2,6 @@
namespace App\Domains\Ticketing\Ticket\Services;
use App\Domains\Commerce\Catalog\Models\Inventory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use RuntimeException;
@@ -65,9 +64,14 @@ class BackfillRefundedUnitsService
}, 'refunds.id', 'id');
foreach ($counts as $inventoryId => $count) {
$inventory = Inventory::query()->lockForUpdate()->find($inventoryId)
?? throw new RuntimeException("No se encontró el inventario {$inventoryId} para reponerlo.");
$inventory->refundStock($count['refunded']);
$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'));
@@ -78,8 +82,7 @@ class BackfillRefundedUnitsService
'bundles_skipped' => $bundlesSkipped,
'inventories_updated' => count($counts),
'refunded_units_added' => $refundedUnitsAdded,
'real_stock_added' => 0,
'available_stock_added' => $refundedUnitsAdded,
'real_stock_added' => array_sum(array_column($counts, 'stock')),
];
});

View File

@@ -3,12 +3,11 @@
namespace App\Shared\Integration\Services;
use App\Domains\Core\Client\Models\Client;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Event\Models\Event;
use App\Shared\Integration\Models\AdminWebsiteTypeIntegration;
use App\Shared\Integration\Models\ClientIntegration;
use App\Shared\Integration\Models\Integration;
use App\Shared\Integration\Models\IntegrationInstance;
use App\Shared\Integration\Models\AdminWebsiteTypeIntegration;
use App\Domains\Core\Tenant\Models\Tenant;
use Exception;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
@@ -87,17 +86,6 @@ abstract class BaseIntegrationService
return $this;
}
public function forEvent(Event $event): self
{
$event->loadMissing(['client', 'tenant.client']);
$this->tenant = $event->tenant;
$this->tenantCode = $event->tenant_code;
$this->clientContext = $event->effectiveClient();
$this->loadIntegration();
return $this;
}
/**
* Load the integration definition and its effective instance configuration.
*

View File

@@ -3,9 +3,8 @@
namespace App\Shared\Integration\Services;
use App\Domains\Core\Client\Models\Client;
use App\Domains\Core\Tenant\Models\AdminWebsiteType;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Event\Models\Event;
use App\Domains\Core\Tenant\Models\AdminWebsiteType;
use Exception;
use Illuminate\Contracts\Mail\Factory as MailFactory;
use Illuminate\Contracts\Mail\Mailer;
@@ -40,7 +39,14 @@ class MailService extends BaseIntegrationService
public function forTenant(string $tenantCode): self
{
parent::forTenant($tenantCode);
$this->configureMailer();
if ($this->integrationInstance) {
$this->mailer = $this->resolveMailer();
$this->usesInstanceMailer = true;
} else {
$this->mailer = $this->mailFactory->mailer();
$this->usesInstanceMailer = false;
}
return $this;
}
@@ -49,30 +55,16 @@ class MailService extends BaseIntegrationService
{
parent::forClient($client);
$this->tenant = $this->clientContext?->tenants()->first();
$this->configureMailer();
return $this;
}
public function forEvent(Event $event): self
{
parent::forEvent($event);
$this->configureMailer();
return $this;
}
private function configureMailer(): void
{
if ($this->integrationInstance) {
$this->mailer = $this->resolveMailer();
$this->usesInstanceMailer = true;
return;
} else {
$this->mailer = $this->mailFactory->mailer();
$this->usesInstanceMailer = false;
}
$this->mailer = $this->mailFactory->mailer();
$this->usesInstanceMailer = false;
return $this;
}
public function getHeaders(): array
@@ -91,7 +83,7 @@ class MailService extends BaseIntegrationService
array $attachments = [],
): void {
if (! $this->mailer || ! $this->tenant) {
throw new Exception('MailService no está configurado. Llamá a forTenant(), forClient() o forEvent() primero.');
throw new Exception('MailService no está configurado. Llamá a forTenant() o forClient() primero.');
}
$brand ??= $this->tenant;
@@ -168,7 +160,7 @@ class MailService extends BaseIntegrationService
public function onSetup(): void
{
if (! $this->mailer || ! $this->clientContext) {
throw new Exception('MailService no está configurado. Llamá a forTenant(), forClient() o forEvent() primero.');
throw new Exception('MailService no está configurado. Llamá a forTenant() o forClient() primero.');
}
$recipient = $this->getIntegrationSetting('MAIL_FROM_ADDRESS');

View File

@@ -46,7 +46,7 @@ class TelepagosIntegrationService extends BaseIntegrationService
public function getToken(): string
{
if (! $this->integrationInstance) {
throw new Exception('Client integration is not loaded. Call forTenant(), forClient(), or forEvent() first.');
throw new Exception('Client integration is not loaded. Call forTenant() or forClient() first.');
}
$cacheKey = $this->integrationInstance->tokenCacheKey();

View File

@@ -2,12 +2,12 @@
namespace App\Shared\Integration\Services;
use App\Domains\Core\Client\Models\Client;
use App\Domains\Commerce\Purchase\Models\Purchase;
use App\Domains\Commerce\Purchase\Models\TelepagosPayment;
use App\Domains\Commerce\Purchase\Models\TelepagosQr;
use App\Domains\Commerce\Purchase\Services\CheckoutService;
use App\Domains\Commerce\Purchase\Services\DniDistanceService;
use App\Domains\Core\Client\Models\Client;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
@@ -75,30 +75,9 @@ class TelepagosWebhookService
$dni = substr($cuit, 2, -1);
$tenantCodes = $client->tenants()->pluck('codigo');
$eligiblePurchases = Purchase::query()
->where(function (Builder $purchases) use ($client): void {
$purchases
->whereHas('event', function (Builder $events) use ($client): void {
$events
->where('client_id', $client->id)
->orWhere(function (Builder $fallback) use ($client): void {
$fallback
->whereNull('client_id')
->whereHas(
'tenant',
fn (Builder $tenants): Builder => $tenants->where('client_id', $client->id),
);
});
})
->orWhere(function (Builder $legacy) use ($client): void {
$legacy
->whereNull('event_id')
->whereHas(
'tenant',
fn (Builder $tenants): Builder => $tenants->where('client_id', $client->id),
);
});
})
->whereIn('tenant_codigo', $tenantCodes)
->whereIn('status', [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
@@ -191,7 +170,7 @@ class TelepagosWebhookService
return;
}
if (! $this->purchaseBelongsToClient($compra, $client)) {
if (! $client->tenants()->where('codigo', $compra->tenant_codigo)->exists()) {
Log::channel('telepagos')->warning('Telepagos webhook: Purchase does not belong to client.', [
'client_code' => $client->code,
'cashin_id' => $cashinId,
@@ -265,16 +244,6 @@ class TelepagosWebhookService
return number_format((float) $amount, 2, '.', '');
}
private function purchaseBelongsToClient(Purchase $purchase, Client $client): bool
{
$purchase->loadMissing(['event.client', 'event.tenant.client', 'tenant.client']);
$effectiveClient = $purchase->event?->effectiveClient()
?? $purchase->tenant?->client;
return $effectiveClient?->is($client) ?? false;
}
/**
* @param Builder<Purchase> $eligiblePurchases
* @return Collection<int, Purchase>

View File

@@ -2,16 +2,16 @@
namespace App\Shared\Notification\Services;
use App\Domains\Commerce\Purchase\Models\Purchase;
use App\Domains\Core\Auth\Models\ResetPasswordAttempt;
use App\Domains\Core\Auth\Models\User;
use App\Shared\Integration\Services\MailService;
use App\Shared\Notification\Events\PasswordResetRequested;
use App\Domains\Commerce\Purchase\Models\Purchase;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use App\Domains\Ticketing\Ticket\Services\TicketPdfService;
use App\Domains\Ticketing\Ticket\Services\TicketPresentationResolver;
use App\Domains\Ticketing\Ticket\Services\TicketValidityResolver;
use App\Shared\Integration\Services\MailService;
use App\Shared\Notification\Events\PasswordResetRequested;
use Closure;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
@@ -158,7 +158,7 @@ class NotificationMailService
$context = ['purchase_id' => $purchaseId];
$purchase = Purchase::query()
->with(['event', 'tenant', 'user', 'items'])
->with(['tenant', 'user', 'items'])
->find($purchaseId);
if ($purchase === null) {
@@ -197,7 +197,8 @@ class NotificationMailService
'mime' => 'application/pdf',
]];
$this->mailForPurchase($purchase)
$this->mailService
->forTenant($purchase->tenant_codigo)
->send(
$recipient,
"Compra confirmada - Compra #{$purchase->getKey()}",
@@ -285,6 +286,7 @@ class NotificationMailService
$context,
$recipient,
function () use (
$tenantCode,
$purchase,
$recipient,
$previousDate,
@@ -293,7 +295,8 @@ class NotificationMailService
): array {
$brand = $purchase->tenant;
$this->mailForPurchase($purchase)
$this->mailService
->forTenant($tenantCode)
->send(
$recipient,
"Tu evento fue reprogramado - N° de Orden #{$purchase->getKey()}",
@@ -384,6 +387,7 @@ class NotificationMailService
$context,
$recipient,
function () use (
$tenantCode,
$purchase,
$recipient,
$date,
@@ -392,7 +396,8 @@ class NotificationMailService
): array {
$brand = $purchase->tenant;
$this->mailForPurchase($purchase)
$this->mailService
->forTenant($tenantCode)
->send(
$recipient,
"Una fecha de tu evento fue suspendida - N° de Orden #{$purchase->getKey()}",
@@ -416,17 +421,10 @@ class NotificationMailService
{
return Purchase::query()
->where('tenant_codigo', $tenantCode)
->with(['event', 'tenant', 'user'])
->with(['tenant', 'user'])
->find($purchaseId);
}
private function mailForPurchase(Purchase $purchase): MailService
{
return $purchase->event
? $this->mailService->forEvent($purchase->event)
: $this->mailService->forTenant($purchase->tenant_codigo);
}
private function recipientFor(Purchase $purchase): string
{
return (string) ($purchase->email ?: $purchase->user?->email);