Auto-deduct spice inventory when batch is created/updated/deleted
Deploy / deploy (push) Successful in 14s

- Add size_id, units_produced, quantity_g to batches table
- quantity_g auto-calculated from units × packing size on save
- Batch model deducts spice quantities on create, reverses on delete,
  recalculates on update when relevant fields change
- Batch form shows live total weight preview
- Chargen table shows units + grams produced

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Malek TellissiandClaude Sonnet 4.6 committed 2026-09-12 05:34:09 +02:00
1 parent 1e93aaa7d8
commit a34bb29620
4 files changed
+163 -1

No files matched your search

+66 -1
View File
@@ -6,7 +6,10 @@ use Illuminate\Database\Eloquent\Model;
class Batch extends Model
{
protected $fillable = ['lot_number', 'product_id', 'recipe_id', 'produced_at', 'expires_at'];
protected $fillable = [
'lot_number', 'product_id', 'size_id', 'recipe_id',
'units_produced', 'quantity_g', 'produced_at', 'expires_at',
];
protected $casts = [
'produced_at' => 'date',
@@ -18,6 +21,11 @@ class Batch extends Model
return $this->belongsTo(Product::class);
}
public function size()
{
return $this->belongsTo(ProductSize::class);
}
public function recipe()
{
return $this->belongsTo(Recipe::class);
@@ -27,4 +35,61 @@ class Batch extends Model
{
return $this->hasMany(BatchOrigin::class);
}
protected static function booted(): void
{
// Auto-calculate quantity_g before saving
static::saving(function (Batch $batch) {
if ($batch->units_produced && $batch->size_id) {
$gramsPerUnit = $batch->size?->packing?->size ?? 0;
$batch->quantity_g = $batch->units_produced * $gramsPerUnit;
}
});
static::created(function (Batch $batch) {
$batch->deductSpices();
});
static::updated(function (Batch $batch) {
if ($batch->wasChanged(['recipe_id', 'size_id', 'units_produced'])) {
$batch->restoreSpices(
$batch->getOriginal('recipe_id'),
$batch->getOriginal('quantity_g'),
);
$batch->deductSpices();
}
});
static::deleting(function (Batch $batch) {
$batch->restoreSpices($batch->recipe_id, $batch->quantity_g);
});
}
private function deductSpices(): void
{
if (! $this->quantity_g || ! $this->recipe_id) {
return;
}
$recipe = Recipe::with('spices')->find($this->recipe_id);
foreach ($recipe->spices as $spice) {
$grams = $this->quantity_g * $spice->pivot->amount_in_percent / 100;
$spice->decrement('quantity', $grams);
}
}
private function restoreSpices(int $recipeId, float $quantityG): void
{
if (! $quantityG || ! $recipeId) {
return;
}
$recipe = Recipe::with('spices')->find($recipeId);
foreach ($recipe->spices as $spice) {
$grams = $quantityG * $spice->pivot->amount_in_percent / 100;
$spice->increment('quantity', $grams);
}
}
}