106 lines
2.7 KiB
PHP
106 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
|
|
class RetributionFormula extends Model
|
|
{
|
|
protected $fillable = [
|
|
'building_function_id',
|
|
'name',
|
|
'formula_expression',
|
|
'description',
|
|
'is_active'
|
|
];
|
|
|
|
protected $casts = [
|
|
'is_active' => 'boolean'
|
|
];
|
|
|
|
/**
|
|
* Building function relationship (1:1)
|
|
*/
|
|
public function buildingFunction(): BelongsTo
|
|
{
|
|
return $this->belongsTo(BuildingFunction::class);
|
|
}
|
|
|
|
/**
|
|
* Retribution calculations relationship (1:n)
|
|
*/
|
|
public function retributionCalculations(): HasMany
|
|
{
|
|
return $this->hasMany(RetributionCalculation::class);
|
|
}
|
|
|
|
/**
|
|
* Scope: Active formulas only
|
|
*/
|
|
public function scopeActive($query)
|
|
{
|
|
return $query->where('is_active', true);
|
|
}
|
|
|
|
/**
|
|
* Execute formula calculation
|
|
*/
|
|
public function calculate(float $luasBangunan, array $parameters): float
|
|
{
|
|
// Replace placeholders in formula with actual values
|
|
$formula = $this->formula_expression;
|
|
|
|
// Replace luas_bangunan
|
|
$formula = str_replace('luas_bangunan', $luasBangunan, $formula);
|
|
|
|
// Replace parameter values
|
|
foreach ($parameters as $key => $value) {
|
|
$formula = str_replace($key, $value, $formula);
|
|
}
|
|
|
|
// Evaluate the mathematical expression
|
|
// Note: In production, use a safer math expression evaluator
|
|
try {
|
|
$result = eval("return $formula;");
|
|
return (float) $result;
|
|
} catch (Exception $e) {
|
|
throw new \Exception("Error calculating formula: " . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get formula with parameter placeholders replaced for display
|
|
*/
|
|
public function getDisplayFormula(array $parameters = []): string
|
|
{
|
|
$formula = $this->formula_expression;
|
|
|
|
if (!empty($parameters)) {
|
|
foreach ($parameters as $key => $value) {
|
|
$formula = str_replace($key, "({$key}={$value})", $formula);
|
|
}
|
|
}
|
|
|
|
return $formula;
|
|
}
|
|
|
|
/**
|
|
* Validate formula expression
|
|
*/
|
|
public function validateFormula(): bool
|
|
{
|
|
// Basic validation - check if formula contains required elements
|
|
$requiredElements = ['luas_bangunan'];
|
|
|
|
foreach ($requiredElements as $element) {
|
|
if (strpos($this->formula_expression, $element) === false) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|