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:
@@ -3,6 +3,7 @@
|
||||
namespace App\Filament\Tenant\Resources;
|
||||
|
||||
use App\Filament\Tenant\Resources\PartResource\Pages;
|
||||
use App\Filament\Tenant\Resources\PartResource\RelationManagers;
|
||||
use App\Models\Tenant\Part;
|
||||
use App\Models\Tenant\Supplier;
|
||||
use Filament\Actions;
|
||||
@@ -112,6 +113,12 @@ class PartResource extends Resource
|
||||
->alignRight()
|
||||
->color(fn ($state, $record) => $record->qty <= 0 ? 'danger' : ($record->qty <= $record->min_qty ? 'warning' : null))
|
||||
->weight(fn ($state, $record) => $record->qty <= $record->min_qty ? 'bold' : null),
|
||||
Tables\Columns\TextColumn::make('qty_reserved')
|
||||
->label('Rezervat')
|
||||
->numeric(decimalPlaces: 2)
|
||||
->alignRight()
|
||||
->color(fn ($state) => (float) $state > 0 ? 'info' : null)
|
||||
->toggleable(),
|
||||
Tables\Columns\TextColumn::make('unit')->label('UM'),
|
||||
Tables\Columns\TextColumn::make('location')->label('Loc.')->placeholder('—'),
|
||||
Tables\Columns\TextColumn::make('sell_price')->label('Preț vz.')->money('MDL')->alignRight(),
|
||||
@@ -128,6 +135,42 @@ class PartResource extends Resource
|
||||
->query(fn ($q) => $q->where('qty', '<=', 0)),
|
||||
])
|
||||
->actions([
|
||||
Actions\Action::make('receive')
|
||||
->label('Recepție')
|
||||
->icon('heroicon-m-arrow-down-tray')
|
||||
->color('success')
|
||||
->schema([
|
||||
Forms\Components\TextInput::make('qty')->label('Cantitate')->numeric()->required()->minValue(0.001),
|
||||
Forms\Components\TextInput::make('buy_price')->label('Preț unitar')->numeric()->required(),
|
||||
Forms\Components\Select::make('supplier_id')
|
||||
->label('Furnizor')
|
||||
->options(fn () => \App\Models\Tenant\Supplier::pluck('name', 'id')),
|
||||
Forms\Components\Select::make('warehouse_id')
|
||||
->label('Depozit')
|
||||
->options(fn () => \App\Models\Tenant\Warehouse::where('is_active', true)->pluck('name', 'id'))
|
||||
->default(fn () => \App\Models\Tenant\Warehouse::where('is_default', true)->value('id')),
|
||||
Forms\Components\TextInput::make('batch_ref')->label('Ref. lot/factură')->maxLength(64),
|
||||
])
|
||||
->action(function (Part $record, array $data) {
|
||||
$warehouse = $data['warehouse_id']
|
||||
? \App\Models\Tenant\Warehouse::find($data['warehouse_id'])
|
||||
: null;
|
||||
$supplier = $data['supplier_id']
|
||||
? \App\Models\Tenant\Supplier::find($data['supplier_id'])
|
||||
: null;
|
||||
app(\App\Services\Warehouse\WarehouseService::class)->receive(
|
||||
part: $record,
|
||||
qty: (float) $data['qty'],
|
||||
buyPrice: (float) $data['buy_price'],
|
||||
warehouse: $warehouse,
|
||||
supplier: $supplier,
|
||||
batchRef: $data['batch_ref'] ?? null,
|
||||
);
|
||||
\Filament\Notifications\Notification::make()
|
||||
->title('Stoc adăugat')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
Actions\EditAction::make(),
|
||||
Actions\DeleteAction::make(),
|
||||
])
|
||||
@@ -137,6 +180,13 @@ class PartResource extends Resource
|
||||
->defaultSort('name');
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
RelationManagers\BatchesRelationManager::class,
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Tenant\Resources\PartResource\RelationManagers;
|
||||
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Tables;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class BatchesRelationManager extends RelationManager
|
||||
{
|
||||
protected static string $relationship = 'batches';
|
||||
|
||||
protected static ?string $title = 'Loturi (FIFO)';
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
Tables\Columns\TextColumn::make('received_at')
|
||||
->label('Recepție')
|
||||
->dateTime('d.m.Y H:i')
|
||||
->sortable(),
|
||||
Tables\Columns\TextColumn::make('warehouse.code')->label('Depozit')->placeholder('—'),
|
||||
Tables\Columns\TextColumn::make('batch_ref')->label('Ref.')->placeholder('—'),
|
||||
Tables\Columns\TextColumn::make('supplier.name')->label('Furnizor')->placeholder('—'),
|
||||
Tables\Columns\TextColumn::make('qty_in')
|
||||
->label('Intrat')
|
||||
->numeric(decimalPlaces: 2)
|
||||
->alignRight(),
|
||||
Tables\Columns\TextColumn::make('qty_remaining')
|
||||
->label('Rămas')
|
||||
->numeric(decimalPlaces: 2)
|
||||
->alignRight()
|
||||
->weight('bold')
|
||||
->color(fn ($state) => (float) $state <= 0 ? 'gray' : 'success'),
|
||||
Tables\Columns\TextColumn::make('buy_price')
|
||||
->label('Preț unit.')
|
||||
->money('MDL')
|
||||
->alignRight(),
|
||||
])
|
||||
->defaultSort('received_at')
|
||||
->emptyStateHeading('Niciun lot înregistrat')
|
||||
->emptyStateDescription('Apasă „Recepție" pe lista de piese pentru a înregistra prima intrare în depozit.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Tenant\Resources;
|
||||
|
||||
use App\Filament\Tenant\Resources\WarehouseResource\Pages;
|
||||
use App\Models\Tenant\Warehouse;
|
||||
use Filament\Actions;
|
||||
use Filament\Forms;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class WarehouseResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Warehouse::class;
|
||||
|
||||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-building-storefront';
|
||||
|
||||
protected static ?string $navigationLabel = 'Depozite';
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Depozit';
|
||||
|
||||
protected static ?string $modelLabel = 'depozit';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'depozite';
|
||||
|
||||
protected static ?int $navigationSort = 38;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
Schemas\Components\Section::make()->columns(2)->schema([
|
||||
Forms\Components\TextInput::make('code')->label('Cod')->required()->maxLength(32),
|
||||
Forms\Components\TextInput::make('name')->label('Denumire')->required()->maxLength(120),
|
||||
Forms\Components\TextInput::make('address')->label('Adresă')->columnSpanFull()->maxLength(200),
|
||||
Forms\Components\Toggle::make('is_default')->label('Depozit implicit'),
|
||||
Forms\Components\Toggle::make('is_active')->label('Activ')->default(true),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
Tables\Columns\TextColumn::make('code')->searchable()->sortable(),
|
||||
Tables\Columns\TextColumn::make('name')->searchable()->sortable(),
|
||||
Tables\Columns\TextColumn::make('address')->placeholder('—')->toggleable(),
|
||||
Tables\Columns\IconColumn::make('is_default')->label('Implicit')->boolean(),
|
||||
Tables\Columns\IconColumn::make('is_active')->label('Activ')->boolean(),
|
||||
Tables\Columns\TextColumn::make('batches_count')
|
||||
->counts('batches')
|
||||
->label('Loturi')
|
||||
->alignRight(),
|
||||
])
|
||||
->actions([
|
||||
Actions\EditAction::make(),
|
||||
Actions\DeleteAction::make(),
|
||||
])
|
||||
->emptyStateHeading('Niciun depozit')
|
||||
->emptyStateDescription('Un depozit implicit a fost creat la migrare. Adaugă altele dacă ai locații fizice separate (sucursală, hală, mobil).')
|
||||
->emptyStateIcon('heroicon-o-building-storefront')
|
||||
->defaultSort('code');
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => Pages\ListWarehouses::route('/'),
|
||||
'create' => Pages\CreateWarehouse::route('/create'),
|
||||
'edit' => Pages\EditWarehouse::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Tenant\Resources\WarehouseResource\Pages;
|
||||
|
||||
use App\Filament\Tenant\Resources\WarehouseResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateWarehouse extends CreateRecord
|
||||
{
|
||||
protected static string $resource = WarehouseResource::class;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Tenant\Resources\WarehouseResource\Pages;
|
||||
|
||||
use App\Filament\Tenant\Resources\WarehouseResource;
|
||||
use Filament\Actions;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditWarehouse extends EditRecord
|
||||
{
|
||||
protected static string $resource = WarehouseResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [Actions\DeleteAction::make()];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Tenant\Resources\WarehouseResource\Pages;
|
||||
|
||||
use App\Filament\Tenant\Resources\WarehouseResource;
|
||||
use Filament\Actions;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListWarehouses extends ListRecords
|
||||
{
|
||||
protected static string $resource = WarehouseResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [Actions\CreateAction::make()];
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Warehouse;
|
||||
|
||||
class InsufficientStockException extends \RuntimeException
|
||||
{
|
||||
public function __construct(
|
||||
public readonly int $partId,
|
||||
public readonly float $requested,
|
||||
public readonly float $available,
|
||||
) {
|
||||
parent::__construct(sprintf(
|
||||
'Stoc insuficient pentru piesa #%d: cerut %.3f, disponibil %.3f',
|
||||
$partId, $requested, $available
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Warehouse;
|
||||
|
||||
use App\Models\Tenant\Part;
|
||||
use App\Models\Tenant\PartBatch;
|
||||
use App\Models\Tenant\PartReservation;
|
||||
use App\Models\Tenant\Supplier;
|
||||
use App\Models\Tenant\Warehouse;
|
||||
use App\Models\Tenant\WarehouseEvent;
|
||||
use App\Models\Tenant\WorkOrder;
|
||||
use App\Models\Tenant\WorkOrderPart;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class WarehouseService
|
||||
{
|
||||
/**
|
||||
* Resolve the warehouse to operate on. Default = company.default_warehouse_id.
|
||||
*/
|
||||
public function defaultWarehouse(int $companyId): Warehouse
|
||||
{
|
||||
$company = \App\Models\Central\Company::withoutGlobalScopes()->findOrFail($companyId);
|
||||
if ($company->default_warehouse_id) {
|
||||
return Warehouse::findOrFail($company->default_warehouse_id);
|
||||
}
|
||||
// Lazy-create a default warehouse if missing (e.g. tenant created
|
||||
// before warehouse migration). This makes the service self-healing.
|
||||
$wh = Warehouse::create([
|
||||
'company_id' => $companyId,
|
||||
'code' => 'MAIN',
|
||||
'name' => 'Depozit principal',
|
||||
'is_default' => true,
|
||||
]);
|
||||
$company->forceFill(['default_warehouse_id' => $wh->id])->saveQuietly();
|
||||
return $wh;
|
||||
}
|
||||
|
||||
/**
|
||||
* Receive new stock — creates a batch + receipt event + updates cached qty.
|
||||
*/
|
||||
public function receive(
|
||||
Part $part,
|
||||
float $qty,
|
||||
float $buyPrice,
|
||||
?Warehouse $warehouse = null,
|
||||
?Supplier $supplier = null,
|
||||
?string $batchRef = null,
|
||||
?Model $ref = null,
|
||||
?string $notes = null,
|
||||
?Carbon $occurredAt = null,
|
||||
): PartBatch {
|
||||
if ($qty <= 0) {
|
||||
throw new \InvalidArgumentException('Cantitatea de recepție trebuie să fie pozitivă.');
|
||||
}
|
||||
|
||||
$warehouse ??= $this->defaultWarehouse($part->company_id);
|
||||
$occurredAt ??= now();
|
||||
|
||||
return DB::transaction(function () use ($part, $qty, $buyPrice, $warehouse, $supplier, $batchRef, $ref, $notes, $occurredAt) {
|
||||
$batch = PartBatch::create([
|
||||
'company_id' => $part->company_id,
|
||||
'part_id' => $part->id,
|
||||
'warehouse_id' => $warehouse->id,
|
||||
'supplier_id' => $supplier?->id,
|
||||
'batch_ref' => $batchRef,
|
||||
'qty_in' => $qty,
|
||||
'qty_remaining' => $qty,
|
||||
'buy_price' => $buyPrice,
|
||||
'received_at' => $occurredAt,
|
||||
'notes' => $notes,
|
||||
]);
|
||||
|
||||
$this->logEvent($part, $batch, $warehouse, 'receipt', $qty, $buyPrice, $ref, $notes, $occurredAt);
|
||||
|
||||
$this->syncPartCachedQty($part);
|
||||
|
||||
return $batch;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Consume stock FIFO across batches. Writes one event per consumed batch.
|
||||
* Throws InsufficientStockException if total available < qty.
|
||||
*/
|
||||
public function issue(
|
||||
Part $part,
|
||||
float $qty,
|
||||
?Warehouse $warehouse = null,
|
||||
?Model $ref = null,
|
||||
?string $notes = null,
|
||||
): array {
|
||||
if ($qty <= 0) {
|
||||
throw new \InvalidArgumentException('Cantitatea de consum trebuie să fie pozitivă.');
|
||||
}
|
||||
|
||||
$warehouse ??= $this->defaultWarehouse($part->company_id);
|
||||
|
||||
return DB::transaction(function () use ($part, $qty, $warehouse, $ref, $notes) {
|
||||
$available = $this->availableForIssue($part, $warehouse);
|
||||
if ($available < $qty) {
|
||||
throw new InsufficientStockException($part->id, $qty, $available);
|
||||
}
|
||||
|
||||
$remaining = $qty;
|
||||
$events = [];
|
||||
|
||||
$batches = $this->fifoBatches($part, $warehouse)->lockForUpdate()->get();
|
||||
|
||||
foreach ($batches as $batch) {
|
||||
if ($remaining <= 0) break;
|
||||
|
||||
$take = min($remaining, (float) $batch->qty_remaining);
|
||||
if ($take <= 0) continue;
|
||||
|
||||
$batch->qty_remaining = (float) $batch->qty_remaining - $take;
|
||||
$batch->save();
|
||||
|
||||
$events[] = $this->logEvent(
|
||||
$part, $batch, $warehouse, 'issue',
|
||||
-$take, (float) $batch->buy_price, $ref, $notes
|
||||
);
|
||||
|
||||
$remaining -= $take;
|
||||
}
|
||||
|
||||
$this->syncPartCachedQty($part);
|
||||
|
||||
return $events;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reserve qty from FIFO batches against a WorkOrderPart. Returns reservation rows.
|
||||
*/
|
||||
public function reserve(WorkOrderPart $wop): array
|
||||
{
|
||||
return DB::transaction(function () use ($wop) {
|
||||
$part = $wop->part;
|
||||
if (! $part) return []; // free-text part with no catalog link — skip
|
||||
|
||||
$warehouse = $this->defaultWarehouse($part->company_id);
|
||||
$qty = (float) $wop->qty;
|
||||
|
||||
$available = $this->availableForReservation($part, $warehouse);
|
||||
if ($available < $qty) {
|
||||
throw new InsufficientStockException($part->id, $qty, $available);
|
||||
}
|
||||
|
||||
$remaining = $qty;
|
||||
$reservations = [];
|
||||
$batches = $this->fifoBatchesAvailable($part, $warehouse)->lockForUpdate()->get();
|
||||
|
||||
foreach ($batches as $batch) {
|
||||
if ($remaining <= 0) break;
|
||||
|
||||
$reservedOnBatch = (float) PartReservation::where('batch_id', $batch->id)
|
||||
->where('status', PartReservation::STATUS_ACTIVE)
|
||||
->sum('qty');
|
||||
$free = (float) $batch->qty_remaining - $reservedOnBatch;
|
||||
if ($free <= 0) continue;
|
||||
|
||||
$take = min($remaining, $free);
|
||||
|
||||
$reservations[] = PartReservation::create([
|
||||
'company_id' => $part->company_id,
|
||||
'work_order_id' => $wop->work_order_id,
|
||||
'work_order_part_id' => $wop->id,
|
||||
'part_id' => $part->id,
|
||||
'batch_id' => $batch->id,
|
||||
'qty' => $take,
|
||||
'status' => PartReservation::STATUS_ACTIVE,
|
||||
'reserved_at' => now(),
|
||||
]);
|
||||
|
||||
$remaining -= $take;
|
||||
}
|
||||
|
||||
$part->qty_reserved = (float) $part->qty_reserved + ($qty - $remaining);
|
||||
$part->saveQuietly();
|
||||
|
||||
return $reservations;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Release active reservations on a WorkOrderPart (e.g. WO cancelled / line removed).
|
||||
*/
|
||||
public function release(WorkOrderPart $wop): int
|
||||
{
|
||||
return DB::transaction(function () use ($wop) {
|
||||
$active = PartReservation::where('work_order_part_id', $wop->id)
|
||||
->where('status', PartReservation::STATUS_ACTIVE)
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
$totalReleased = 0.0;
|
||||
foreach ($active as $r) {
|
||||
$r->status = PartReservation::STATUS_RELEASED;
|
||||
$r->save();
|
||||
$totalReleased += (float) $r->qty;
|
||||
}
|
||||
|
||||
if ($wop->part_id && $totalReleased > 0) {
|
||||
$part = Part::find($wop->part_id);
|
||||
if ($part) {
|
||||
$part->qty_reserved = max(0.0, (float) $part->qty_reserved - $totalReleased);
|
||||
$part->saveQuietly();
|
||||
}
|
||||
}
|
||||
|
||||
return $active->count();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Consume reservations against a closed WO — converts each active reservation
|
||||
* into an issue event and decrements batch qty_remaining.
|
||||
*/
|
||||
public function consume(WorkOrder $wo): int
|
||||
{
|
||||
return DB::transaction(function () use ($wo) {
|
||||
$active = PartReservation::with(['batch', 'part'])
|
||||
->where('work_order_id', $wo->id)
|
||||
->where('status', PartReservation::STATUS_ACTIVE)
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
foreach ($active as $r) {
|
||||
$batch = $r->batch;
|
||||
if (! $batch) continue;
|
||||
$take = min((float) $r->qty, (float) $batch->qty_remaining);
|
||||
if ($take <= 0) continue;
|
||||
|
||||
$batch->qty_remaining = (float) $batch->qty_remaining - $take;
|
||||
$batch->save();
|
||||
|
||||
$this->logEvent(
|
||||
$r->part, $batch, $batch->warehouse,
|
||||
'issue', -$take, (float) $batch->buy_price,
|
||||
$wo, "WO #{$wo->number}"
|
||||
);
|
||||
|
||||
$r->status = PartReservation::STATUS_CONSUMED;
|
||||
$r->consumed_at = now();
|
||||
$r->save();
|
||||
|
||||
if ($r->part) {
|
||||
$r->part->qty_reserved = max(0.0, (float) $r->part->qty_reserved - (float) $r->qty);
|
||||
$r->part->saveQuietly();
|
||||
}
|
||||
}
|
||||
|
||||
// Re-sync all touched parts.
|
||||
$partIds = $active->pluck('part_id')->unique();
|
||||
foreach ($partIds as $pid) {
|
||||
if ($p = Part::find($pid)) $this->syncPartCachedQty($p);
|
||||
}
|
||||
|
||||
return $active->count();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Move stock between warehouses (FIFO from source). Creates one transfer_out
|
||||
* + one transfer_in batch in the destination warehouse.
|
||||
*/
|
||||
public function transfer(
|
||||
Part $part,
|
||||
float $qty,
|
||||
Warehouse $from,
|
||||
Warehouse $to,
|
||||
?string $notes = null,
|
||||
): PartBatch {
|
||||
if ($qty <= 0) throw new \InvalidArgumentException('Cantitatea de transfer trebuie să fie pozitivă.');
|
||||
if ($from->id === $to->id) throw new \InvalidArgumentException('Sursa și destinația sunt identice.');
|
||||
|
||||
return DB::transaction(function () use ($part, $qty, $from, $to, $notes) {
|
||||
$available = $this->availableForIssue($part, $from);
|
||||
if ($available < $qty) {
|
||||
throw new InsufficientStockException($part->id, $qty, $available);
|
||||
}
|
||||
|
||||
$remaining = $qty;
|
||||
$totalCost = 0.0;
|
||||
|
||||
$batches = $this->fifoBatches($part, $from)->lockForUpdate()->get();
|
||||
foreach ($batches as $batch) {
|
||||
if ($remaining <= 0) break;
|
||||
$take = min($remaining, (float) $batch->qty_remaining);
|
||||
if ($take <= 0) continue;
|
||||
|
||||
$batch->qty_remaining = (float) $batch->qty_remaining - $take;
|
||||
$batch->save();
|
||||
|
||||
$totalCost += $take * (float) $batch->buy_price;
|
||||
|
||||
$this->logEvent($part, $batch, $from, 'transfer_out', -$take, (float) $batch->buy_price, null, $notes);
|
||||
$remaining -= $take;
|
||||
}
|
||||
|
||||
$avgCost = $qty > 0 ? round($totalCost / $qty, 2) : 0.0;
|
||||
|
||||
$destBatch = PartBatch::create([
|
||||
'company_id' => $part->company_id,
|
||||
'part_id' => $part->id,
|
||||
'warehouse_id' => $to->id,
|
||||
'qty_in' => $qty,
|
||||
'qty_remaining' => $qty,
|
||||
'buy_price' => $avgCost,
|
||||
'received_at' => now(),
|
||||
'notes' => $notes ?? "Transfer din {$from->code}",
|
||||
]);
|
||||
|
||||
$this->logEvent($part, $destBatch, $to, 'transfer_in', $qty, $avgCost, null, $notes);
|
||||
|
||||
return $destBatch;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Inventory adjustment (stock-take correction). Positive delta = mystery gain;
|
||||
* negative = write-off. For losses we consume FIFO; for gains we open a new batch.
|
||||
*/
|
||||
public function adjust(Part $part, float $delta, ?Warehouse $warehouse = null, ?string $notes = null): void
|
||||
{
|
||||
if (abs($delta) < 0.001) return;
|
||||
$warehouse ??= $this->defaultWarehouse($part->company_id);
|
||||
|
||||
DB::transaction(function () use ($part, $delta, $warehouse, $notes) {
|
||||
if ($delta > 0) {
|
||||
// Use average current cost or last buy_price as cost for the gain batch.
|
||||
$cost = (float) ($part->batches()->latest('received_at')->value('buy_price') ?? $part->buy_price);
|
||||
$batch = PartBatch::create([
|
||||
'company_id' => $part->company_id,
|
||||
'part_id' => $part->id,
|
||||
'warehouse_id' => $warehouse->id,
|
||||
'qty_in' => $delta,
|
||||
'qty_remaining' => $delta,
|
||||
'buy_price' => $cost,
|
||||
'received_at' => now(),
|
||||
'notes' => $notes ?? 'Ajustare manuală',
|
||||
]);
|
||||
$this->logEvent($part, $batch, $warehouse, 'adjustment', $delta, $cost, null, $notes);
|
||||
} else {
|
||||
$remaining = -$delta;
|
||||
$batches = $this->fifoBatches($part, $warehouse)->lockForUpdate()->get();
|
||||
foreach ($batches as $batch) {
|
||||
if ($remaining <= 0) break;
|
||||
$take = min($remaining, (float) $batch->qty_remaining);
|
||||
if ($take <= 0) continue;
|
||||
$batch->qty_remaining = (float) $batch->qty_remaining - $take;
|
||||
$batch->save();
|
||||
$this->logEvent($part, $batch, $warehouse, 'adjustment', -$take, (float) $batch->buy_price, null, $notes);
|
||||
$remaining -= $take;
|
||||
}
|
||||
}
|
||||
|
||||
$this->syncPartCachedQty($part);
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Internals ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Available qty for FIFO issue ignoring reservations
|
||||
* (caller decides whether reservations matter).
|
||||
*/
|
||||
public function availableForIssue(Part $part, Warehouse $warehouse): float
|
||||
{
|
||||
return (float) PartBatch::where('part_id', $part->id)
|
||||
->where('warehouse_id', $warehouse->id)
|
||||
->sum('qty_remaining');
|
||||
}
|
||||
|
||||
/**
|
||||
* Available for new reservation = on_hand − active_reservations.
|
||||
*/
|
||||
public function availableForReservation(Part $part, Warehouse $warehouse): float
|
||||
{
|
||||
$onHand = $this->availableForIssue($part, $warehouse);
|
||||
|
||||
$reserved = (float) PartReservation::where('part_id', $part->id)
|
||||
->where('status', PartReservation::STATUS_ACTIVE)
|
||||
->whereHas('batch', fn ($q) => $q->where('warehouse_id', $warehouse->id))
|
||||
->sum('qty');
|
||||
|
||||
return max(0.0, $onHand - $reserved);
|
||||
}
|
||||
|
||||
protected function fifoBatches(Part $part, Warehouse $warehouse)
|
||||
{
|
||||
return PartBatch::where('part_id', $part->id)
|
||||
->where('warehouse_id', $warehouse->id)
|
||||
->where('qty_remaining', '>', 0)
|
||||
->orderBy('received_at')
|
||||
->orderBy('id');
|
||||
}
|
||||
|
||||
protected function fifoBatchesAvailable(Part $part, Warehouse $warehouse)
|
||||
{
|
||||
return $this->fifoBatches($part, $warehouse);
|
||||
}
|
||||
|
||||
protected function logEvent(
|
||||
Part $part,
|
||||
PartBatch $batch,
|
||||
Warehouse $warehouse,
|
||||
string $type,
|
||||
float $qtyDelta,
|
||||
?float $unitCost,
|
||||
?Model $ref,
|
||||
?string $notes,
|
||||
?Carbon $occurredAt = null,
|
||||
): WarehouseEvent {
|
||||
return WarehouseEvent::create([
|
||||
'company_id' => $part->company_id,
|
||||
'part_id' => $part->id,
|
||||
'batch_id' => $batch->id,
|
||||
'warehouse_id' => $warehouse->id,
|
||||
'type' => $type,
|
||||
'qty_delta' => $qtyDelta,
|
||||
'unit_cost' => $unitCost,
|
||||
'ref_type' => $ref ? get_class($ref) : null,
|
||||
'ref_id' => $ref?->getKey(),
|
||||
'user_id' => auth()->id(),
|
||||
'occurred_at' => $occurredAt ?? now(),
|
||||
'notes' => $notes,
|
||||
]);
|
||||
}
|
||||
|
||||
/** Keep parts.qty in sync as a cached aggregate across all warehouses. */
|
||||
protected function syncPartCachedQty(Part $part): void
|
||||
{
|
||||
$total = (float) PartBatch::where('part_id', $part->id)->sum('qty_remaining');
|
||||
$part->qty = $total;
|
||||
$part->saveQuietly();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user