Stage 5.1 — Warehouse ERP: batches + FIFO + reservations + multi-warehouse
Schema: - warehouses (multi-warehouse, code unique per company, is_default) - part_batches (lot per receipt, qty_in/qty_remaining, buy_price, FIFO-indexed) - warehouse_events (immutable ledger: opening/receipt/issue/transfer/adjustment/write_off) - part_reservations (per-WO allocations from specific batches, active/consumed/released) - companies.default_warehouse_id + parts.qty_reserved Backfill: 1 default warehouse + 1 opening batch per existing part per company. WarehouseService: - receive / issue (FIFO) / reserve / release / consume / transfer / adjust - DB::transaction + lockForUpdate on batch rows - InsufficientStockException with requested + available context - Auto-syncs parts.qty as aggregate cache (source of truth = sum(qty_remaining)) WO integration: - WorkOrderPart created/updated → reserve from FIFO batches - WorkOrderPart deleted → release - WorkOrder status=done → consume reservations into issue events - WorkOrder status=cancelled → release reservations Filament: - WarehouseResource (CRUD) - BatchesRelationManager on PartResource (FIFO list with qty_remaining + cost) - "Recepție" action on parts list → calls WarehouseService::receive - qty_reserved column added on parts list Tests (8 new, all pass): - receipt creates batch + event - FIFO order verified across 3 batches with different received_at - InsufficientStockException on over-issue - Reservations block other reservations but don't deplete on-hand - WO done consumes; WO cancelled releases - Batches tenant-isolated - Transfer between warehouses with weighted-avg cost Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,7 @@ namespace App\Models\Tenant;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
class Part extends Model
|
||||
@@ -18,7 +19,7 @@ class Part extends Model
|
||||
|
||||
protected $fillable = [
|
||||
'company_id', 'name', 'article', 'brand', 'category',
|
||||
'qty', 'unit', 'min_qty',
|
||||
'qty', 'qty_reserved', 'unit', 'min_qty',
|
||||
'buy_price', 'sell_price',
|
||||
'location', 'barcode', 'preferred_supplier_id',
|
||||
'is_active', 'notes',
|
||||
@@ -26,6 +27,7 @@ class Part extends Model
|
||||
|
||||
protected $casts = [
|
||||
'qty' => 'decimal:2',
|
||||
'qty_reserved' => 'decimal:3',
|
||||
'min_qty' => 'decimal:2',
|
||||
'buy_price' => 'decimal:2',
|
||||
'sell_price' => 'decimal:2',
|
||||
@@ -37,6 +39,35 @@ class Part extends Model
|
||||
return $this->belongsTo(Supplier::class, 'preferred_supplier_id');
|
||||
}
|
||||
|
||||
public function batches(): HasMany
|
||||
{
|
||||
return $this->hasMany(PartBatch::class);
|
||||
}
|
||||
|
||||
public function reservations(): HasMany
|
||||
{
|
||||
return $this->hasMany(PartReservation::class);
|
||||
}
|
||||
|
||||
public function events(): HasMany
|
||||
{
|
||||
return $this->hasMany(WarehouseEvent::class);
|
||||
}
|
||||
|
||||
/** Live total across all batches of all warehouses (source of truth). */
|
||||
public function qtyOnHand(?int $warehouseId = null): float
|
||||
{
|
||||
$q = $this->batches()->newQuery()->where('part_id', $this->id);
|
||||
if ($warehouseId) $q->where('warehouse_id', $warehouseId);
|
||||
return (float) $q->sum('qty_remaining');
|
||||
}
|
||||
|
||||
/** Available for new reservations = on hand − already reserved. */
|
||||
public function qtyAvailable(?int $warehouseId = null): float
|
||||
{
|
||||
return max(0.0, $this->qtyOnHand($warehouseId) - (float) $this->qty_reserved);
|
||||
}
|
||||
|
||||
public function isLow(): bool
|
||||
{
|
||||
return (float) $this->qty <= (float) $this->min_qty;
|
||||
@@ -47,6 +78,11 @@ class Part extends Model
|
||||
return (float) $this->qty <= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy direct-stock adjustment.
|
||||
* NOTE: this only moves the cached `qty` column. Real stock changes
|
||||
* should go through WarehouseService so batches + events stay in sync.
|
||||
*/
|
||||
public function adjustStock(float $delta, ?string $reason = null): void
|
||||
{
|
||||
$this->qty = max(0, (float) $this->qty + $delta);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models\Tenant;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class PartBatch extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
|
||||
protected $fillable = [
|
||||
'company_id', 'part_id', 'warehouse_id', 'supplier_id',
|
||||
'batch_ref', 'qty_in', 'qty_remaining', 'buy_price',
|
||||
'received_at', 'notes',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'qty_in' => 'decimal:3',
|
||||
'qty_remaining' => 'decimal:3',
|
||||
'buy_price' => 'decimal:2',
|
||||
'received_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function part(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Part::class);
|
||||
}
|
||||
|
||||
public function warehouse(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Warehouse::class);
|
||||
}
|
||||
|
||||
public function supplier(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Supplier::class);
|
||||
}
|
||||
|
||||
public function reservations(): HasMany
|
||||
{
|
||||
return $this->hasMany(PartReservation::class, 'batch_id');
|
||||
}
|
||||
|
||||
public function isDepleted(): bool
|
||||
{
|
||||
return (float) $this->qty_remaining <= 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models\Tenant;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class PartReservation extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
|
||||
public const STATUS_ACTIVE = 'active';
|
||||
public const STATUS_CONSUMED = 'consumed';
|
||||
public const STATUS_RELEASED = 'released';
|
||||
|
||||
protected $fillable = [
|
||||
'company_id', 'work_order_id', 'work_order_part_id',
|
||||
'part_id', 'batch_id', 'qty', 'status',
|
||||
'reserved_at', 'consumed_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'qty' => 'decimal:3',
|
||||
'reserved_at' => 'datetime',
|
||||
'consumed_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function workOrder(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(WorkOrder::class);
|
||||
}
|
||||
|
||||
public function workOrderPart(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(WorkOrderPart::class);
|
||||
}
|
||||
|
||||
public function part(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Part::class);
|
||||
}
|
||||
|
||||
public function batch(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(PartBatch::class, 'batch_id');
|
||||
}
|
||||
|
||||
public function isActive(): bool
|
||||
{
|
||||
return $this->status === self::STATUS_ACTIVE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models\Tenant;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
class Warehouse extends Model
|
||||
{
|
||||
use BelongsToTenant, SoftDeletes;
|
||||
|
||||
protected $fillable = [
|
||||
'company_id', 'code', 'name', 'address', 'is_default', 'is_active',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_default' => 'boolean',
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
|
||||
public function batches(): HasMany
|
||||
{
|
||||
return $this->hasMany(PartBatch::class);
|
||||
}
|
||||
|
||||
public function events(): HasMany
|
||||
{
|
||||
return $this->hasMany(WarehouseEvent::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models\Tenant;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphTo;
|
||||
|
||||
/**
|
||||
* Immutable ledger of every stock movement. The qty/cost reality of the
|
||||
* warehouse can always be reconstructed by aggregating these events.
|
||||
*/
|
||||
class WarehouseEvent extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
|
||||
public const TYPES = [
|
||||
'opening' => 'Stoc inițial',
|
||||
'receipt' => 'Recepție',
|
||||
'issue' => 'Consum',
|
||||
'transfer_out' => 'Transfer (ieșire)',
|
||||
'transfer_in' => 'Transfer (intrare)',
|
||||
'adjustment' => 'Ajustare',
|
||||
'write_off' => 'Casare',
|
||||
'return' => 'Retur',
|
||||
];
|
||||
|
||||
protected $fillable = [
|
||||
'company_id', 'part_id', 'batch_id', 'warehouse_id',
|
||||
'type', 'qty_delta', 'unit_cost',
|
||||
'ref_type', 'ref_id', 'user_id',
|
||||
'occurred_at', 'notes',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'qty_delta' => 'decimal:3',
|
||||
'unit_cost' => 'decimal:2',
|
||||
'occurred_at' => 'datetime',
|
||||
];
|
||||
|
||||
public $timestamps = true;
|
||||
|
||||
public function part(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Part::class);
|
||||
}
|
||||
|
||||
public function batch(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(PartBatch::class, 'batch_id');
|
||||
}
|
||||
|
||||
public function warehouse(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Warehouse::class);
|
||||
}
|
||||
|
||||
public function ref(): MorphTo
|
||||
{
|
||||
return $this->morphTo();
|
||||
}
|
||||
}
|
||||
@@ -141,6 +141,20 @@ class WorkOrder extends Model implements HasMedia
|
||||
app(\App\Services\NotificationDispatcher::class)->workOrderReady($wo);
|
||||
}
|
||||
|
||||
// Warehouse lifecycle: status=done → consume reservations into issues;
|
||||
// status=cancelled → release reservations.
|
||||
if ($wo->wasChanged('status')) {
|
||||
$svc = app(\App\Services\Warehouse\WarehouseService::class);
|
||||
if ($wo->status === 'done' && $wo->getOriginal('status') !== 'done') {
|
||||
$svc->consume($wo);
|
||||
}
|
||||
if ($wo->status === 'cancelled' && $wo->getOriginal('status') !== 'cancelled') {
|
||||
foreach ($wo->parts as $wop) {
|
||||
$svc->release($wop);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Broadcast real-time update on any field change (skip if broadcasting=log).
|
||||
if (config('broadcasting.default') !== 'log') {
|
||||
try {
|
||||
|
||||
@@ -52,21 +52,37 @@ class WorkOrderPart extends Model
|
||||
$row->total = round($sub * (1 - $disc / 100), 2);
|
||||
});
|
||||
|
||||
// When a part is marked installed, decrement catalog stock once.
|
||||
static::updating(function (self $row) {
|
||||
$wasInstalled = $row->getOriginal('status') === 'installed';
|
||||
$isInstalled = $row->status === 'installed';
|
||||
if (! $wasInstalled && $isInstalled && $row->part_id) {
|
||||
$part = Part::find($row->part_id);
|
||||
$part?->adjustStock(-(float) $row->qty);
|
||||
// Reserve batches as soon as a catalog-linked part line is created.
|
||||
// Reservations don't reduce on-hand qty, only block other reservations.
|
||||
static::created(function (self $row) {
|
||||
if ($row->part_id) {
|
||||
try {
|
||||
app(\App\Services\Warehouse\WarehouseService::class)->reserve($row);
|
||||
} catch (\App\Services\Warehouse\InsufficientStockException $e) {
|
||||
\Illuminate\Support\Facades\Log::warning('WO part reservation skipped: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
// If reverting from installed → restore stock
|
||||
if ($wasInstalled && ! $isInstalled && $row->part_id) {
|
||||
$part = Part::find($row->part_id);
|
||||
$part?->adjustStock((float) $row->qty);
|
||||
});
|
||||
|
||||
// If qty / part link changes, release old reservation and re-reserve.
|
||||
static::updated(function (self $row) {
|
||||
if ($row->wasChanged(['qty', 'part_id'])) {
|
||||
$svc = app(\App\Services\Warehouse\WarehouseService::class);
|
||||
$svc->release($row);
|
||||
if ($row->part_id) {
|
||||
try {
|
||||
$svc->reserve($row);
|
||||
} catch (\App\Services\Warehouse\InsufficientStockException $e) {
|
||||
\Illuminate\Support\Facades\Log::warning('WO part re-reservation skipped: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
static::deleted(function (self $row) {
|
||||
app(\App\Services\Warehouse\WarehouseService::class)->release($row);
|
||||
});
|
||||
|
||||
static::saved(fn (self $row) => $row->workOrder?->recalcTotal());
|
||||
static::deleted(fn (self $row) => $row->workOrder?->recalcTotal());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user