Files
contabilidad/api/src/Cuenta.php

87 lines
2.5 KiB
PHP
Raw Normal View History

2021-07-27 22:29:56 -04:00
<?php
namespace Contabilidad;
use ProVM\Common\Alias\Model;
/**
* @property int $id
* @property string $nombre
* @property Categoria $categoria_id
*/
class Cuenta extends Model {
public static $_table = 'cuentas';
protected static $fields = ['nombre', 'categoria_id'];
protected $categoria;
public function categoria() {
if ($this->categoria === null) {
$this->categoria = $this->childOf(Categoria::class, [Model::SELF_KEY => 'categoria_id']);
}
return $this->categoria;
}
protected $entradas;
public function entradas() {
if ($this->entradas === null) {
$this->entradas = $this->parentOf(Entrada::class, [Model::CHILD_KEY => 'cuenta_id']);
}
return $this->entradas;
}
2021-07-30 16:38:09 -04:00
protected $cargos;
public function cargos() {
if ($this->cargos === null) {
$this->cargos = $this->parentOf(Transaccion::class, [Model::CHILD_KEY => 'hasta_id']);
}
return $this->cargos;
}
protected $abonos;
public function abonos() {
if ($this->abonos === null) {
$this->abonos = $this->parentOf(Transaccion::class, [Model::CHILD_KEY => 'desde_id']);
}
return $this->abonos;
}
protected $transacciones;
public function transacciones($limit = null, $start = 0) {
2021-07-30 16:38:09 -04:00
if ($this->transacciones === null) {
$transacciones = Model::factory(Transaccion::class)
->join('cuentas', 'cuentas.id = transacciones.desde_id OR cuentas.id = transacciones.hasta_id')
->whereEqual('cuentas.id', $this->id)
->orderByAsc('transacciones.fecha');
if ($limit !== null) {
$transacciones = $transacciones->limit($limit)
->offset($start);
2021-07-30 16:38:09 -04:00
}
$this->transacciones = $transacciones->findMany();
foreach ($this->transacciones as &$transaccion) {
$transaccion->setFactory($this->factory);
if ($transaccion->desde_id === $this->id) {
$transaccion->valor = - $transaccion->valor;
2021-07-30 16:38:09 -04:00
}
}
2021-07-30 16:38:09 -04:00
}
return $this->transacciones;
}
protected $saldo;
public function saldo() {
if ($this->saldo === null) {
$this->saldo = 0;
if (count($this->transacciones()) > 0) {
$this->saldo = array_reduce($this->transacciones(), function($sum, $item) {
return $sum + $item->valor;
});
}
}
return $this->saldo;
}
2021-07-27 22:29:56 -04:00
public function toArray(): array {
$arr = parent::toArray();
$arr['categoria'] = $this->categoria()->toArray();
2021-07-30 16:38:09 -04:00
$arr['saldo'] = $this->saldo();
$arr['saldoFormateado'] = '$' . number_format($this->saldo(), 0, ',', '.');
2021-07-27 22:29:56 -04:00
return $arr;
}
}