Files
pos_heidiver/app/Models/ProductVariant.php
T
2026-01-06 15:35:59 -05:00

94 lines
2.2 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class ProductVariant extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'producto_id',
'color_id',
'size_id',
'stock',
'sku',
'barcode'
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'id' => 'integer',
];
public function producto(): BelongsTo
{
return $this->belongsTo(Producto::class);
}
public function color(): BelongsTo
{
return $this->belongsTo(Color::class);
}
public function size(): BelongsTo
{
return $this->belongsTo(Size::class);
}
/**
* Relación many-to-many con bodegas
*/
public function bodegas(): BelongsToMany
{
return $this->belongsToMany(Bodega::class, 'variante_bodega', 'variante_id', 'bodega_id')
->withPivot('stock')
->withTimestamps();
}
/**
* Obtener el stock total de la variante en todas las bodegas
*/
public function getStockTotalBodegas(): int
{
try {
return $this->bodegas()->sum('variante_bodega.stock');
} catch (\Exception $e) {
// En caso de error, retornar 0
return 0;
}
}
/**
* Obtener el stock efectivo de la variante (considerando bodegas si existen)
*/
public function getStockEfectivo(): int
{
try {
// Si tiene distribución en bodegas, usar ese stock
if ($this->bodegas()->exists()) {
return $this->getStockTotalBodegas();
}
} catch (\Exception $e) {
// En caso de error (tabla no existe, etc.), usar stock directo
// Esto puede ocurrir durante migraciones o configuración inicial
}
// Stock directo de la variante
return $this->stock;
}
}