Delegate result computation to goals_criteria and add revenue calculation logic.

This commit is contained in:
Jeppe Bundgaard
2026-01-26 19:16:46 +01:00
parent 52a2f38f81
commit 83b0a27c93
2 changed files with 45 additions and 0 deletions
@@ -31,8 +31,14 @@ class goals
*/
public function getResult(): int|float
{
// Delegate computation to criteria to keep logic centralized
if (method_exists($this->criteria, 'currentResult')) {
return $this->criteria->currentResult();
}
// Fallback for legacy behavior
return match ($this->criteria->type) {
goals_criteria_type::PRODUCT => $this->criteria->products->count($this->criteria),
goals_criteria_type::REVENUE => 0,
default => 0,
};
}
@@ -8,6 +8,7 @@ use goals\traits\goals_result_parser_t;
use goals\traits\goals_target_t;
use goals\traits\goals_timeframe_t;
use goals\traits\goals_label_t;
use objects\order_items_o;
class goals_criteria implements goals_criteria_i
{
@@ -188,7 +189,45 @@ class goals_criteria implements goals_criteria_i
{
return match ($this->type) {
goals_criteria_type::PRODUCT => $this->products->count($this),
goals_criteria_type::REVENUE => $this->sumRevenue(),
default => 0,
};
}
/**
* Calculate revenue within the criteria filters.
* Revenue is computed as sum(price * quantity) for matching order items.
* Prices are assumed to be stored as integers (e.g., cents) in the database.
*/
private function sumRevenue(): int
{
$datetime_start = $this->start ?? new \DateTime();
$datetime_end = $this->end ?? new \DateTime();
$items = order_items_o::getListByCriteria(
department_ids: $this->departments?->listIDs() ?? [],
product_ids: $this->products?->listIDs() ?? [],
customer_numbers: $this->users?->listCustomerNumbers() ?? [],
datetime_start: $datetime_start,
datetime_end: $datetime_end,
);
$sum = 0;
foreach ($items as $item) {
$price = (int)$item->price->value();
$qty = (int)$item->quantity->value();
$sum += $price * $qty;
}
return $sum;
}
/**
* Public accessor for the current result based on criteria type.
* Allows external callers (e.g., goals class) to retrieve the computed result
* without duplicating switch logic.
*/
public function currentResult(): int|float
{
return $this->getProgress();
}
}