feat(admin-stock): apply idempotent availability deltas
This commit is contained in:
@@ -43,9 +43,9 @@ class MerchandiseService
|
||||
* @param array<int, array<string, mixed>> $items
|
||||
* @return Collection<int, CatalogItem>
|
||||
*/
|
||||
public function upsertMany(Tenant $tenant, array $items): Collection
|
||||
public function upsertMany(Tenant $tenant, array $items, ?string $stockAdjustmentId = null): Collection
|
||||
{
|
||||
return DB::transaction(function () use ($tenant, $items): Collection {
|
||||
return DB::transaction(function () use ($tenant, $items, $stockAdjustmentId): Collection {
|
||||
$attributes = $this->attributes($tenant);
|
||||
$category = Category::query()->firstOrCreate([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
@@ -57,6 +57,7 @@ class MerchandiseService
|
||||
$tenant,
|
||||
$attributes,
|
||||
$category,
|
||||
$stockAdjustmentId,
|
||||
&$reservedSlugs,
|
||||
): CatalogItem {
|
||||
$item = isset($data['id'])
|
||||
@@ -101,7 +102,7 @@ class MerchandiseService
|
||||
if ($variant === null) {
|
||||
$this->createVariant($item, $itemAttributes, $variantData);
|
||||
} else {
|
||||
$this->updateVariant($variant, $itemAttributes, $variantData, $index, $variantIndex);
|
||||
$this->updateVariant($variant, $itemAttributes, $variantData, $index, $variantIndex, $stockAdjustmentId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,6 +343,7 @@ 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'],
|
||||
@@ -359,22 +361,16 @@ 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->update(['real_stock' => $data['stock']]);
|
||||
$stockDifference = (int) ($data['stock_difference'] ?? ($data['stock'] - $inventory->availableStock()));
|
||||
$inventory->adjustAvailableStock($stockDifference, idempotencyKey: $stockAdjustmentId);
|
||||
$this->syncDefinitions($variant, $itemAttributes, $data);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user