pdv.backend/app/Models/Inventory.php
2026-02-05 17:01:19 -06:00

107 lines
2.4 KiB
PHP

<?php namespace App\Models;
/**
* @copyright (c) 2025 Notsoweb Software (https://notsoweb.com) - All Rights Reserved
*/
use Illuminate\Database\Eloquent\Model;
/**
* Descripción
*
* @author Moisés Cortés C. <moises.cortes@notsoweb.com>
*
* @version 1.0.0
*/
class Inventory extends Model
{
protected $fillable = [
'category_id',
'name',
'sku',
'barcode',
'stock',
'track_serials',
'is_active',
];
protected $casts = [
'is_active' => 'boolean',
'track_serials' => 'boolean',
];
protected $appends = ['has_serials', 'inventory_value'];
public function warehouses() {
return $this->belongsToMany(Warehouse::class, 'inventory_warehouse')
->withPivot('stock', 'min_stock', 'max_stock')
->withTimestamps();
}
// Obtener stock total en todos los almacenes
public function getTotalStockAttribute(): int {
return $this->warehouses()->sum('inventory_warehouse.stock');
}
// Sincronizar stock global
public function syncGlobalStock(): void {
$this->update(['stock' => $this->total_stock]);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function price()
{
return $this->hasOne(Price::class);
}
public function serials()
{
return $this->hasMany(InventorySerial::class);
}
/**
* Obtener seriales disponibles
*/
public function availableSerials()
{
return $this->hasMany(InventorySerial::class)
->where('status', 'disponible');
}
/**
* Calcular stock basado en seriales disponibles
*/
public function getAvailableStockAttribute(): int
{
return $this->availableSerials()->count();
}
/**
* Sincronizar el campo stock con los seriales disponibles
*/
public function syncStock(): void
{
if($this->track_serials) {
$this->update(['stock' => $this->getAvailableStockAttribute()]);
}
}
public function getHasSerialsAttribute(): bool
{
return isset($this->attributes['serials_count']) && $this->attributes['serials_count'] > 0;
}
/**
* Calcular el valor total del inventario para este producto (stock * costo)
*/
public function getInventoryValueAttribute(): float
{
return $this->total_stock * ($this->price?->cost ?? 0);
}
}