feat(admin-stock): apply idempotent availability deltas
This commit is contained in:
@@ -39,9 +39,9 @@ class AccommodationService
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $variants
|
||||
*/
|
||||
public function upsertMany(Tenant $tenant, array $variants): CatalogItem
|
||||
public function upsertMany(Tenant $tenant, array $variants, ?string $stockAdjustmentId = null): CatalogItem
|
||||
{
|
||||
return DB::transaction(function () use ($tenant, $variants): CatalogItem {
|
||||
return DB::transaction(function () use ($tenant, $variants, $stockAdjustmentId): 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);
|
||||
$this->updateVariant($attribute, $variant, $itemAttribute, $data, $index, $stockAdjustmentId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,6 +212,7 @@ 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'],
|
||||
@@ -230,20 +231,13 @@ 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
|
||||
@@ -263,7 +257,8 @@ class AccommodationService
|
||||
'descripcion' => $data['description'],
|
||||
'precio' => $data['price'],
|
||||
]);
|
||||
$inventory->update(['real_stock' => $data['stock']]);
|
||||
$stockDifference = (int) ($data['stock_difference'] ?? ($data['stock'] - $inventory->availableStock()));
|
||||
$inventory->adjustAvailableStock($stockDifference, idempotencyKey: $stockAdjustmentId);
|
||||
$variant->definitions()->updateOrCreate(
|
||||
['item_attribute_id' => $itemAttribute->id],
|
||||
['value' => $data['value']],
|
||||
|
||||
Reference in New Issue
Block a user