Files
contabilidad/api/src/Categoria.php

104 lines
2.8 KiB
PHP
Raw Normal View History

2021-07-27 22:29:56 -04:00
<?php
namespace Contabilidad;
2021-12-06 22:10:41 -03:00
use Carbon\Carbon;
2021-07-27 22:29:56 -04:00
use ProVM\Common\Alias\Model;
2021-12-06 22:10:41 -03:00
use Contabilidad\Common\Service\TiposCambios as Service;
2021-07-27 22:29:56 -04:00
/**
* @property int $id
* @property string $nombre
2021-11-01 11:00:59 -03:00
* @property TipoCategoria $tipo_id
2021-07-27 22:29:56 -04:00
*/
class Categoria extends Model {
public static $_table = 'categorias';
2021-12-06 22:10:41 -03:00
protected static $fields = ['nombre', 'tipo_id'];
2021-07-27 22:29:56 -04:00
protected $cuentas;
public function cuentas() {
if ($this->cuentas === null) {
$this->cuentas = $this->parentOf(Cuenta::class, [Model::CHILD_KEY => 'categoria_id']);
2022-01-05 15:58:03 -03:00
if ($this->cuentas !== null) {
usort($this->cuentas, function($a, $b) {
return strcmp($a->nombre, $b->nombre);
});
}
2021-07-27 22:29:56 -04:00
}
return $this->cuentas;
}
2021-11-01 11:00:59 -03:00
protected $tipo;
public function tipo() {
if ($this->tipo === null) {
$this->tipo = $this->childOf(TipoCategoria::class, [Model::SELF_KEY => 'tipo_id']);
}
return $this->tipo;
}
2021-07-30 16:38:09 -04:00
2021-12-06 22:10:41 -03:00
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;
}
2021-07-30 16:38:09 -04:00
protected $saldo;
2021-12-06 22:10:41 -03:00
public function saldo(Service $service = null) {
2021-07-30 16:38:09 -04:00
if ($this->saldo === null) {
$this->saldo = 0;
if ($this->cuentas() !== null) {
2021-12-06 22:10:41 -03:00
$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;
2021-07-30 16:38:09 -04:00
}
}
return $this->saldo;
}
2021-12-07 09:13:20 -03:00
public function toArray(): array {
$arr = parent::toArray();
$arr['tipo'] = $this->tipo()->toArray();
return $arr;
}
2021-07-27 22:29:56 -04:00
}