total calculated – wyliczanie podrzędnych wartości

Wyliczanie wartości całkowitej ze wszystkich podrzędnych modeli.


Wyliczanie wartości całkowitej netto faktury z wartości na fakturze i pozycji podrzędnych. Dla walut obcych przeliczany jest kurs do złotówek.

use Cake\Collection\Collection;
.....
protected $_accessible = [ 'total_netto' => true, ... ];
....
protected function _getTotalNetto()
    {
      $netto = 0;
      if (isset($this->_fields['total_netto'])) { return $this->_fields['total_netto']; }

      // Lokalna wartość
      if($this->netto) {
        // Waluta obca
        if($this->currency_id > 1 && $this->exchange != 1) {
          $netto += ($this->netto * $this->exchange);
        } else {
          $netto += $this->netto;
        }
      }

      // Wartości powiązanego modelu - hasMany
      if (!empty($this->positions)) {
          $positions = new Collection($this->positions);
          $netto += $positions->reduce(function ($sum, $tag) {
            // Waluta obca
            if($this->currency_id > 1 && $this->exchange != 1) {
              return $sum + ($tag->netto * $this->exchange);
            } else {
              return $sum + $tag->netto;
            }
          }, 0);
      }
      return $netto;
    }

 

Tworzymy getter _getPrice(), który będzie dostępny w kontrolerze jako $this->MyModelname->price

use Cake\Collection\Collection;
...
protected $_accessible = [ 'price' => true, ...];
...
protected function _getPrice()
    {
      $price = 0;

      // pole wirtualne już jest wyliczone - nie wyliczaj 2 razy
      if (isset($this->_fields['price'])) {
        return $this->_fields['price'];
      }

      // Lokalna wartość
      if($this->working_hours) {
        $price = $this->working_hours * STAWKA_GODZ;
      }

      // Wartości powiązanego modelu - hasMany
      if (!empty($this->positions)) {
          $position = new Collection($this->positions);
          $price += $position->reduce(function ($sum, $tag) {
            return $sum + $tag->price;
          }, 0);
      }

      // Materiały - model belongsToMany
      if (!empty($this->materials)) {
          $material_price = new Collection($this->materials);
          $price += $material_price->reduce(function ($sum, $tag) {
            $amount = ($tag->_joinData['amount']) ? $tag->_joinData['amount'] : 0;
            return $sum + ($tag->price * $amount);
          }, 0);
      }

      // Maszyny - belongsToMany
      if (!empty($this->machines)) {
          $machines = new Collection($this->machines);
          $price += $machines->reduce(function ($sum, $tag) {
            $hours = ($tag->_joinData['hours']) ? $tag->_joinData['hours'] : 0;
            return $sum + ($tag->stawka * $hours);
          }, 0);
      }

      return $price;
    }