webmoney/backend/app/Models/BusinessSetting.php
CnxiFly Dev 84d9d7d187 feat(business): add Business section with Markup pricing v1.28.0
- Add business_settings table for Markup configuration
- Add product_sheets table for product technical sheets (CMV)
- Add product_sheet_items table for cost components
- Create BusinessSetting model with calculateMarkup() method
- Create ProductSheet model with recalculateCmv() method
- Create ProductSheetItem model for cost breakdown
- Add BusinessSettingController with CRUD + simulate-price endpoint
- Add ProductSheetController with CRUD + items management + duplicate
- Add Business page with 3 tabs (Settings, Products, Calculator)
- Add BusinessSettingsTab component with markup cards
- Add ProductSheetsTab component with product grid
- Add PriceCalculatorTab component with interactive simulator
- Add i18n translations in ES, PT-BR, EN
- Multi-currency support (EUR, BRL, USD)
2025-12-14 07:44:18 +01:00

181 lines
4.9 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\HasMany;
class BusinessSetting extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'currency',
'name',
'monthly_revenue',
'fixed_expenses',
'tax_rate',
'sales_commission',
'card_fee',
'other_variable_costs',
'investment_rate',
'profit_margin',
'markup_factor',
'is_active',
];
protected $casts = [
'monthly_revenue' => 'decimal:2',
'fixed_expenses' => 'decimal:2',
'tax_rate' => 'decimal:2',
'sales_commission' => 'decimal:2',
'card_fee' => 'decimal:2',
'other_variable_costs' => 'decimal:2',
'investment_rate' => 'decimal:2',
'profit_margin' => 'decimal:2',
'markup_factor' => 'decimal:4',
'is_active' => 'boolean',
];
/**
* Relacionamento com usuário
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* Fichas técnicas que usam esta configuração
*/
public function productSheets(): HasMany
{
return $this->hasMany(ProductSheet::class);
}
/**
* Calcula o percentual de despesas fixas sobre a receita
*
* @return float
*/
public function getFixedExpensesRateAttribute(): float
{
if ($this->monthly_revenue <= 0) {
return 0;
}
return round(($this->fixed_expenses / $this->monthly_revenue) * 100, 2);
}
/**
* Calcula o total de custos variáveis (sem CMV)
*
* @return float
*/
public function getTotalVariableCostsAttribute(): float
{
return $this->tax_rate +
$this->sales_commission +
$this->card_fee +
$this->other_variable_costs;
}
/**
* Calcula o fator de Markup usando a fórmula:
* Markup = 1 / (1 - (Despesas Fixas % + Custos Variáveis % + Investimento % + Lucro %))
*
* @return float
*/
public function calculateMarkup(): float
{
// Converter percentuais para decimais
$fixedExpensesRate = $this->fixed_expenses_rate / 100;
$variableCosts = $this->total_variable_costs / 100;
$investmentRate = $this->investment_rate / 100;
$profitMargin = $this->profit_margin / 100;
// Total de deduções
$totalDeductions = $fixedExpensesRate + $variableCosts + $investmentRate + $profitMargin;
// Verificar se é possível calcular (não pode ser >= 100%)
if ($totalDeductions >= 1) {
return 0; // Markup inválido - deduções >= 100%
}
// Fórmula: Markup = 1 / (1 - deduções)
$markup = 1 / (1 - $totalDeductions);
return round($markup, 4);
}
/**
* Recalcula e salva o markup
*
* @return float
*/
public function recalculateMarkup(): float
{
$this->markup_factor = $this->calculateMarkup();
$this->save();
return $this->markup_factor;
}
/**
* Calcula o preço de venda para um CMV dado
*
* @param float $cmv Custo da Mercadoria Vendida
* @return float
*/
public function calculateSalePrice(float $cmv): float
{
$markup = $this->markup_factor ?? $this->calculateMarkup();
if ($markup <= 0) {
return 0;
}
return round($cmv * $markup, 2);
}
/**
* Retorna o breakdown do Markup para exibição
*
* @return array
*/
public function getMarkupBreakdownAttribute(): array
{
return [
'fixed_expenses_rate' => $this->fixed_expenses_rate,
'tax_rate' => (float) $this->tax_rate,
'sales_commission' => (float) $this->sales_commission,
'card_fee' => (float) $this->card_fee,
'other_variable_costs' => (float) $this->other_variable_costs,
'total_variable_costs' => $this->total_variable_costs,
'investment_rate' => (float) $this->investment_rate,
'profit_margin' => (float) $this->profit_margin,
'total_deductions' => $this->fixed_expenses_rate + $this->total_variable_costs + $this->investment_rate + $this->profit_margin,
'markup_factor' => (float) ($this->markup_factor ?? $this->calculateMarkup()),
];
}
/**
* Scope para buscar configurações ativas do usuário
*/
public function scopeOfUser($query, $userId)
{
return $query->where('user_id', $userId);
}
/**
* Scope para buscar apenas configurações ativas
*/
public function scopeActive($query)
{
return $query->where('is_active', true);
}
}