'decimal:2', 'quantity' => 'decimal:4', 'unit_cost' => 'decimal:2', 'sort_order' => 'integer', ]; /** * Tipos de componentes disponíveis */ const TYPE_PRODUCT_COST = 'product_cost'; const TYPE_PACKAGING = 'packaging'; const TYPE_LABEL = 'label'; const TYPE_SHIPPING = 'shipping'; const TYPE_HANDLING = 'handling'; const TYPE_OTHER = 'other'; /** * Lista de tipos para validação */ public static function getTypes(): array { return [ self::TYPE_PRODUCT_COST => 'Custo do Produto', self::TYPE_PACKAGING => 'Embalagem', self::TYPE_LABEL => 'Etiqueta', self::TYPE_SHIPPING => 'Frete', self::TYPE_HANDLING => 'Manuseio', self::TYPE_OTHER => 'Outro', ]; } /** * Relacionamento com ficha técnica */ public function productSheet(): BelongsTo { return $this->belongsTo(ProductSheet::class); } /** * Calcula o custo unitário * * @return float */ public function calculateUnitCost(): float { if ($this->quantity <= 0) { return (float) $this->amount; } return round($this->amount / $this->quantity, 2); } /** * Boot do modelo para recalcular automaticamente */ protected static function boot() { parent::boot(); // Antes de salvar, calcular o custo unitário static::saving(function ($item) { $item->unit_cost = $item->calculateUnitCost(); }); // Após salvar, recalcular o CMV da ficha técnica static::saved(function ($item) { if ($item->productSheet) { $item->productSheet->recalculateCmv(); } }); // Após deletar, recalcular o CMV da ficha técnica static::deleted(function ($item) { if ($item->productSheet) { $item->productSheet->recalculateCmv(); } }); } }