Files
contabilidad/api/src/Categoria.php
2021-12-06 22:10:41 -03:00

93 lines
2.5 KiB
PHP

<?php
namespace Contabilidad;
use Carbon\Carbon;
use ProVM\Common\Alias\Model;
use Contabilidad\Common\Service\TiposCambios as Service;
/**
* @property int $id
* @property string $nombre
* @property TipoCategoria $tipo_id
*/
class Categoria extends Model {
public static $_table = 'categorias';
protected static $fields = ['nombre', 'tipo_id'];
protected $cuentas;
public function cuentas() {
if ($this->cuentas === null) {
$this->cuentas = $this->parentOf(Cuenta::class, [Model::CHILD_KEY => 'categoria_id']);
}
return $this->cuentas;
}
protected $tipo;
public function tipo() {
if ($this->tipo === null) {
$this->tipo = $this->childOf(TipoCategoria::class, [Model::SELF_KEY => 'tipo_id']);
}
return $this->tipo;
}
public function getCuentasOf($tipo) {
return $this->factory->find(Cuenta::class)
->select([['cuentas', '*']])
->join([
['tipos_cuenta', 'tipos_cuenta.id', 'cuentas.tipo_id']
])
->where([
['tipos_cuenta.descripcion', $tipo],
['cuentas.categoria_id', $this->id]
])
->many();
}
protected $activos;
public function activos() {
if ($this->activos === null) {
$this->activos = $this->getCuentasOf('Activo');
}
return $this->activos();
}
protected $pasivos;
public function pasivos() {
if ($this->pasivos === null) {
$this->activos = $this->getCuentasOf('Pasivo');
}
return $this->pasivos;
}
protected $ganancias;
public function ganancias() {
if ($this->ganancias === null) {
$this->ganancias = $this->getCuentasOf('Ganancia');
}
return $this->ganancias;
}
protected $perdidas;
public function perdidas() {
if ($this->perdidas === null) {
$this->perdidas = $this->getCuentasOf('Perdida');
}
return $this->perdidas;
}
protected $saldo;
public function saldo(Service $service = null) {
if ($this->saldo === null) {
$this->saldo = 0;
if ($this->cuentas() !== null) {
$sum = 0;
$debitos = ['Activo', 'Perdida'];
foreach ($this->cuentas() as $cuenta) {
if (array_search($cuenta->tipo()->descripcion, $debitos) !== false) {
$sum -= $cuenta->saldo($service, true);
continue;
}
$sum += $cuenta->saldo($service, true);
}
$this->saldo = $sum;
}
}
return $this->saldo;
}
}