82 lines
2.1 KiB
PHP
82 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class MasterFormula extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $fillable = [
|
|
'formula_code',
|
|
'formula_name',
|
|
'formula_expression',
|
|
'formula_category',
|
|
'description',
|
|
'usage_notes',
|
|
];
|
|
|
|
/**
|
|
* Relationship to FormulaParameter (Many-to-Many dengan MasterParameter)
|
|
*/
|
|
public function formulaParameters()
|
|
{
|
|
return $this->hasMany(FormulaParameter::class, 'formula_id');
|
|
}
|
|
|
|
/**
|
|
* Relationship to MasterParameter through FormulaParameter
|
|
*/
|
|
public function parameters()
|
|
{
|
|
return $this->belongsToMany(MasterParameter::class, 'formula_parameters', 'formula_id', 'parameter_id');
|
|
}
|
|
|
|
/**
|
|
* Relationship to BuildingFunctionFormulaConfig
|
|
*/
|
|
public function buildingConfigs()
|
|
{
|
|
return $this->hasMany(BuildingFunctionFormulaConfig::class, 'formula_id');
|
|
}
|
|
|
|
/**
|
|
* Scope untuk mencari berdasarkan kategori
|
|
*/
|
|
public function scopeByCategory($query, $category)
|
|
{
|
|
return $query->where('formula_category', $category);
|
|
}
|
|
|
|
/**
|
|
* Method untuk mendapatkan parameter yang diperlukan formula ini
|
|
*/
|
|
public function getRequiredParameters()
|
|
{
|
|
return $this->parameters()->get();
|
|
}
|
|
|
|
/**
|
|
* Method untuk evaluate formula dengan parameter values
|
|
*/
|
|
public function evaluateFormula($parameterValues = [])
|
|
{
|
|
$expression = $this->formula_expression;
|
|
|
|
// Replace parameter codes dengan nilai actual
|
|
foreach ($parameterValues as $parameterCode => $value) {
|
|
$expression = str_replace('{' . $parameterCode . '}', $value, $expression);
|
|
}
|
|
|
|
// Evaluasi mathematical expression (hati-hati dengan security!)
|
|
// Untuk production, gunakan library yang aman seperti SymfonyExpressionLanguage
|
|
try {
|
|
return eval("return $expression;");
|
|
} catch (Exception $e) {
|
|
throw new \Exception("Error evaluating formula: " . $e->getMessage());
|
|
}
|
|
}
|
|
}
|