diff --git a/common/Alias/Model.php b/common/Alias/Model.php
new file mode 100644
index 0000000..88ef3c9
--- /dev/null
+++ b/common/Alias/Model.php
@@ -0,0 +1,87 @@
+id;
+ $orm = $this->orm;
+ $ref = new \ReflectionObject($orm);
+ if (!$ref->hasProperty('_dirty_fields')) {
+ return;
+ }
+ $dirty = $ref->getProperty('_dirty_fields');
+ $dirty->setAccessible(true);
+ $new_values = $dirty->getValue($orm);
+ $changes = array_combine(array_keys($new_values), array_fill(0, count($new_values), ['old' => '', 'new' => '']));
+ if ($this->isNew()) {
+ $old = (object) array_combine(array_keys($new_values), array_fill(0, count($new_values), ''));
+ } else {
+ $old = model(get_called_class())->findOne($this->{$this->getId()});
+ }
+ foreach ($new_values as $column => $value) {
+ $changes[$column] = ['column' => $column, 'old' => $old->$column, 'new' => $value];
+ }
+ $action = '[' . get_called_class() . ']';
+ doLog($user, $action, $changes);
+ }
+ public function getId()
+ {
+ if (property_exists(get_called_class(), '_id_column')) {
+ return static::$_id_column;
+ }
+ return $this->id;
+ }
+ public function save()
+ {
+ $ref = new \ReflectionObject($this);
+ if ($ref->hasProperty('_timestamps')) {
+ $ref = $ref->getProperty('_timestamps');
+ $ref->setAccessible(true);
+ if ($ref->getValue()) {
+ if ($this->is_new()) {
+ $this->setExpr('created_at', 'NOW()');
+ }
+ $this->setExpr('updated_at', 'NOW()');
+ }
+ }
+ if (!\ORM::getDb()->inTransaction()) {
+ \ORM::getDb()->beginTransaction();
+ }
+ try {
+ parent::save();
+ if (\ORM::getDb()->inTransaction()) {
+ \ORM::getDb()->commit();
+ }
+ } catch (\Exception $e) {
+ if (\ORM::getDb()->inTransaction()) {
+ \ORM::getDb()->rollBack();
+ }
+ throw $e;
+ }
+ $this->log();
+ }
+ public function __call($method, $args)
+ {
+ if (!method_exists($this, $method)) {
+ $str = '' . Stringy::create($method)->underscored();
+ if (method_exists($this, $str)) {
+ return call_user_func_array([$this, $str], $args);
+ }
+ throw new \BadMethodCallException($method . ' not found in ' . get_class($this));
+ }
+ return call_user_func_array([$this, $str], $args);
+ }
+}
+?>
diff --git a/common/Alias/NewEstado.php b/common/Alias/NewEstado.php
new file mode 100644
index 0000000..2ec1ba1
--- /dev/null
+++ b/common/Alias/NewEstado.php
@@ -0,0 +1,20 @@
+fecha, config('app.timezone'));
+ }
+}
+?>
diff --git a/common/Alias/NewModel.php b/common/Alias/NewModel.php
new file mode 100644
index 0000000..fbc209c
--- /dev/null
+++ b/common/Alias/NewModel.php
@@ -0,0 +1,9 @@
+
diff --git a/common/Alias/NewTipo.php b/common/Alias/NewTipo.php
new file mode 100644
index 0000000..e33d83c
--- /dev/null
+++ b/common/Alias/NewTipo.php
@@ -0,0 +1,15 @@
+
diff --git a/common/Alias/OldModel.php b/common/Alias/OldModel.php
new file mode 100644
index 0000000..f12a3cd
--- /dev/null
+++ b/common/Alias/OldModel.php
@@ -0,0 +1,8 @@
+
diff --git a/common/Factory/Model.php b/common/Factory/Model.php
new file mode 100644
index 0000000..2aef844
--- /dev/null
+++ b/common/Factory/Model.php
@@ -0,0 +1,204 @@
+class = $class;
+ $this->is_aggregator = true;
+ if (is_subclass_of($class, 'Model')) {
+ $this->is_aggregator = false;
+ }
+ }
+ public function new()
+ {
+ $class = $this->class;
+ if ($this->is_aggregator) {
+ return new $class();
+ }
+ return model($class)->create();
+ }
+ public function create($data)
+ {
+ $class = $this->class;
+ if ($this->is_aggregator) {
+ $obj = new $class();
+ $obj->create($data);
+ return $obj;
+ }
+ return model($class)->create($data);
+ }
+ /**
+ * [column => value, column => [value, operator]]
+ * @var array
+ */
+ protected $conditions;
+ public function where(array $data)
+ {
+ if ($this->conditions == null) {
+ $this->conditions = $data;
+ return $this;
+ }
+ $this->conditions = array_merge($this->conditions, $data);
+ return $this;
+ }
+ /**
+ * [column, column => order]
+ * @var array
+ */
+ protected $order;
+ public function order(array $data)
+ {
+ if ($this->order == null) {
+ $this->order = $data;
+ return $this;
+ }
+ $this->order = array_merge($this->order, $data);
+ return $this;
+ }
+ protected $limit;
+ public function limit(array $data)
+ {
+ if (!isset($data['limit'])) {
+ $data['limit'] = $data[0];
+ }
+ if (!isset($data['offset'])) {
+ $data['offset'] = 0;
+ if (isset($data[1])) {
+ $data['offset'] = $data[1];
+ }
+ }
+ $this->limit = (object) ['limit' => $data['limit'], 'offset' => $data['offset']];
+ return $this;
+ }
+ protected $many;
+ public function find($many = false)
+ {
+ $this->many = $many;
+ if ($this->is_aggregator) {
+ return $this->findAggregator();
+ }
+ return $this->findModel();
+ }
+
+ protected function findModel()
+ {
+ $objs = model($this->class);
+ $objs = $this->parseLimit($this->parseOrder($this->parseConditions($objs)));
+
+ if ($this->many) {
+ return $objs->findMany();
+ }
+ return $objs->findOne();
+ }
+ protected function parseConditions($orm)
+ {
+ if ($this->conditions == null) {
+ return $orm;
+ }
+ foreach ($this->conditions as $column => $value) {
+ if (is_array($value)) {
+ list($value, $op) = $value;
+ switch ($op) {
+ case '>':
+ case 'gt':
+ $orm = $orm->whereGt($column, $value);
+ break;
+ }
+ } else {
+ $orm = $orm->where($column, $value);
+ }
+ }
+ return $orm;
+ }
+ protected function parseOrder($orm)
+ {
+ if ($this->order == null) {
+ return $orm;
+ }
+ foreach ($this->order as $column => $order) {
+ if (is_numeric($column)) {
+ $column = $order;
+ $order = 'asc';
+ }
+ switch (strtolower($order)) {
+ case 'asc':
+ default:
+ $orm = $orm->orderByAsc($column);
+ break;
+ case 'desc':
+ $orm = $orm->orderByDesc($column);
+ break;
+ case 'expr':
+ $orm = $orm->orderByExpr($column);
+ break;
+ }
+ }
+ return $orm;
+ }
+ protected function parseLimit($orm)
+ {
+ if ($this->limit == null) {
+ return $orm;
+ }
+ $orm = $orm->limit($this->limit->limit);
+ if (isset($this->limit->offset)) {
+ $orm = $orm->offset($this->limit->offset);
+ }
+ return $orm;
+ }
+ protected function findAggregator()
+ {
+ $model = $this->modelName($this->class);
+ $ids = $this->getIds($model);
+ $class = $this->class;
+ if (count($ids) == 0) {
+ return false;
+ }
+ if ($this->many) {
+ $objs = [];
+ foreach ($ids as $id) {
+ $objs []= new $class($id);
+ }
+ } else {
+ $objs = new $class($ids[0]);
+ }
+ return $objs;
+ }
+ protected function getIds($model)
+ {
+ $id = $this->getModelId($model);
+ $table = $this->getTable($model);
+ $st = \ORM::forTable($table)->select($id);
+ $st = $this->parseConditions($st);
+ $results = $st->findArray();
+ $output = array_map(function($a) use($id) {
+ return $a[$id];
+ }, $results);
+ return $output;
+ }
+ protected function modelName($class)
+ {
+ $arr = explode("\\", $class);
+ \array_push($arr, end($arr));
+ return implode("\\", $arr);
+ }
+ protected function getModelId($model)
+ {
+ $table = $this->getTable($model);
+ $query = "SHOW KEYS FROM {$table} WHERE Key_name = 'PRIMARY'";
+ $st = \ORM::getDb()->query($query);
+ $results = $st->fetchAll(\PDO::FETCH_OBJ);
+ return $results[0]->Column_name;
+ }
+ protected function getTable($model)
+ {
+ $arr = explode("\\", $model);
+ return Stringy::create(end($arr))->toLowerCase() . '';
+ }
+}
diff --git a/composer.json b/composer.json
new file mode 100644
index 0000000..55767f2
--- /dev/null
+++ b/composer.json
@@ -0,0 +1,26 @@
+{
+ "name": "incoviba/modelos",
+ "description": "Modelos para Incoviba",
+ "type": "library",
+ "require": {
+ "j4mie/paris": "^1.5",
+ "nesbot/carbon": "^2.28"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^8.5",
+ "kint-php/kint": "^3.3"
+ },
+ "license": "UNLICENSED",
+ "authors": [
+ {
+ "name": "Aldarien",
+ "email": "aldarien85@gmail.com"
+ }
+ ],
+ "autoload": {
+ "psr-4": {
+ "Incoviba\\Common\\": "common",
+ "Incoviba\\": "src"
+ }
+ }
+}
diff --git a/src/common/Action.php b/src/common/Action.php
new file mode 100644
index 0000000..8a46229
--- /dev/null
+++ b/src/common/Action.php
@@ -0,0 +1,12 @@
+belongsTo(User::class, 'user_id')->findOne();
+ }
+ public function token($token = null)
+ {
+ if ($token == null) {
+ return false;
+ }
+ $this->token = \password_hash($token, \PASSWORD_DEFAULT);
+ }
+ public function time($time = null)
+ {
+ if ($time == null) {
+ return Carbon::parse($this->time, config('app.timezone'));
+ }
+ if (!\is_a($time, \DateTime::class)) {
+ $time = Carbon::parse($time, config('app.timezone'));
+ }
+ $this->time = $time;
+ }
+ public function save()
+ {
+ if (!\is_string($this->time)) {
+ $this->time = $this->time->format('Y-m-d H:i:s');
+ }
+ parent::save();
+ }
+ public function isIn()
+ {
+ if ($this->status == 0) {
+ return false;
+ }
+ $now = Carbon::now(config('app.timezone'));
+ $diff = $now->diffAsCarbonInterval($this->time, true);
+ if ($diff->totalHours > config('app.login_hours')) {
+ return false;
+ }
+ return true;
+ }
+}
+?>
diff --git a/src/common/Location.php b/src/common/Location.php
new file mode 100644
index 0000000..5d3323d
--- /dev/null
+++ b/src/common/Location.php
@@ -0,0 +1,23 @@
+hasMany(Permission::class, 'location')->findMany();
+ }
+}
+?>
diff --git a/src/common/Permission.php b/src/common/Permission.php
new file mode 100644
index 0000000..c283e7e
--- /dev/null
+++ b/src/common/Permission.php
@@ -0,0 +1,49 @@
+all == 0) {
+ return $this->belongsTo(Location::class, 'location')->findOne();
+ }
+ if ($this->locations == null) {
+ $this->locations = \Model::factory(Location::class)->findMany();
+ }
+ return $this->locations;
+ }*/
+ public function who()
+ {
+ switch ($this->type) {
+ case 1:
+ return $this->belongsTo(User::class, 'ext_id')->findOne();
+ case 2:
+ return $this->belongsTo(Role::class, 'ext_id')->findOne();
+ }
+ }
+ public function action()
+ {
+ return $this->belongsTo(Action::class, 'action_id')->findOne();
+ }
+}
+?>
diff --git a/src/common/Registry.php b/src/common/Registry.php
new file mode 100644
index 0000000..aae8a0a
--- /dev/null
+++ b/src/common/Registry.php
@@ -0,0 +1,64 @@
+belongsTo(User::class, 'user')->findOne();
+ }
+ protected $model;
+ public function model()
+ {
+ if ($this->model == null) {
+ list($model, $actions) = explode(']', $this->action);
+ $model = str_replace(['Incoviba\\old\\', 'Incoviba\\nuevo\\', '\\'], ['', '', '->'], trim($model, '['));
+ $this->model = $model;
+ }
+ return $this->model;
+ }
+ protected $actions;
+ public function actions()
+ {
+ if ($this->actions == null) {
+ list($model, $actions) = explode(']', $this->action);
+ $actions = explode(', ', trim($actions));
+ $resultados = [];
+ foreach ($actions as $action) {
+ if (strpos($action, ': ') !== false) {
+ list($columna, $valor) = explode(': ', $action);
+ } else {
+ $columna = '';
+ $valor = $action;
+ }
+ if (strpos($valor, ' -> ') !== false) {
+ list($old, $new) = explode(' -> ', $valor);
+ } else {
+ $old = '';
+ $new = $valor;
+ }
+ $resultados[$columna] = (object) ['old' => $old, 'new' => $new];
+ }
+ $this->actions = $resultados;
+ }
+ return $this->actions;
+ }
+ public function time(Carbon $time = null)
+ {
+ if ($time == null) {
+ return Carbon::parse($this->time);
+ }
+ $this->time = $time->toDateTimeString();
+ }
+}
diff --git a/src/common/RegistryData.php b/src/common/RegistryData.php
new file mode 100644
index 0000000..18dee39
--- /dev/null
+++ b/src/common/RegistryData.php
@@ -0,0 +1,16 @@
+inherits != 0) {
+ return $this->belongsTo(Role::class, 'inherits')->findOne();
+ }
+ return false;
+ }
+ protected $permissions;
+ public function permissions()
+ {
+ if ($this->permissions == null) {
+ $permissions = $this->hasMany(Permission::class, 'ext_id')->where('permissions.type', 2)->findMany();
+ if ($this->inherits()) {
+ $permissions = array_merge($permissions, $this->inherits()->permissions());
+ }
+ usort($permissions, function($a, $b) {
+ return strcmp($a->action()->description, $b->action()->description);
+ });
+ $this->permissions = $permissions;
+ }
+ return $this->permissions;
+ }
+ public function users()
+ {
+ return $this->hasManyThrough(User::class, UserRole::class, 'role', 'user')->findMany();
+ }
+ public function hasAccess($route)
+ {
+ $action = $route->getArgument('action');
+ $action = (new Factory(Action::class))->where(['description' => $action])->find();
+ if (!$action) {
+ return false;
+ }
+
+ $data = [
+ 'type' => 2,
+ 'ext_id' => $this->id,
+ 'action_id' => $action->id,
+ 'status' => 1
+ ];
+ $permission = (new Factory(Permission::class))->where($data)->find();
+ if ($permission !== false) {
+ return true;
+ }
+
+ if ($this->inherits()) {
+ return $this->inherits()->hasAccess($route);
+ }
+ return false;
+ }
+ public function checkAccess($action_name)
+ {
+ $action = (new Factory(Action::class))->where(['description' => $action_name])->find();
+ if (!$action) {
+ throw new \Exception('Action ' . $action_name . ' not found.');
+ }
+ $permission = (new Factory(Permission::class))->where([
+ 'type' => 2,
+ 'ext_id' => $this->id,
+ 'action_id' => $action->id,
+ 'status' => 1
+ ])->find();
+ if ($permission !== false) {
+ return true;
+ }
+ if ($this->inherits()) {
+ return $this->inherits()->checkAccess($action_name);
+ }
+ return false;
+ }
+ public function addPermission($action_name)
+ {
+ if ($this->checkAccess($action_name)) {
+ return;
+ }
+ $action = (new Factory(Action::class))->where(['description' => $action_name])->find();
+ if (!$action) {
+ throw new \InvalidArgumentException($action_name . ' not found.');
+ }
+ $data = [
+ 'type' => 2,
+ 'ext_id' => $this->id,
+ 'action_id' => $action->id
+ ];
+ $permission = (new Factory(Permission::class))->where($data)->find();
+ if (!$permission) {
+ $permission = (new Factory(Permission::class))->create($data);
+ }
+ $permission->status = 1;
+ $permission->save();
+ }
+ public function removePermission($action_name)
+ {
+ if (!$this->checkAccess($action_name)) {
+ return;
+ }
+ $action = (new Factory(Action::class))->where(['description' => $action_name])->find();
+ if (!$action) {
+ throw new \InvalidArgumentException($action_name . ' not found.');
+ }
+ $data = [
+ 'type' => 2,
+ 'ext_id' => $this->id,
+ 'action_id' => $action->id
+ ];
+ $permission = (new Factory(Permission::class))->where($data)->find();
+ if (!$permission) {
+ return;
+ }
+ $permission->status = 0;
+ $permission->save();
+ }
+ public function hasUser($user)
+ {
+ $user = \Model::factory(User::class)
+ ->select('users.*')
+ ->join('user_roles', ['user_roles.user', '=', 'users.id'])
+ ->join('roles', ['roles.id', '=', 'user_roles.role'])
+ ->where('roles.id', $this->id)
+ ->whereAnyIs([['users.name' => $user], ['users.id' => $user]])
+ ->findOne();
+ if ($user !== false) {
+ return true;
+ }
+ return false;
+ }
+ public function isInherited($action_name)
+ {
+ if (!$this->checkAccess($action_name)) {
+ return false;
+ }
+ $action = (new Factory(Action::class))->where(['description' => $action_name])->find();
+ $permission = (new Factory(Permission::class))->where([
+ 'type' => 2,
+ 'ext_id' => $this->id,
+ 'action_id' => $action->id,
+ 'status' => 1
+ ])->find();
+ if ($permission !== false) {
+ return false;
+ }
+ return true;
+ }
+}
+?>
diff --git a/src/common/User.php b/src/common/User.php
new file mode 100644
index 0000000..7d4844e
--- /dev/null
+++ b/src/common/User.php
@@ -0,0 +1,104 @@
+password = \password_hash($password, \PASSWORD_BCRYPT);
+ }
+ protected $permissions = null;
+ public function permissions()
+ {
+ if ($this->permissions == null) {
+ $permissions = $this->hasMany(Permission::class, 'ext_id')->where('permissions.type', 1)->findMany();
+ if ($permissions == false) {
+ $permissions = [];
+ }
+ foreach ($this->roles() as $role) {
+ $rp = $role->permissions();
+ if ($rp !== false) {
+ $permissions = array_merge($permissions, $rp);
+ }
+ }
+ if (count($permissions) == 0) {
+ $permissions = false;
+ }
+ $this->permissions = $permissions;
+ }
+ return $this->permissions;
+ }
+ public function roles()
+ {
+ return $this->hasManyThrough(Role::class, UserRole::class, 'user', 'role')->findMany();
+ }
+ public function hasAccess($route)
+ {
+ foreach ($this->roles() as $role) {
+ if ($role->hasAccess($route) === true) {
+ return true;
+ }
+ }
+
+ $action = $route->getArgument('action');
+ $action = (new Factory(Action::class))->where(['description' => $action])->find();
+ if (!$action) {
+ return false;
+ }
+
+ $data = [
+ 'type' => 1,
+ 'ext_id' => $this->id,
+ 'action_id' => $action->id,
+ 'status' => 1
+ ];
+ $permission = (new Factory(Permission::class))->where($data)->find();
+ if ($permission !== false) {
+ return true;
+ }
+ return false;
+ }
+ public function checkAccess($action_name)
+ {
+ foreach ($this->roles() as $role) {
+ if ($role->checkAccess($action_name) === true) {
+ return true;
+ }
+ }
+ $action = (new Factory(Action::class))->where(['description' => $action_name])->find();
+
+ $permission = (new Factory(Permission::class))->where([
+ 'type' => 1,
+ 'ext_id' => $this->id,
+ 'action_id' => $action->id,
+ 'status' => 1
+ ])->find();
+ if ($permission !== false) {
+ return true;
+ }
+ return false;
+ }
+ public function hasRole($role)
+ {
+ foreach ($this->roles() as $r) {
+ if ($r->description == $role or $r->id == $role) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
diff --git a/src/common/UserRole.php b/src/common/UserRole.php
new file mode 100644
index 0000000..646bf01
--- /dev/null
+++ b/src/common/UserRole.php
@@ -0,0 +1,26 @@
+belongsTo(User::class, 'user')->findOne();
+ }
+ public function role()
+ {
+ return $this->belongsTo(Role::class, 'role')->findOne();
+ }
+}
+?>
diff --git a/src/nuevo/Common/Banco.php b/src/nuevo/Common/Banco.php
new file mode 100644
index 0000000..365cbb8
--- /dev/null
+++ b/src/nuevo/Common/Banco.php
@@ -0,0 +1,22 @@
+has_many(\Incoviba\nuevo\Inmobiliaria\Cuenta::class, 'banco_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Common/Comuna.php b/src/nuevo/Common/Comuna.php
new file mode 100644
index 0000000..4e25192
--- /dev/null
+++ b/src/nuevo/Common/Comuna.php
@@ -0,0 +1,27 @@
+belongs_to(Provincia::class, 'provincia_id')->findOne();
+ }
+ public function direcciones()
+ {
+ return $this->has_many(Direccion::class, 'comuna_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Common/Direccion.php b/src/nuevo/Common/Direccion.php
new file mode 100644
index 0000000..b195681
--- /dev/null
+++ b/src/nuevo/Common/Direccion.php
@@ -0,0 +1,24 @@
+belongs_to(Comuna::class, 'comuna_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Common/M2.php b/src/nuevo/Common/M2.php
new file mode 100644
index 0000000..9c4f05d
--- /dev/null
+++ b/src/nuevo/Common/M2.php
@@ -0,0 +1,33 @@
+has_many(\Incoviba\nuevo\Proyecto\UnidadProyecto::class, 'm2_id')->findMany();
+ }
+ public function vendibles()
+ {
+ return $this->util + $this->logia + $this->terraza / 2 + $this->cubierta / 3;
+ }
+ public function total()
+ {
+ return $this->util + $this->logia + $this->terraza + $this->cubierta;
+ }
+}
diff --git a/src/nuevo/Common/Provincia.php b/src/nuevo/Common/Provincia.php
new file mode 100644
index 0000000..2f74d80
--- /dev/null
+++ b/src/nuevo/Common/Provincia.php
@@ -0,0 +1,27 @@
+belongs_to(Region::class, 'region_id')->findOne();
+ }
+ public function comunas()
+ {
+ return $this->has_many(Comuna::class, 'provincia_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Common/Region.php b/src/nuevo/Common/Region.php
new file mode 100644
index 0000000..e3e211e
--- /dev/null
+++ b/src/nuevo/Common/Region.php
@@ -0,0 +1,24 @@
+has_many(Provincia::class, 'region_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Common/UF.php b/src/nuevo/Common/UF.php
new file mode 100644
index 0000000..53f7329
--- /dev/null
+++ b/src/nuevo/Common/UF.php
@@ -0,0 +1,33 @@
+fecha, config('app.timezone'));
+ $uf = uf($fecha);
+
+ if ($uf != null) {
+ $this->valor = $uf->uf->value;
+ }
+ }
+
+}
diff --git a/src/nuevo/Inmobiliaria/Agente.php b/src/nuevo/Inmobiliaria/Agente.php
new file mode 100644
index 0000000..2b7d828
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/Agente.php
@@ -0,0 +1,47 @@
+belongsTo(Representante::class, 'representante_rut', 'rut')->findOne();
+ }
+ public function direccion()
+ {
+ return $this->belongsTo(Direccion::class, 'direccion_id')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongsTo(TipoAgente::class, 'tipo_agente_id')->findOne();
+ }
+ public function contratos()
+ {
+ return $this->hasMany(Contrato::class, 'agente_id')->findMany();
+ }
+ public function comision($inmobiliaria_rut)
+ {
+ return $this->hasMany(Contrato::class, 'agente_id')->where('inmobiliaria_rut', $inmobiliaria_rut)->sum('valor');
+ }
+}
diff --git a/src/nuevo/Inmobiliaria/CategoriaCuentaContable.php b/src/nuevo/Inmobiliaria/CategoriaCuentaContable.php
new file mode 100644
index 0000000..8c6de25
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/CategoriaCuentaContable.php
@@ -0,0 +1,21 @@
+hasMany(CuentaContable::class, 'categoria_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Inmobiliaria/Cobro.php b/src/nuevo/Inmobiliaria/Cobro.php
new file mode 100644
index 0000000..ed856f2
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/Cobro.php
@@ -0,0 +1,36 @@
+belongsTo(Contrato::class, 'contrato_id')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongsTo(TipoCobro::class, 'tipo_cobro_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Inmobiliaria/Contrato.php b/src/nuevo/Inmobiliaria/Contrato.php
new file mode 100644
index 0000000..903f7f6
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/Contrato.php
@@ -0,0 +1,37 @@
+belongsTo(Inmobiliaria::class, 'inmobiliaria_rut', 'rut')->findOne();
+ }
+ public function agente()
+ {
+ return $this->belongsTo(Agente::class, 'agente_id')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongsTo(TipoContrato::class, 'tipo_contrato_id')->findOne();
+ }
+ public function cobros()
+ {
+ return $this->hasMany(Cobro::class, 'contrato_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Inmobiliaria/Cuenta.php b/src/nuevo/Inmobiliaria/Cuenta.php
new file mode 100644
index 0000000..94dbfc8
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/Cuenta.php
@@ -0,0 +1,31 @@
+belongsTo(Inmobiliaria::class, 'inmobiliaria_rut', 'rut')->findOne();
+ }
+ public function banco()
+ {
+ return $this->belongsTo(Banco::class, 'banco_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Inmobiliaria/CuentaContable.php b/src/nuevo/Inmobiliaria/CuentaContable.php
new file mode 100644
index 0000000..7c28136
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/CuentaContable.php
@@ -0,0 +1,44 @@
+belongsTo(Inmobiliaria::class, 'inmobiliaria_rut', 'rut')->findOne();
+ }
+ public function categoria()
+ {
+ return $this->belongsTo(CategoriaCuentaContable::class, 'categoria_id')->findOne();
+ }
+ public function cargos()
+ {
+ return $this->hasMany(TransaccionContable::class, 'cuenta_de')->findMany();
+ }
+ public function abonos()
+ {
+ return $this->hasMany(TransaccionContable::class, 'cuenta_para')->findMany();
+ }
+ public function transacciones()
+ {
+ $transacciones = model(TransaccionContable::class)->whereAnyIs([['cuenta_de', $this->id], ['cuenta_para', $this->id]])->orderByAsc('fecha')->findMany();
+ return $transacciones;
+ }
+ public function unidades()
+ {
+ return null;
+ }
+}
diff --git a/src/nuevo/Inmobiliaria/EstadoCobro.php b/src/nuevo/Inmobiliaria/EstadoCobro.php
new file mode 100644
index 0000000..251c914
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/EstadoCobro.php
@@ -0,0 +1,26 @@
+belongsTo(Cobro::class, 'cobro_id')->findOne();
+ }
+ public function estado()
+ {
+ return $this->belongsTo(TipoEstadoCobro::class, 'estado_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Inmobiliaria/Inmobiliaria.php b/src/nuevo/Inmobiliaria/Inmobiliaria.php
new file mode 100644
index 0000000..c28388a
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/Inmobiliaria.php
@@ -0,0 +1,50 @@
+belongs_to(Direccion::class, 'direccion_id')->findOne();
+ }
+ public function representante()
+ {
+ return $this->belongs_to(Representante::class, 'representante_rut', 'rut')->findOne();
+ }
+ public function estado()
+ {
+ return ($estado != 0);
+ }
+
+ public function proyectos()
+ {
+ return $this->has_many(Proyecto::class, 'inmobiliaria_rut', 'rut')->findMany();
+ }
+ public function inversionistas()
+ {
+ return $this->has_many_through(Socio::class, Participacion::class, 'socio_id', 'inmobiliaria_rut', 'rut')->findMany();
+ }
+}
+?>
\ No newline at end of file
diff --git a/src/nuevo/Inmobiliaria/Participacion.php b/src/nuevo/Inmobiliaria/Participacion.php
new file mode 100644
index 0000000..f56388a
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/Participacion.php
@@ -0,0 +1,27 @@
+belongsTo(Inmobiliaria::class, 'inmobiliaria_rut', 'rut')->findOne();
+ }
+ public function socio()
+ {
+ return $this->belongsTo(Socio::class, 'socio_rut', 'rut')->findOne();
+ }
+}
diff --git a/src/nuevo/Inmobiliaria/Representante.php b/src/nuevo/Inmobiliaria/Representante.php
new file mode 100644
index 0000000..1bc76b3
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/Representante.php
@@ -0,0 +1,56 @@
+belongsTo(Direccion::class, 'direccion_id')->findMany();
+ }
+ public function nombreCompleto()
+ {
+ return $this->nombres . ' ' . $this->apellidos;
+ }
+
+ public function inmobiliarias()
+ {
+ return $this->hasMany(Inmobiliaria::class, 'representante_rut', 'rut')->findMany();
+ }
+ public function agentes()
+ {
+ return $this->hasMany(Agente::class, 'representante_rut', 'rut')->findMany();
+ }
+ public function apelativo()
+ {
+ if ($this->sexo == 'f') {
+ return 'doña';
+ }
+ return 'don';
+ }
+ public function articulo()
+ {
+ if ($this->sexo == 'f') {
+ return 'la';
+ }
+ return 'el';
+ }
+}
diff --git a/src/nuevo/Inmobiliaria/Socio.php b/src/nuevo/Inmobiliaria/Socio.php
new file mode 100644
index 0000000..dddd84e
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/Socio.php
@@ -0,0 +1,23 @@
+hasMany(Participacion::class, 'socio_rut', 'rut')->findMany();
+ }
+}
diff --git a/src/nuevo/Inmobiliaria/TipoAgente.php b/src/nuevo/Inmobiliaria/TipoAgente.php
new file mode 100644
index 0000000..7455f90
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/TipoAgente.php
@@ -0,0 +1,22 @@
+hasMany(Agente::class, 'tipo_agente_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Inmobiliaria/TipoCobro.php b/src/nuevo/Inmobiliaria/TipoCobro.php
new file mode 100644
index 0000000..3bb0f1a
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/TipoCobro.php
@@ -0,0 +1,22 @@
+hasMany(Cobro::class, 'tipo_cobro_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Inmobiliaria/TipoContrato.php b/src/nuevo/Inmobiliaria/TipoContrato.php
new file mode 100644
index 0000000..15ae99d
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/TipoContrato.php
@@ -0,0 +1,22 @@
+hasMany(Contrato::class)->findMany();
+ }
+}
diff --git a/src/nuevo/Inmobiliaria/TipoEstadoCobro.php b/src/nuevo/Inmobiliaria/TipoEstadoCobro.php
new file mode 100644
index 0000000..777e97f
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/TipoEstadoCobro.php
@@ -0,0 +1,22 @@
+hasMany(EstadoCobro::class, 'estado_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Inmobiliaria/TransaccionContable.php b/src/nuevo/Inmobiliaria/TransaccionContable.php
new file mode 100644
index 0000000..ddbbed5
--- /dev/null
+++ b/src/nuevo/Inmobiliaria/TransaccionContable.php
@@ -0,0 +1,46 @@
+belongsTo(CuentaContable::class, 'cuenta_de');
+ }
+ public function para()
+ {
+ return $this->belongsTo(CuentaContable::class, 'cuenta_para');
+ }
+
+ public function valor($tipo = 'pesos')
+ {
+ if ($tipo == 'ufs') {
+ $uf = model(UF::class)->where('fecha', $this->fecha)->findOne();
+ if (!$uf) {
+ $uf = model(UF::class)->create();
+ $uf->fecha = $this->fecha;
+ $uf->getValor();
+ $uf->save();
+ }
+ return ($this->valor / $uf->valor) ?: 0;
+ }
+ return $this->valor;
+ }
+}
diff --git a/src/nuevo/Proyecto/EstadoProyecto.php b/src/nuevo/Proyecto/EstadoProyecto.php
new file mode 100644
index 0000000..c400628
--- /dev/null
+++ b/src/nuevo/Proyecto/EstadoProyecto.php
@@ -0,0 +1,25 @@
+belongsTo(Proyecto::class, 'proyecto_id')->findOne();
+ }
+ public function estado()
+ {
+ return $this->belongsTo(TipoEstadoProyecto::class, 'estado_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Proyecto/Etapa.php b/src/nuevo/Proyecto/Etapa.php
new file mode 100644
index 0000000..9dbda32
--- /dev/null
+++ b/src/nuevo/Proyecto/Etapa.php
@@ -0,0 +1,22 @@
+hasMany(TipoEstadoProyecto::class, 'etapa_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Proyecto/Participe.php b/src/nuevo/Proyecto/Participe.php
new file mode 100644
index 0000000..1aafd6f
--- /dev/null
+++ b/src/nuevo/Proyecto/Participe.php
@@ -0,0 +1,27 @@
+hasManyThrough(Proyecto::class, ProyectoParticipe::class, 'proyecto_id', 'participe_rut', 'rut')->findMany();
+ }
+ public function participaciones()
+ {
+ return $this->hasMany(ProyectoParticipe::class, 'participe_rut', 'rut')->findMany();
+ }
+}
diff --git a/src/nuevo/Proyecto/Proyecto.php b/src/nuevo/Proyecto/Proyecto.php
new file mode 100644
index 0000000..922573e
--- /dev/null
+++ b/src/nuevo/Proyecto/Proyecto.php
@@ -0,0 +1,132 @@
+belongsTo(Inmobiliaria::class, 'inmobiliaria_rut', 'rut')->findOne();
+ }
+ public function direccion()
+ {
+ return $this->belongsTo(Direccion::class, 'direccion_id')->findOne();
+ }
+
+ public function participaciones()
+ {
+ return $this->hasMany(ProyectoParticipe::class, 'proyecto_id')->findMany();
+ }
+ public function participes()
+ {
+ return $this->hasManyThrough(Participe::class, ProyectoParticipe::class, 'proyecto_id', 'participe_rut', 'rut')->findMany();
+ }
+ public function unidades()
+ {
+ return $this->hasMany(UnidadProyecto::class, 'proyecto_id')->findMany();
+ }
+ public function cantidad($tipo = 'departamento')
+ {
+ $total = 0;
+ $unidades = $this->unidades;
+ foreach ($unidades as $unidad) {
+ if ($unidad->tipo->descripcion == $tipo) {
+ $total += $unidad->unidades->count();
+ }
+ }
+ return $total;
+ }
+ public function unidadesPrincipales()
+ {
+ if ($this->tipoUnidades()) {
+ return $this->cantidad('departamento');
+ } else {
+ return $this->cantidad('casa');
+ }
+ }
+ public function pisos()
+ {
+ $max_piso = 0;
+ $unidades = $this->unidades;
+ foreach ($unidades as $unidad) {
+ $piso = $unidad->unidades->max('piso');
+ if ($max_piso < $piso) {
+ $max_piso = $piso;
+ }
+ }
+ return $max_piso;
+ }
+ public function m2Construidos()
+ {
+ $total = 0;
+ $unidades = $this->unidades;
+ foreach ($unidades as $unidad) {
+ $total += $unidad->m2->total() * $unidad->unidades->count();
+ }
+ return $total;
+ }
+ public function tipoUnidades()
+ {
+ return (!$this->unidades->isEmpty() and $this->unidades[0]->tipo->descripcion == 'departamento');
+ }
+ public function ventas()
+ {
+ $ventas = [];
+ foreach ($this->unidades as $up) {
+ foreach ($up->unidades as $u) {
+ if (isset($u->propiedad)) {
+ $ventas->add($u->propiedad->venta);
+ }
+ }
+ }
+ $ventas = sort($ventas, function($a, $b) {
+ return $a->propiedad->unidadPrincipal->numeracion - $b->propiedad->unidadPrincipal->numeracion;
+ });
+ return $ventas;
+ }
+ public function ventasActivas()
+ {
+ $ventas = $this->ventas();
+ $output = [];
+ foreach ($ventas as $venta) {
+ $estado = $venta->ultimoEstado()->estado->descripcion;
+ if ($estado == 'promesado' or $estado == 'escriturado' or $estado == 'entregado') {
+ $output []= $venta;
+ }
+ }
+ return $output;
+ }
+ public function pVendido()
+ {
+ return $this->ventasActivas()->count() / $this->unidadesPrincipales();
+ }
+ public function m2Vendidos()
+ {
+ $ventas = $this->ventasActivas();
+ $sum = 0;
+ foreach ($ventas as $venta) {
+ $sum += $venta->propiedad->unidadPrincipal->unidadProyecto->m2->vendibles();
+ }
+ return $sum;
+ }
+}
diff --git a/src/nuevo/Proyecto/ProyectoParticipe.php b/src/nuevo/Proyecto/ProyectoParticipe.php
new file mode 100644
index 0000000..743e218
--- /dev/null
+++ b/src/nuevo/Proyecto/ProyectoParticipe.php
@@ -0,0 +1,27 @@
+belongsTo(Proyecto::class, 'proyecto_id')->findOne();
+ }
+ public function participe()
+ {
+ $this->belongsTo(Participe::class, 'participe_rut', 'rut')->findOne();
+ }
+}
diff --git a/src/nuevo/Proyecto/Tema.php b/src/nuevo/Proyecto/Tema.php
new file mode 100644
index 0000000..8f665e5
--- /dev/null
+++ b/src/nuevo/Proyecto/Tema.php
@@ -0,0 +1,75 @@
+belongsTo(Proyecto::class)->findOne();
+ if ($proyecto) {
+ return $proyecto;
+ }
+ return $this->belongsTo(P::class)->findOne();
+ }
+ public function inicio()
+ {
+ return Carbon::parse($this->inicio, config('app.timezone'));
+ }
+ public function cierre()
+ {
+ return Carbon::parse($this->cierre, config('app.timezone'));
+ }
+ public function texto()
+ {
+ $text = $this->texto;
+ $text = explode("\n", $text);
+ foreach ($text as &$line) {
+ $line = trim(rtrim($line, '.')) . '.';
+ if ($line != ltrim($line, '-')) {
+ $line = ' ' . $line;
+ }
+ }
+ $text = implode('
', $text);
+
+ preg_match_all('/\[\[.*\]\]/', $text, $matches);
+ $search = [];
+ $replace = [];
+ if (count($matches[0]) > 0) {
+ foreach ($matches[0] as $match) {
+ $search []= $match;
+ list($model, $where, $value) = explode(':', str_replace(['[',']'], ['', ''], $match));
+ $class = '\\Incoviba\\old\\' . $model;
+ $obj = model($class)->where($where, $value)->findOne();
+
+ $str = $value;
+ if ($obj->venta()) {
+ $str = '' . $value . '';
+ }
+ $replace []= $str;
+ }
+ }
+
+ $text = str_replace($search, $replace, $text);
+
+ return $text;
+ }
+}
+?>
\ No newline at end of file
diff --git a/src/nuevo/Proyecto/TipoEstadoProyecto.php b/src/nuevo/Proyecto/TipoEstadoProyecto.php
new file mode 100644
index 0000000..8d87e4d
--- /dev/null
+++ b/src/nuevo/Proyecto/TipoEstadoProyecto.php
@@ -0,0 +1,28 @@
+belongsTo(Etapa::class, 'etapa_id')->findOne();
+ }
+
+ public function estados()
+ {
+ return $this->hasMany(EstadoProyecto::class, 'estado_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Proyecto/TipoUnidad.php b/src/nuevo/Proyecto/TipoUnidad.php
new file mode 100644
index 0000000..2eb403d
--- /dev/null
+++ b/src/nuevo/Proyecto/TipoUnidad.php
@@ -0,0 +1,21 @@
+hasMany(UnidadProyecto::class, 'tipo_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Proyecto/UnidadProyecto.php b/src/nuevo/Proyecto/UnidadProyecto.php
new file mode 100644
index 0000000..0cd665c
--- /dev/null
+++ b/src/nuevo/Proyecto/UnidadProyecto.php
@@ -0,0 +1,50 @@
+belongsTo(Proyecto::class, 'proyecto_id')->findOne();
+ }
+ public function m2()
+ {
+ return $this->belongsTo(M2::class, 'm2_id')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongsTo(TipoUnidad::class, 'tipo_id')->findOne();
+ }
+ public function unidades()
+ {
+ return $this->hasMany(Unidad::class, 'unidad_proyecto_id')->findMany();
+ }
+ public function orientaciones()
+ {
+ $orientaciones = [];
+ foreach ($this->unidades as $unidad) {
+ if (array_search($unidad->orientacion, $orientaciones) === false) {
+ $orientaciones []= $unidad->orientacion;
+ }
+ }
+ return $orientaciones;
+ }
+}
diff --git a/src/nuevo/Venta/Cierre.php b/src/nuevo/Venta/Cierre.php
new file mode 100644
index 0000000..ce5a28e
--- /dev/null
+++ b/src/nuevo/Venta/Cierre.php
@@ -0,0 +1,59 @@
+belongsTo(Proyecto::class, 'proyecto_id')->findOne();
+ }
+ public function agente()
+ {
+ return $this->belongsTo(Agente::class, 'agente_id')->findOne();
+ }
+ public function propietario()
+ {
+ return $this->belongsTo(Propietario::class, 'propietario_rut')->findOne();
+ }
+ public function reserva()
+ {
+ return $this->belongsTo(Reserva::class, 'reserva_id')->findOne();
+ }
+ public function fecha()
+ {
+ return Carbon::parse($this->fecha, config('app.timezone'));
+ }
+ public function pie($type = 'ufs')
+ {
+ if ($type == 'ufs') {
+ return $this->pie;
+ }
+ $uf = uf($this->fecha());
+ return $this->pie * $uf->uf->value;
+ }
+}
+?>
\ No newline at end of file
diff --git a/src/nuevo/Venta/Comentario.php b/src/nuevo/Venta/Comentario.php
new file mode 100644
index 0000000..4c99f66
--- /dev/null
+++ b/src/nuevo/Venta/Comentario.php
@@ -0,0 +1,23 @@
+belongsTo(Venta::class, 'venta_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Venta/Cuota.php b/src/nuevo/Venta/Cuota.php
new file mode 100644
index 0000000..d273578
--- /dev/null
+++ b/src/nuevo/Venta/Cuota.php
@@ -0,0 +1,27 @@
+belongsTo(Pie::class, 'pie_id')->findOne();
+ }
+ public function pago()
+ {
+ return $this->belongsTo(Pago::class, 'pago_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Venta/Entrega.php b/src/nuevo/Venta/Entrega.php
new file mode 100644
index 0000000..fb15691
--- /dev/null
+++ b/src/nuevo/Venta/Entrega.php
@@ -0,0 +1,47 @@
+belongs_to(Venta::class, 'venta_id')->findOne();
+ }
+
+ public function fondos()
+ {
+ return $this->has_many_through(Pago::class, FondoEntrega::class, 'entrega_id', 'pago_id')->findMany();
+ }
+ public function mediciones()
+ {
+ return $this->has_many_through(Medicion::class, MedicionEntrega::class, 'entrega_id', 'medicion_id')->findMany();
+ }
+ public function observaciones()
+ {
+ return $this->has_many_through(Observacion::class, EntregaObservacion::class, 'entrega_id', 'observacion_id')->findMany();
+ }
+ public function observacionesPendientes()
+ {
+ return $this->has_many_through(Observacion::class, EntregaObservacion::class, 'entrega_id', 'observacion_id')
+ ->select('observaciones.*')
+ ->rawJoin('JOIN (SELECT e1.* FROM (SELECT MAX(id) AS id, observacion_id FROM estado_observaciones GROUP BY observacion_id) e0 JOIN estado_observaciones e1 ON e1.id = e0.id)', ['ep.observacion_id', '=', 'observaciones.id'], 'ep')
+ ->leftOuterJoin('tipo_estado_observaciones', ['tipo_estado_observaciones.id', '=', 'ep.tipo_estado_observacion_id'])
+ ->where('tipo_estado_observaciones.descripcion', 'ingresada')
+ ->findMany();
+ }
+}
+?>
\ No newline at end of file
diff --git a/src/nuevo/Venta/EstadoCierre.php b/src/nuevo/Venta/EstadoCierre.php
new file mode 100644
index 0000000..d9be83e
--- /dev/null
+++ b/src/nuevo/Venta/EstadoCierre.php
@@ -0,0 +1,26 @@
+belongsTo(Cierre::class)->findOne();
+ }
+ public function estado()
+ {
+ return $this->belongsTo(TipoEstadoCierre::class)->findOne();
+ }
+}
+?>
\ No newline at end of file
diff --git a/src/nuevo/Venta/EstadoObservacion.php b/src/nuevo/Venta/EstadoObservacion.php
new file mode 100644
index 0000000..e4fc984
--- /dev/null
+++ b/src/nuevo/Venta/EstadoObservacion.php
@@ -0,0 +1,26 @@
+belongs_to(Observacion::class, 'observacion_id')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongs_to(TipoEstadoObservacion::class, 'tipo_estado_observacion_id')->findOne();
+ }
+}
+?>
\ No newline at end of file
diff --git a/src/nuevo/Venta/EstadoPago.php b/src/nuevo/Venta/EstadoPago.php
new file mode 100644
index 0000000..a163d9d
--- /dev/null
+++ b/src/nuevo/Venta/EstadoPago.php
@@ -0,0 +1,25 @@
+belongsTo(Pago::class, 'pago_id')->findOne();
+ }
+ public function estado()
+ {
+ return $this->belongsTo(TipoEstadoPago::class, 'estado_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Venta/EstadoPostventa.php b/src/nuevo/Venta/EstadoPostventa.php
new file mode 100644
index 0000000..ba8b6be
--- /dev/null
+++ b/src/nuevo/Venta/EstadoPostventa.php
@@ -0,0 +1,27 @@
+belongs_to(Postventa::class, 'postventa_id')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongs_to(TipoEstadoPostventa::class, 'tipo_estado_postventa_id')->findOne();
+ }
+}
+?>
\ No newline at end of file
diff --git a/src/nuevo/Venta/EstadoVenta.php b/src/nuevo/Venta/EstadoVenta.php
new file mode 100644
index 0000000..52ac3df
--- /dev/null
+++ b/src/nuevo/Venta/EstadoVenta.php
@@ -0,0 +1,25 @@
+belongsTo(Venta::class, 'venta_id')->findOne();
+ }
+ public function estado()
+ {
+ return $this->belongsTo(TipoEstadoVenta::class, 'estado_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Venta/FondoVenta.php b/src/nuevo/Venta/FondoVenta.php
new file mode 100644
index 0000000..7e5c689
--- /dev/null
+++ b/src/nuevo/Venta/FondoVenta.php
@@ -0,0 +1,31 @@
+belongs_to(Venta::class, 'venta_id')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongs_to(TipoFondo::class, 'tipo_id')->findOne();
+ }
+ public function pago()
+ {
+ return $this->belongs_to(Pago::class, 'pago_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Venta/FormaPago.php b/src/nuevo/Venta/FormaPago.php
new file mode 100644
index 0000000..43ffff0
--- /dev/null
+++ b/src/nuevo/Venta/FormaPago.php
@@ -0,0 +1,35 @@
+belongsTo(Pie::class, 'pie_id')->findOne();
+ }
+ public function escritura()
+ {
+ return $this->belongsTo(Pago::class, 'escritura_id')->findOne();
+ }
+ public function credito()
+ {
+ return $this->belongsTo(Pago::class, 'credito_id')->findOne();
+ }
+ public function subsidio()
+ {
+ return $this->belongs_to(Subsidio::class, 'subsidio_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Venta/Medicion.php b/src/nuevo/Venta/Medicion.php
new file mode 100644
index 0000000..4e8c25f
--- /dev/null
+++ b/src/nuevo/Venta/Medicion.php
@@ -0,0 +1,24 @@
+belongs_to(TipoMedicion::class, 'tipo_medicion_id')->findOne();
+ }
+}
+?>
\ No newline at end of file
diff --git a/src/nuevo/Venta/Observacion.php b/src/nuevo/Venta/Observacion.php
new file mode 100644
index 0000000..af3d10e
--- /dev/null
+++ b/src/nuevo/Venta/Observacion.php
@@ -0,0 +1,20 @@
+
\ No newline at end of file
diff --git a/src/nuevo/Venta/Pago.php b/src/nuevo/Venta/Pago.php
new file mode 100644
index 0000000..2aa1d18
--- /dev/null
+++ b/src/nuevo/Venta/Pago.php
@@ -0,0 +1,35 @@
+belongsTo(TipoPago::class, 'tipo_id')->findOne();
+ }
+ public function banco()
+ {
+ return $this->belongsTo(Banco::class, 'banco_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Venta/Pie.php b/src/nuevo/Venta/Pie.php
new file mode 100644
index 0000000..70a292a
--- /dev/null
+++ b/src/nuevo/Venta/Pie.php
@@ -0,0 +1,39 @@
+belongsTo(Pie::class, 'asociado_id');
+ if ($pie) {
+ return $pie->findOne();
+ }
+ return null;
+ }
+ public function Cuotas()
+ {
+ return $this->hasMany(Cuota::class, 'pie_id')->findMany();
+ }
+ public function CuotasPagadas()
+ {
+ return $this->hasMany(Cuota::class, 'pie_id')->filter(function($cuota) {
+ $estado = $cuota->pago->ultimoEstado()->estado->descripcion;
+ return ($estado == 'depositado' or $estado == 'abonado');
+ });
+ }
+}
diff --git a/src/nuevo/Venta/Postventa.php b/src/nuevo/Venta/Postventa.php
new file mode 100644
index 0000000..defd340
--- /dev/null
+++ b/src/nuevo/Venta/Postventa.php
@@ -0,0 +1,38 @@
+belongs_to(Venta::class, 'venta_id')->findOne();
+ }
+ public function observaciones()
+ {
+ return $this->has_many_through(Observacion::class, PostventaObservacion::class, 'postventa_id', 'observacion_id')->findMany();
+ }
+ public function observacionesPendientes()
+ {
+ return $this->has_many_through(Observacion::class, PostventaObservacion::class, 'postventa_id', 'observacion_id')
+ ->select('observaciones.*')
+ ->rawJoin('JOIN (SELECT e1.* FROM (SELECT MAX(id) AS id, observacion_id FROM estado_observaciones GROUP BY observacion_id) e0 JOIN estado_observaciones e1 ON e1.id = e0.id)', ['ep.observacion_id', '=', 'observaciones.id'], 'ep')
+ ->leftOuterJoin('tipo_estado_observaciones', ['tipo_estado_observaciones.id', '=', 'ep.tipo_estado_observacion_id'])
+ ->where('tipo_estado_observaciones.descripcion', 'ingresada')
+ ->findMany();
+ }
+}
+?>
\ No newline at end of file
diff --git a/src/nuevo/Venta/PostventaObservacion.php b/src/nuevo/Venta/PostventaObservacion.php
new file mode 100644
index 0000000..f16309a
--- /dev/null
+++ b/src/nuevo/Venta/PostventaObservacion.php
@@ -0,0 +1,27 @@
+belongs_to(Postventa::class, 'postventa_id')->findOne();
+ }
+ public function observacion()
+ {
+ return $this->belongs_to(Observacion::class, 'observacion_id')->findOne();
+ }
+}
+?>
\ No newline at end of file
diff --git a/src/nuevo/Venta/Premio.php b/src/nuevo/Venta/Premio.php
new file mode 100644
index 0000000..0ea45c0
--- /dev/null
+++ b/src/nuevo/Venta/Premio.php
@@ -0,0 +1,27 @@
+belongsTo(Venta::class, 'venta_id')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongsTo(TipoPremio::class, 'tipo_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Venta/Propiedad.php b/src/nuevo/Venta/Propiedad.php
new file mode 100644
index 0000000..edc7299
--- /dev/null
+++ b/src/nuevo/Venta/Propiedad.php
@@ -0,0 +1,30 @@
+belongsTo(Unidad::class, 'unidad_id')->findOne();
+ }
+ public function unidades()
+ {
+ return $this->hasMany(UnidadPropiedad::class, 'propiedad_id')->findMany();
+ }
+ public function venta()
+ {
+ return $this->hasMany(Venta::class, 'propiedad_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Venta/Propietario.php b/src/nuevo/Venta/Propietario.php
new file mode 100644
index 0000000..be00555
--- /dev/null
+++ b/src/nuevo/Venta/Propietario.php
@@ -0,0 +1,71 @@
+belongsTo(Direccion::class, 'direccion_id')->findOne();
+ }
+ public function representante()
+ {
+ $prop = $this->belongsTo(Propietario::class, 'representante_rut', 'rut');
+ if ($prop) {
+ return $prop->findOne();
+ }
+ return null;
+ }
+ public function otro()
+ {
+ $prop = $this->belongsTo(Propietario::class, 'otro_rut', 'rut');
+ if ($prop) {
+ return $prop->findOne();
+ }
+ return null;
+ }
+
+ public function nombreCompleto()
+ {
+ return implode(' ', [$this->nombres, $this->apellido_paterno, $this->apellido_materno]);
+ }
+
+ public function represntado()
+ {
+ $prop = $this->has_many(Propietario::class, 'representante_rut', 'rut');
+ if ($prop) {
+ return $prop->findOne();
+ }
+ return null;
+ }
+ public function ventas()
+ {
+ return $this->hasMany(Venta::class, 'propietario_rut', 'rut')->findMany();
+ }
+ public function articulo()
+ {
+ if ($this->sexo == 'f') {
+ return 'la';
+ }
+ return 'el';
+ }
+}
diff --git a/src/nuevo/Venta/ProyectoTipoMedicion.php b/src/nuevo/Venta/ProyectoTipoMedicion.php
new file mode 100644
index 0000000..6d479c7
--- /dev/null
+++ b/src/nuevo/Venta/ProyectoTipoMedicion.php
@@ -0,0 +1,28 @@
+belongs_to(Proyecto::class, 'proyecto_id')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongs_to(TipoMedicion::class, 'tipo_medicion_id')->findOne();
+ }
+}
+?>
\ No newline at end of file
diff --git a/src/nuevo/Venta/Reserva.php b/src/nuevo/Venta/Reserva.php
new file mode 100644
index 0000000..3f68449
--- /dev/null
+++ b/src/nuevo/Venta/Reserva.php
@@ -0,0 +1,30 @@
+belongsTo(Unidad::class, 'unidad_id')->findOne();
+ }
+ public function unidades()
+ {
+ return $this->hasMany(UnidadReserva::class, 'reserva_id')->findMany();
+ }
+}
+?>
\ No newline at end of file
diff --git a/src/nuevo/Venta/TipoEstadoCierre.php b/src/nuevo/Venta/TipoEstadoCierre.php
new file mode 100644
index 0000000..50498bc
--- /dev/null
+++ b/src/nuevo/Venta/TipoEstadoCierre.php
@@ -0,0 +1,10 @@
+
\ No newline at end of file
diff --git a/src/nuevo/Venta/TipoEstadoObservacion.php b/src/nuevo/Venta/TipoEstadoObservacion.php
new file mode 100644
index 0000000..ba0eb69
--- /dev/null
+++ b/src/nuevo/Venta/TipoEstadoObservacion.php
@@ -0,0 +1,10 @@
+
\ No newline at end of file
diff --git a/src/nuevo/Venta/TipoEstadoPago.php b/src/nuevo/Venta/TipoEstadoPago.php
new file mode 100644
index 0000000..0224436
--- /dev/null
+++ b/src/nuevo/Venta/TipoEstadoPago.php
@@ -0,0 +1,14 @@
+hasMany(EstadoPago::class, 'estado_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Venta/TipoEstadoPostventa.php b/src/nuevo/Venta/TipoEstadoPostventa.php
new file mode 100644
index 0000000..3a50841
--- /dev/null
+++ b/src/nuevo/Venta/TipoEstadoPostventa.php
@@ -0,0 +1,17 @@
+
\ No newline at end of file
diff --git a/src/nuevo/Venta/TipoEstadoVenta.php b/src/nuevo/Venta/TipoEstadoVenta.php
new file mode 100644
index 0000000..044dcbf
--- /dev/null
+++ b/src/nuevo/Venta/TipoEstadoVenta.php
@@ -0,0 +1,14 @@
+hasMany(EstadoVenta::class, 'estado_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Venta/TipoFondo.php b/src/nuevo/Venta/TipoFondo.php
new file mode 100644
index 0000000..0374e5f
--- /dev/null
+++ b/src/nuevo/Venta/TipoFondo.php
@@ -0,0 +1,14 @@
+hasMany(FontoVenta::class, 'tipo_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Venta/TipoMedicion.php b/src/nuevo/Venta/TipoMedicion.php
new file mode 100644
index 0000000..64d21cd
--- /dev/null
+++ b/src/nuevo/Venta/TipoMedicion.php
@@ -0,0 +1,10 @@
+
\ No newline at end of file
diff --git a/src/nuevo/Venta/TipoPago.php b/src/nuevo/Venta/TipoPago.php
new file mode 100644
index 0000000..0ce8a64
--- /dev/null
+++ b/src/nuevo/Venta/TipoPago.php
@@ -0,0 +1,14 @@
+hasMany(Pago::class, 'tipo_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Venta/TipoPremio.php b/src/nuevo/Venta/TipoPremio.php
new file mode 100644
index 0000000..381cc39
--- /dev/null
+++ b/src/nuevo/Venta/TipoPremio.php
@@ -0,0 +1,14 @@
+hasMany(Premio::class, 'tipo_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Venta/Unidad.php b/src/nuevo/Venta/Unidad.php
new file mode 100644
index 0000000..7e43358
--- /dev/null
+++ b/src/nuevo/Venta/Unidad.php
@@ -0,0 +1,47 @@
+belongsTo(UnidadProyecto::class, 'unidad_proyecto_id')->findOne();
+ }
+ public function uPropiedad()
+ {
+ $up = $this->hasMany(UnidadPropiedad::class, 'unidad_id');
+ if ($up) {
+ return $up->findOne();
+ }
+ return null;
+ }
+ public function propiedad()
+ {
+ $prop = $this->hasMany(Propiedad::class, 'unidad_id');
+ if ($prop) {
+ return $prop->findOne();
+ }
+ return null;
+ }
+ public function cuentas()
+ {
+ return $this->belongsTo(CuentaContable::class, 'cuenta_unidades', 'unidad_id', 'cuenta_id')->findMany();
+ }
+}
diff --git a/src/nuevo/Venta/UnidadPropiedad.php b/src/nuevo/Venta/UnidadPropiedad.php
new file mode 100644
index 0000000..d8a8465
--- /dev/null
+++ b/src/nuevo/Venta/UnidadPropiedad.php
@@ -0,0 +1,27 @@
+belongsTo(Propiedad::class, 'propiedad_id')->findOne();
+ }
+ public function unidad()
+ {
+ return $this->belongsTo(Unidad::class, 'unidad_id')->findOne();
+ }
+}
diff --git a/src/nuevo/Venta/UnidadReserva.php b/src/nuevo/Venta/UnidadReserva.php
new file mode 100644
index 0000000..f0355cb
--- /dev/null
+++ b/src/nuevo/Venta/UnidadReserva.php
@@ -0,0 +1,27 @@
+belongsTo(Reserva::class, 'reserva_id')->findOne();
+ }
+ public function unidad()
+ {
+ return $this->belongsTo(Unidad::class, 'unidad_id')->findOne();
+ }
+}
+?>
\ No newline at end of file
diff --git a/src/nuevo/Venta/Venta.php b/src/nuevo/Venta/Venta.php
new file mode 100644
index 0000000..d5bad0d
--- /dev/null
+++ b/src/nuevo/Venta/Venta.php
@@ -0,0 +1,104 @@
+belongs_to(Propietario::class, 'propietario_rut', 'rut')->findOne();
+ }
+ public function propiedad()
+ {
+ return $this->belongs_to(Propiedad::class, 'propiedad_id')->findOne();
+ }
+ public function formaPago()
+ {
+ return $this->belongs_to(FormaPago::class, 'forma_pago_id')->findOne();
+ }
+ public function agente()
+ {
+ $agente = $this->belongs_to(Agente::class, 'agente_id');
+ if ($agente) {
+ return $agente->findOne();
+ }
+ return null;
+ }
+
+ public function valor()
+ {
+ return $this->valor_promesa * $this->uf;
+ }
+ public function proyecto()
+ {
+ return $this->propiedad->unidadPrincipal->unidadProyecto->proyecto();
+ }
+ public function comision()
+ {
+ return $this->agente->comision($this->proyecto->inmobiliaria->rut);
+ }
+ public function ufM2()
+ {
+ if (!$this->agente) {
+ return 0;
+ }
+ return ($this->valor_promesa - $this->premios->sum('valor') - $this->comision() - $this->propiedad->unidades->sum('valor')) / $this->propiedad->unidadPrincipal->unidadProyecto->m2->vendibles();
+ }
+ public function fechaPromesa()
+ {
+ return Carbon::parse($this->fecha_promesa, config('app.timezone'));
+ }
+
+ public function premios()
+ {
+ $premios = $this->has_many(Premio::class, 'venta_id');
+ if ($premios) {
+ return $premios->findMany();
+ }
+ return [];
+ }
+ public function comentarios()
+ {
+ $comentarios = $this->has_many(Comentario::class, 'venta_id');
+ if ($comentarios) {
+ return $comentarios->findMany();
+ }
+ return [];
+ }
+ public function fondos()
+ {
+ return $this->has_many(FondoVenta::class, 'venta_id')->findMany();
+ }
+ public function postventas()
+ {
+ $postventas = $this->has_many(Postventa::class, 'venta_id');
+ if ($postventas) {
+ return $postventas->findMany();
+ }
+ return null;
+ }
+}
diff --git a/src/old/Common/Banco.php b/src/old/Common/Banco.php
new file mode 100644
index 0000000..d11cb22
--- /dev/null
+++ b/src/old/Common/Banco.php
@@ -0,0 +1,29 @@
+nombre) {
+ case 'Estado':
+ case 'Chile':
+ case 'Edwards':
+ $str .= 'Banco ';
+ }
+ $str .= $this->nombre;
+ return $str;
+ }
+}
+?>
diff --git a/src/old/Common/Comuna.php b/src/old/Common/Comuna.php
new file mode 100644
index 0000000..58266a6
--- /dev/null
+++ b/src/old/Common/Comuna.php
@@ -0,0 +1,22 @@
+belongs_to(Provincia::class, 'provincia')->findOne();
+ }
+}
+?>
diff --git a/src/old/Common/Direccion.php b/src/old/Common/Direccion.php
new file mode 100644
index 0000000..2ab38fc
--- /dev/null
+++ b/src/old/Common/Direccion.php
@@ -0,0 +1,36 @@
+belongs_to(Comuna::class, 'comuna')->findOne();
+ }
+
+ public function completa($comuna = false)
+ {
+ $str = $this->calle . ' ' . $this->numero;
+ if ($this->extra != '') {
+ $str .= ', ' . $this->extra;
+ }
+ if ($comuna) {
+ $str .= ', ' . $this->comuna()->descripcion;
+ }
+ return $str;
+ }
+}
+?>
diff --git a/src/old/Common/Provincia.php b/src/old/Common/Provincia.php
new file mode 100644
index 0000000..8571dca
--- /dev/null
+++ b/src/old/Common/Provincia.php
@@ -0,0 +1,26 @@
+belongsTo(Region::class, 'region')->findOne();
+ }
+ public function comunas()
+ {
+ return $this->hasMany(Comuna::class, 'provincia')->findMany();
+ }
+}
+?>
diff --git a/src/old/Common/Region.php b/src/old/Common/Region.php
new file mode 100644
index 0000000..b182609
--- /dev/null
+++ b/src/old/Common/Region.php
@@ -0,0 +1,44 @@
+provincias == null) {
+ $this->provincias = $this->hasMany(Provincia::class, 'region')->findMany();
+ }
+ return $this->provincias;
+ }
+ public function comunas()
+ {
+ if ($this->comunas == null) {
+ $provincias = $this->provincias();
+ $comunas = [];
+ foreach ($provincias as $prov) {
+ $comunas = array_merge($comunas, $prov->comunas());
+ }
+ usort($comunas, function($a, $b) {
+ return strcmp($a->descripcion, $b->descripcion);
+ });
+ $this->comunas = $comunas;
+ }
+ return $this->comunas;
+ }
+}
+?>
diff --git a/src/old/Inmobiliaria/Cuenta.php b/src/old/Inmobiliaria/Cuenta.php
new file mode 100644
index 0000000..dc14e8c
--- /dev/null
+++ b/src/old/Inmobiliaria/Cuenta.php
@@ -0,0 +1,23 @@
+belongsTo(Inmobiliaria::class, 'inmobiliaria', 'rut')->findOne();
+ }
+ public function banco()
+ {
+ return $this->belongsTo(Banco::class, 'banco')->findOne();
+ }
+}
diff --git a/src/old/Inmobiliaria/Inmobiliaria.php b/src/old/Inmobiliaria/Inmobiliaria.php
new file mode 100644
index 0000000..5f7f9d7
--- /dev/null
+++ b/src/old/Inmobiliaria/Inmobiliaria.php
@@ -0,0 +1,135 @@
+cuenta()->banco();
+ //return $this->belongsTo(Banco::class, 'banco')->findOne();
+ }
+ public function proyectos()
+ {
+ return $this->hasMany(Proyecto::class, 'inmobiliaria', 'rut')->orderByAsc('descripcion')->findMany();
+ }
+ public function nombre(bool $tipo = false)
+ {
+ return $this->abreviacion . (($tipo) ? ' ' . $this->sociedad()->abreviacion . '.' : '');
+ }
+ public function rut()
+ {
+ return format('rut', $this->rut) . '-' . $this->dv;
+ }
+ public function sociedad() {
+ return $this->belongsTo(TipoSociedad::class, 'sociedad')->findOne();
+ }
+ public function razon(bool $tipo = false, bool $abreviado = false) {
+ return $this->razon . (($tipo) ? ' ' . (($abreviado) ? $this->sociedad()->abreviacion . '.' : $this->sociedad()->descripcion) : '');
+ }
+ /**
+ * $data = ['descripcion', 'calle', 'numero', 'extra', 'comuna']
+ */
+ public function addProyecto(array $data)
+ {
+ //$proyecto = model(Proyecto::class)->where('inmobiliaria', $this->rut)->where('descripcion', $data['descripcion'])->findOne();
+ $data = [
+ 'inmobiliaria' => $this->rut,
+ 'descripcion' => $data['descripcion']
+ ];
+ $proyecto = (new Factory(Proyecto::class))->where($data)->find();
+ if (!$proyecto) {
+ //$proyecto = model(Proyecto::class)->create();
+ $proyecto = (new Factory(Proyecto::class))->create($data);
+ /*$proyecto->inmobiliaria = $this->rut;
+ $proyecto->descripcion = $data['descripcion'];*/
+ $proyecto->setDireccion($data);
+ $proyecto->save();
+ }
+ }
+ public function removeProyecto(array $data)
+ {
+ $proyecto = (new Factory(Proyecto::class))->where([
+ 'inmobiliaria' => $this->rut,
+ 'descripcion' => $data['descripcion']
+ ])->find();
+ if ($proyecto) {
+ $proyecto->delete();
+ }
+ }
+ public function cuenta()
+ {
+ if (count($this->cuentas()) == 0) {
+ return false;
+ }
+ return $this->cuentas()[0];
+ }
+ public function cuentas()
+ {
+ return $this->hasMany(Cuenta::class, 'inmobiliaria', 'rut')->findMany();
+ }
+ public function addCuenta(array $data)
+ {
+ if (!is_numeric($data['banco'])) {
+ $banco = (new Factory(Banco::class))->where(['descripcion' => $data['banco']])->find();
+ $data['banco'] = $banco->id;
+ }
+ $data = [
+ 'inmobiliaria' => $this->rut,
+ 'cuenta' => $data['cuenta'],
+ 'banco' => $data['banco']
+ ];
+ $cuenta = (new Factory(Cuenta::class))->where($data)->find();
+ if (!$cuenta) {
+ $cuenta = (new Factory(Cuenta::class))->create($data);
+ $cuenta->save();
+ }
+ }
+ public function removeCuenta(array $data)
+ {
+ $cuenta = (new Factory(Cuenta::class))->where(['inmobiliaria' => $this->rut]);
+ if (isset($data['cuenta'])) {
+ $cuenta = $cuenta->where(['cuenta' => $data['cuenta']]);
+ }
+ if (isset($data['banco'])) {
+ if (!is_numeric($data['banco'])) {
+ $banco = (new Factory(Banco::class))->where(['descripcion' => $data['banco']])->find();
+ $data['banco'] = $banco->id;
+ }
+ $cuenta = $cuenta->where(['banco' => $data['banco']]);
+ }
+ $cuenta = $cuenta->find();
+ if ($cuenta) {
+ $cuenta->delete();
+ }
+ }
+ public function modify(array $data)
+ {
+ $fields = ['rut', 'dv', 'razon', 'abreviacion'];
+ foreach ($data as $column => $value) {
+ if (array_search($column, $fields) !== false) {
+ $this->$column = $value;
+ }
+ }
+ $this->cuenta()->modify($data);
+ }
+}
+?>
diff --git a/src/old/Inmobiliaria/RelacionInmobiliarias.php b/src/old/Inmobiliaria/RelacionInmobiliarias.php
new file mode 100644
index 0000000..b86593d
--- /dev/null
+++ b/src/old/Inmobiliaria/RelacionInmobiliarias.php
@@ -0,0 +1,24 @@
+belongsTo(Inmobiliaria::class, 'padre', 'rut')->findOne();
+ }
+ public function hijo()
+ {
+ return $this->belongsTo(Inmobiliaria::class, 'hijo', 'rut')->findOne();
+ }
+}
+?>
diff --git a/src/old/Inmobiliaria/TipoSociedad.php b/src/old/Inmobiliaria/TipoSociedad.php
new file mode 100644
index 0000000..d2f0ce0
--- /dev/null
+++ b/src/old/Inmobiliaria/TipoSociedad.php
@@ -0,0 +1,12 @@
+belongs_to(Direccion::class, 'direccion')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongs_to(TipoAgente::class, 'tipo')->findOne();
+ }
+ public function tipos(int $tipo = 0)
+ {
+ if ($tipo == 0) {
+ return $this->hasMany(AgenteTipo::class, 'agente')->findMany();
+ }
+ return $this->hasMany(AgenteTipo::class, 'agente')->where('tipo', $tipo)->findOne();
+ }
+}
+?>
diff --git a/src/old/Proyecto/AgenteTipo.php b/src/old/Proyecto/AgenteTipo.php
new file mode 100644
index 0000000..91be4e3
--- /dev/null
+++ b/src/old/Proyecto/AgenteTipo.php
@@ -0,0 +1,20 @@
+belongsTo(Agente::class, 'agente')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongsTo(TipoAgente::class, 'tipo')->findOne();
+ }
+}
\ No newline at end of file
diff --git a/src/old/Proyecto/AvanceConstruccion.php b/src/old/Proyecto/AvanceConstruccion.php
new file mode 100644
index 0000000..93b30a4
--- /dev/null
+++ b/src/old/Proyecto/AvanceConstruccion.php
@@ -0,0 +1,86 @@
+belongsTo(Proyecto::class, 'proyecto')->findOne();
+ }
+ public function fecha(\DateTime $fecha = null)
+ {
+ if ($fecha == null) {
+ return Carbon::parse($this->fecha, config('app.timezone'));
+ }
+ $this->fecha = $fecha->format('Y-m-d');
+ }
+ protected $pagare;
+ public function pagare()
+ {
+ if ($this->pagare == null) {
+ $this->pagare = $this->hasMany(Pagare::class, 'estado_pago', 'numero')
+ ->where('proyecto', $this->proyecto)
+ ->findOne();
+ }
+ return $this->pagare;
+ }
+ protected $pagares;
+ public function pagares()
+ {
+ if ($this->pagares == null) {
+ $this->pagares = $this->hasMany(Pagare::class, 'estado_pago', 'numero')
+ ->where('proyecto', $this->proyecto)
+ ->findMany();
+ }
+ return $this->pagares;
+ }
+ public function uf()
+ {
+ if ($this->uf == 0) {
+ $uf = uf($this->fecha());
+ if ($uf->total > 0) {
+ $this->uf = $uf->uf->value;
+ $this->save();
+ }
+ }
+ return $this->uf;
+ }
+ public function pagado($tipo = 'ufs')
+ {
+ if ($tipo == 'ufs') {
+ return $this->pagado / $this->uf();
+ }
+ return $this->pagado;
+ }
+ public function fechaPago(\DateTime $fecha = null)
+ {
+ if ($fecha == null) {
+ return Carbon::parse($this->fecha_pagado, config('app.timezone'));
+ }
+ $this->fecha_pagado = $fecha->format('Y-m-d');
+ }
+ public function edit(array $data)
+ {
+ foreach ($data as $column => $value) {
+ if (isset($this->$column) and $this->$column != $value) {
+ $this->$column = $value;
+ }
+ }
+ $this->save();
+ }
+}
diff --git a/src/old/Proyecto/Cobro.php b/src/old/Proyecto/Cobro.php
new file mode 100644
index 0000000..47a1a0a
--- /dev/null
+++ b/src/old/Proyecto/Cobro.php
@@ -0,0 +1,35 @@
+has_one(Proyecto::class);
+ }
+ public function agente()
+ {
+ return $this->has_one(Agente::class);
+ }
+ public function tipo()
+ {
+ return $this->has_one(TipoCobro::class);
+ }
+}
+?>
diff --git a/src/old/Proyecto/Costo.php b/src/old/Proyecto/Costo.php
new file mode 100644
index 0000000..ef0de2e
--- /dev/null
+++ b/src/old/Proyecto/Costo.php
@@ -0,0 +1,21 @@
+has_one(Proyecto::class, 'proyecto')->findOne();
+ }
+}
+?>
diff --git a/src/old/Proyecto/EstadoCobro.php b/src/old/Proyecto/EstadoCobro.php
new file mode 100644
index 0000000..787edb7
--- /dev/null
+++ b/src/old/Proyecto/EstadoCobro.php
@@ -0,0 +1,25 @@
+has_one(Cobro::class, 'cobro')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->has_one(TipoEstadoCobro::class, 'estado')->findOne();
+ }
+}
+?>
diff --git a/src/old/Proyecto/EstadoProyecto.php b/src/old/Proyecto/EstadoProyecto.php
new file mode 100644
index 0000000..245fe0f
--- /dev/null
+++ b/src/old/Proyecto/EstadoProyecto.php
@@ -0,0 +1,30 @@
+belongs_to(Proyecto::class, 'proyecto')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongs_to(TipoEstadoProyecto::class, 'estado')->findOne();
+ }
+ public function fecha()
+ {
+ return Carbon::parse($this->fecha, config('app.timezone'));
+ }
+}
+?>
diff --git a/src/old/Proyecto/EstadoProyectoAgente.php b/src/old/Proyecto/EstadoProyectoAgente.php
new file mode 100644
index 0000000..0811ce8
--- /dev/null
+++ b/src/old/Proyecto/EstadoProyectoAgente.php
@@ -0,0 +1,29 @@
+belongsTo(ProyectoAgente::class, 'agente')->findOne();
+ }
+ public function fecha(\DateTime $fecha = null) {
+ if ($fecha == null) {
+ return Carbon::parse($this->fecha, config('app.timezone'));
+ }
+ $this->fecha = $fecha->format('Y-m-d');
+ }
+ public function tipo()
+ {
+ return $this->belongsTo(TipoEstadoProyectoAgente::class, 'tipo')->findOne();
+ }
+}
diff --git a/src/old/Proyecto/EtapaProyecto.php b/src/old/Proyecto/EtapaProyecto.php
new file mode 100644
index 0000000..e98c087
--- /dev/null
+++ b/src/old/Proyecto/EtapaProyecto.php
@@ -0,0 +1,18 @@
+
diff --git a/src/old/Proyecto/Pagare.php b/src/old/Proyecto/Pagare.php
new file mode 100644
index 0000000..ab5bd4d
--- /dev/null
+++ b/src/old/Proyecto/Pagare.php
@@ -0,0 +1,142 @@
+belongsTo(Proyecto::class, 'proyecto')->findOne();
+ }
+ public function moneda()
+ {
+ return $this->belongsTo(TipoMonedaPagare::class, 'moneda')->findOne();
+ }
+ public function renovaciones()
+ {
+ return $this->hasMany(RenovacionPagare::class, 'pagare')->findMany();
+ }
+ public function fecha(\DateTime $fecha = null)
+ {
+ if ($fecha == null) {
+ return Carbon::parse($this->fecha, config('app.timezone'));
+ }
+ $this->fecha = $fecha->format('Y-m-d');
+ }
+ public function fechaBanco(\DateTime $fecha = null)
+ {
+ if ($fecha == null) {
+ return Carbon::parse($this->fecha_banco, config('app.timezone'));
+ }
+ $this->fecha_banco = $fecha->format('Y-m-d');
+ }
+ public function vencimiento()
+ {
+ return $this->fechaBanco()->addDays($this->duracion);
+ }
+ public function uf()
+ {
+ if ($this->uf == 0 and $this->fecha != '0000-00-00') {
+ $uf = uf($this->fecha());
+ if ($uf->total > 0) {
+ $this->uf = $uf->uf->value;
+ $this->save();
+ }
+ }
+ return $this->uf;
+ }
+ protected $valores;
+ public function valor($tipo = 'ufs')
+ {
+ if ($this->valores == null) {
+ $valores = [];
+ switch (strtolower($this->moneda()->descripcion)) {
+ case 'uf':
+ $valores = (object) ['uf' => $this->capital, 'pesos' => $this->capital * $this->uf()];
+ break;
+ case 'pesos':
+ $valores = (object) ['uf' => $this->capital / $this->uf(), 'pesos' => $this->capital];
+ break;
+ }
+ $this->valores = $valores;
+ }
+ switch (strtolower($tipo)) {
+ case 'uf':
+ case 'ufs':
+ return $this->valores->uf;
+ case 'peso':
+ case 'pesos':
+ case '$':
+ return $this->valores->pesos;
+ }
+ }
+ public function abonado($tipo = 'ufs')
+ {
+ if ($tipo == 'ufs') {
+ if ($this->uf() > 0) {
+ return $this->abonado / $this->uf();
+ }
+ return 0;
+ }
+ return $this->abonado;
+ }
+ public function edit(array $data)
+ {
+ foreach ($data as $column => $value) {
+ if (isset($this->$column) and $this->$column != $value) {
+ $this->$column = $value;
+ }
+ }
+ $this->save();
+ }
+ protected $intereses;
+ public function intereses($tipo = 'ufs') {
+ if ($this->intereses == null) {
+ $this->intereses = (object) ['uf' => 0, 'pesos' => 0];
+ if ($this->renovaciones()) {
+ $arr = $this->renovaciones();
+ $this->intereses->uf = array_reduce($arr, function($accum, $item) {
+ return $accum + $item->intereses();
+ });
+ $this->intereses->pesos = array_reduce($arr, function($accum, $item) {
+ return $accum + $item->intereses('pesos');
+ });
+ }
+ }
+ switch (strtolower($tipo)) {
+ case 'uf':
+ case 'ufs':
+ return $this->intereses->uf;
+ case 'peso':
+ case 'pesos':
+ case '$':
+ return $this->intereses->pesos;
+ }
+ if ($fecha == null) {
+ $fecha = $this->vencimiento();
+ }
+ $dif = $fecha->diffInDays($this->fecha());
+ $duracion = ($dif > $this->duracion) ? $this->duracion : $dif;
+ return $this->valor() * ($this->tasa / 365 * $duracion) / 100;
+ }
+ public function estado_pago() {
+ if ($this->estado_pago == 0) {
+ return false;
+ }
+ return $this->belongsTo(AvanceConstruccion::class, 'estado_pago', 'numero')->findOne();
+ }
+}
diff --git a/src/old/Proyecto/Proyectista.php b/src/old/Proyecto/Proyectista.php
new file mode 100644
index 0000000..95c40fe
--- /dev/null
+++ b/src/old/Proyecto/Proyectista.php
@@ -0,0 +1,21 @@
+
diff --git a/src/old/Proyecto/Proyectistas.php b/src/old/Proyecto/Proyectistas.php
new file mode 100644
index 0000000..a004d21
--- /dev/null
+++ b/src/old/Proyecto/Proyectistas.php
@@ -0,0 +1,17 @@
+
diff --git a/src/old/Proyecto/Proyecto.php b/src/old/Proyecto/Proyecto.php
new file mode 100644
index 0000000..1a32e9f
--- /dev/null
+++ b/src/old/Proyecto/Proyecto.php
@@ -0,0 +1,859 @@
+belongs_to(Inmobiliaria::class, 'inmobiliaria', 'rut')->findOne();
+ }
+ public function direccion()
+ {
+ return $this->belongs_to(Direccion::class, 'direccion')->findOne();
+ }
+ public function unidades($tipo = null)
+ {
+ if ($tipo == null) {
+ if (!isset($this->unidades) or !isset($this->unidades->total)) {
+ $unidades = [];
+ if (isset($this->unidades)) {
+ $unidades = (array) $this->unidades;
+ }
+ $unidades['total'] = $this->has_many(Unidad::class, 'proyecto')->findMany();
+ $this->unidades = (object) $unidades;
+ }
+ return $this->unidades->total;
+ }
+ switch ($tipo) {
+ case 1:
+ case 'departamento':
+ case 'departamentos':
+ $tipo = 'departamento';
+ $id_tipo = 1;
+ break;
+ case 2:
+ case 'estacionamiento':
+ case 'estacionamientos':
+ $tipo = 'estacionamiento';
+ $id_tipo = 2;
+ break;
+ case 3:
+ case 'bodega':
+ case 'bodegas':
+ $tipo = 'bodega';
+ $id_tipo = 3;
+ break;
+ default:
+ return $this->unidades();
+ }
+ if (!isset($this->unidades) or !isset($this->unidades->{$tipo})) {
+ $unidades = [];
+ if (isset($this->unidades)) {
+ $unidades = (array) $this->unidades;
+ }
+ $unidades[$tipo] = $this->has_many(Unidad::class, 'proyecto')->where('tipo', $id_tipo)->findMany();
+ $this->unidades = (object) $unidades;
+ }
+ return $this->unidades->{$tipo};
+ }
+ public function unidadesDisponibles($tipo = null)
+ {
+ switch ($tipo) {
+ case 1:
+ case 'departamento':
+ case 'departamentos':
+ $tipo = 'departamento';
+ $id_tipo = 1;
+ break;
+ case 2:
+ case 'estacionamiento':
+ case 'estacionamientos':
+ $tipo = 'estacionamiento';
+ $id_tipo = 2;
+ break;
+ case 3:
+ case 'bodega':
+ case 'bodegas':
+ $tipo = 'bodega';
+ $id_tipo = 3;
+ break;
+ default:
+ $tipo = 'total';
+ $id_tipo = null;
+ }
+ if (!isset($this->unidades) or !isset($this->unidades->disponibles) or !isset($this->unidades->disponibles->{$tipo})) {
+ $unidades = ['disponibles' => []];
+ if (isset($this->unidades)) {
+ $unidades = (array) $this->unidades;
+ $unidades['disponibles'] = [];
+ if (isset($this->unidades->disponibles)) {
+ $unidades['disponibles'] = (array) $this->unidades->disponibles;
+ }
+ }
+ $q_s = "SELECT u.*
+ FROM
+ (SELECT * FROM unidad WHERE proyecto = ? ORDER BY tipo) AS u
+ LEFT JOIN
+ (SELECT unidad.*
+ FROM venta
+ JOIN propiedad ON propiedad.id = venta.propiedad
+ JOIN unidad ON unidad.id = propiedad.unidad_principal
+ WHERE venta.estado = 1) AS v ON v.id = u.id
+ LEFT JOIN
+ (SELECT unidad.*
+ FROM venta
+ JOIN propiedad ON propiedad.id = venta.propiedad
+ JOIN unidad ON propiedad.estacionamientos LIKE unidad.id
+ OR propiedad.estacionamientos LIKE CONCAT(unidad.id, ';%')
+ OR propiedad.estacionamientos LIKE CONCAT('%;', unidad.id)
+ OR propiedad.estacionamientos LIKE CONCAT('%;', unidad.id, ';%')
+ WHERE venta.estado = 1) AS e ON e.id = u.id
+ LEFT JOIN
+ (SELECT unidad.*
+ FROM venta
+ JOIN propiedad ON propiedad.id = venta.propiedad
+ JOIN unidad ON propiedad.bodegas LIKE unidad.id
+ OR propiedad.bodegas LIKE CONCAT(unidad.id, ';%')
+ OR propiedad.bodegas LIKE CONCAT('%;', unidad.id)
+ OR propiedad.bodegas LIKE CONCAT('%;', unidad.id, ';%')
+ WHERE venta.estado = 1) AS b ON b.id = u.id
+ WHERE v.id IS NULL AND e.id IS NULL AND b.id IS NULL";
+ $q_p = " ORDER BY u.tipo, LPAD(u.descripcion, 4, '0')";
+ switch (strtolower($id_tipo)) {
+ case null:
+ default:
+ $q = $q_s . $q_p;
+ break;
+ case 1:
+ case 'departamento':
+ case 'departamentos':
+ $q = $q_s . ' AND u.tipo = 1' . $q_p;
+ break;
+ case 2:
+ case 'estacionamiento':
+ case 'estacionamientos':
+ $q = $q_s . ' AND u.tipo = 2' . $q_p;
+ break;
+ case 3:
+ case 'bodega':
+ case 'bodegas':
+ $q = $q_s . ' AND u.tipo = 3' . $q_p;
+ break;
+ }
+ $disponibles = model(Unidad::class)->rawQuery($q, [$this->id])->findMany();
+ $unidades['disponibles'][$tipo] = $disponibles;
+ $unidades['disponibles'] = (object) $unidades['disponibles'];
+ $this->unidades = (object) $unidades;
+ }
+ return $this->unidades->disponibles->{$tipo};
+ }
+ public function proyectoTipoUnidades()
+ {
+ return $this->hasMany(ProyectoTipoUnidad::class, 'proyecto')->orderByAsc('tipo')->findMany();
+ }
+ public function tipoUnidades()
+ {
+ if (!isset($this->tipos_unidades)) {
+ $tipos = \Model::factory(TipoUnidad::class)
+ ->select('tipo_unidad.*')
+ ->join('unidad', ['unidad.tipo', '=', 'tipo_unidad.id'])
+ ->join('proyecto', ['proyecto.id', '=', 'unidad.proyecto'])
+ ->where('proyecto.id', $this->id)
+ ->order_by_asc('tipo_unidad.id')
+ ->group_by('tipo_unidad.id')
+ ->findMany();
+ $this->tipos_unidades = $tipos;
+ }
+ return $this->tipos_unidades;
+ }
+ public function ventas($order = 'departamento')
+ {
+ if (!isset($this->ventas)) {
+ $ventas = model(Venta::class)
+ ->select('venta.*')
+ ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad'])
+ ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal'])
+ ->rawJoin('JOIN (SELECT `e1`.* FROM (SELECT `venta`, MAX(`id`) AS `id` FROM `estado_venta` GROUP BY `venta`) AS `e0` JOIN `estado_venta` AS `e1` ON `e1`.`id` = `e0`.`id`)', ['estado_venta.venta', '=', 'venta.id'], 'estado_venta')
+ ->join('tipo_estado_venta', ['tipo_estado_venta.id', '=', 'estado_venta.estado'])
+ ->where('unidad.proyecto', $this->id)
+ ->where('unidad.tipo', 1)
+ ->where('tipo_estado_venta.activa', 1);
+ switch (strtolower($order)) {
+ case 'fecha':
+ $ventas = $ventas->orderByAsc('venta.fecha');
+ case 'departamento':
+ default:
+ $ventas = $ventas->orderByExpr('LPAD(`unidad`.`descripcion`, 4, "0")');
+ break;
+ }
+ $ventas = $ventas->find_many();
+ $this->ventas = $ventas;
+ }
+ return $this->ventas;
+ }
+ protected $resciliaciones;
+ public function resciliaciones()
+ {
+ if ($this->resciliaciones == null) {
+ $resciliaciones = model(Venta::class)
+ ->select('venta.*')
+ ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad'])
+ ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal'])
+ ->rawJoin('JOIN (SELECT `e1`.* FROM (SELECT `venta`, MAX(`id`) AS `id` FROM `estado_venta` GROUP BY `venta`) AS `e0` JOIN `estado_venta` AS `e1` ON `e1`.`id` = `e0`.`id`)', ['estado_venta.venta', '=', 'venta.id'], 'estado_venta')
+ ->join('tipo_estado_venta', ['tipo_estado_venta.id', '=', 'estado_venta.estado'])
+ ->where('unidad.proyecto', $this->id)
+ ->where('unidad.tipo', 1)
+ ->where('tipo_estado_venta.activa', 0)
+ ->orderByExpr('LPAD(`unidad`.`descripcion`, 4, "0")')
+ ->find_many()
+ ;
+ $this->resciliaciones = $resciliaciones;
+ }
+ return $this->resciliaciones;
+ }
+ public function escrituras()
+ {
+ if (!isset($escrituras)) {
+ $ventas = model(Venta::class)
+ ->select('venta.*')
+ ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad'])
+ ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal'])
+ ->where('unidad.proyecto', $this->id)
+ ->where('venta.estado', 1)
+ ->where('unidad.tipo', 1)
+ ->whereNotEqual('venta.escriturado', '0')
+ ->orderByExpr('LPAD(unidad.descripcion, 4, "0")')
+ ->find_many()
+ ;
+ $this->escrituras = $ventas;
+ }
+ return $this->escrituras;
+ }
+ public function entregas()
+ {
+ if (!isset($this->entregas)) {
+ $entregas = [];
+ $escrituras = $this->escrituras();
+ foreach ($escrituras as $escritura) {
+ if ($escritura->entrega == '0') {
+ continue;
+ }
+ $entregas []= $escritura;
+ }
+ usort($entregas, function($a, $b) {
+ $fa = \Carbon\Carbon::parse($a->entrega()->find_one()->fecha);
+ $fb = \Carbon\Carbon::parse($b->entrega()->find_one()->fecha);
+ $dif = $fb->diffInDays($fa, false);
+ if ($dif == 0) {
+ return $a->unidad()->descripcion - $b->unidad()->descripcion;
+ }
+ return $dif;
+ });
+ $this->entregas = $entregas;
+ }
+ return $this->entregas;
+ }
+ public function estados()
+ {
+ return $this->has_many(EstadoProyecto::class, 'proyecto')->orderByAsc('fecha')->findMany();
+ }
+ public function estado()
+ {
+ if (!isset($this->estado)) {
+ $id = $this->has_many(EstadoProyecto::class, 'proyecto')->max('id');
+ $this->estado = $this->has_many(EstadoProyecto::class, 'proyecto')->findOne($id);
+ }
+ return $this->estado;
+ }
+ public function avances()
+ {
+ return $this->hasMany(AvanceConstruccion::class, 'proyecto')->orderByAsc('fecha')->findMany();
+ }
+ protected $avance;
+ public function avance()
+ {
+ if ($this->avance == null and $this->avances()) {
+ $avance = array_reduce($this->avances(), function($carry, $item) {
+ return ($carry += $item->avance);
+ });
+ $this->avance = $avance;
+ }
+ return $this->avance;
+ }
+ protected $inicio;
+ public function inicio()
+ {
+ if (!isset($this->inicio) or $this->inicio == null) {
+ $id = $this->has_many(EstadoProyecto::class, 'proyecto')->min('id');
+ $this->inicio = $this->has_many(EstadoProyecto::class, 'proyecto')->findOne($id);
+ }
+ return $this->inicio;
+ }
+ public function valores()
+ {
+ if (!isset($this->valores)) {
+ $ventas = $this->ventas();
+
+ /**
+ * vendidos
+ * departamentos
+ * cantidad
+ * ingreso
+ * neto
+ * bruto // suma estacionamientos, bodegas, comision y premios
+ * pagado
+ * abonado
+ * precio
+ * minimo
+ * promedio
+ * maximo
+ * mts
+ * minimo
+ * promedio // total dividido cantidad
+ * maximo
+ * total
+ * uf_m2
+ * minimo // minimo de precio dividido mts
+ * promedio // ingreso neto dividido mts total
+ * maximo // maximo de precio dividido mts
+ * estacionamientos // valor estacionamientos
+ * bodegas // valor bodegas
+ * comision // valor comisiones
+ * premios // valor total cada premio
+ * estimados // idem vendidos, pero valores estimados proporcional a mts
+ * totales // vendidos + estimados
+ */
+
+ $premios = model(Promocion::class)->findMany();
+ $valores = (object) [
+ 'vendidos' => new BaseValores(),
+ 'estimados' => new BaseValores(),
+ 'totales' => new BaseValores()
+ ];
+ foreach ($valores as &$name) {
+ $name->basePremios($premios);
+ }
+ if ($ventas) {
+ $valores->vendidos->ingreso->neto = 0;
+ $valores->vendidos->ingreso->neto = array_reduce($ventas, function($sum, $item) {
+ return $sum + $item->valorFinal();
+ });
+ foreach ($ventas as $venta) {
+ //$valores->vendidos->ingreso->neto += $venta->valorFinal();
+ $valores->vendidos->ingreso->bruto += $venta->valor_uf;
+ $valores->vendidos->ingreso->pagado += $venta->valorPagado();
+ $valores->vendidos->ingreso->abonado += $venta->valorAbonado();
+
+ $valores->vendidos->departamentos->cantidad ++;
+ if ($venta->unidad()->precio($venta->fecha())) {
+ $valores->vendidos->departamentos->addPrecio($venta->unidad()->precio($venta->fecha())->valor);
+ }
+ $valores->vendidos->departamentos->addMts('totales', $venta->unidad()->m2('total'));
+ $valores->vendidos->departamentos->addMts('vendibles', $venta->unidad()->m2());
+
+ //$valores->vendidos->otros->cantidad += ($venta->estacionamientos() or $venta->bodegas()) :
+ $valores->vendidos->otros->valor += $venta->valorEstacionamientosYBodegas();
+ if ($venta->bono_pie) {
+ $valores->vendidos->bono->cantidad ++;
+ $valores->vendidos->bono->valor += $venta->bonoPie()->pago()->valor('ufs');
+ }
+ $valores->vendidos->comision += $venta->valorComision();
+ $ps = $venta->promociones();
+ if (count($ps) > 0) {
+ foreach ($ps as $promo) {
+ if ($promo->descripcion != '') {
+ $valores->vendidos->premios->{$promo->descripcion} += $promo->valor;
+ }
+ }
+ }
+ }
+ $valores->vendidos->departamentos->setPromedios();
+ }
+
+ $valores->estimados->departamentos->cantidad = count($this->unidades(1)) - count($this->ventas());
+ $valores->estimados->departamentos->mts->vendibles->total = 0;
+ $valores->estimados->departamentos->mts->vendibles->promedio = 0;
+ $valores->estimados->departamentos->precio->promedio = 0;
+ $valores->estimados->departamentos->uf_m2->promedio = 0;
+ if ($valores->estimados->departamentos->cantidad > 0) {
+ $valores->estimados->departamentos->mts->vendibles->total = array_reduce($this->unidadesDisponibles(1), function($sum, $item) {
+ return $sum + $item->m2();
+ });
+ $valores->estimados->departamentos->mts->vendibles->promedio = $valores->estimados->departamentos->mts->vendibles->total / $valores->estimados->departamentos->cantidad;
+ $valores->estimados->ingreso->neto = array_reduce($this->unidadesDisponibles(1), function($sum, $item) {
+ if (!$item->precio()) {
+ return $sum;
+ }
+ return $sum + $item->precio()->valor;
+ });
+ if ($valores->estimados->ingreso->neto == null) {
+ $valores->estimados->ingreso->neto = 0;
+ }
+ $valores->estimados->departamentos->precio->promedio = $valores->estimados->ingreso->neto / $valores->estimados->departamentos->cantidad;
+ $valores->estimados->departamentos->uf_m2->promedio = $valores->estimados->ingreso->neto / $valores->estimados->departamentos->mts->vendibles->total;
+ }
+
+ $valores->estimados->otros->cantidad = count($this->unidadesDisponibles(2)) + count($this->unidadesDisponibles(3));
+ $valores->estimados->otros->valor = count($this->unidadesDisponibles(2)) * 330 + count($this->unidadesDisponibles(3)) * 50;
+ foreach ($premios as $premio) {
+ $valores->estimados->premios->{$premio->descripcion} = 0;
+ if ($valores->vendidos->ingreso->neto > 0) {
+ $valores->estimados->premios->{$premio->descripcion} = $valores->vendidos->premios() * $valores->estimados->ingreso->neto / $valores->vendidos->ingreso->neto;
+ }
+ }
+ $valores->estimados->bono->valor = 0;
+ $valores->estimados->comision = 0;
+ if ($valores->vendidos->ingreso->neto > 0) {
+ $valores->estimados->bono->valor = $valores->vendidos->bono->valor * $valores->estimados->ingreso->neto / $valores->vendidos->ingreso->neto;
+ $valores->estimados->comision = $valores->vendidos->comision * $valores->estimados->ingreso->neto / $valores->vendidos->ingreso->neto;
+ }
+ $valores->estimados->ingreso->bruto = $valores->estimados->ingreso->neto
+ + $valores->estimados->otros->valor
+ + $valores->estimados->bono->valor
+ + $valores->estimados->premios()
+ + $valores->estimados->comision;
+
+ $this->valores = $valores;
+ }
+
+ return $this->valores;
+ }
+ public function agentes()
+ {
+ if (!isset($this->agentes)) {
+ $this->agentes = \Model::factory(Agente::class)
+ ->select('agente.*')
+ ->join('proyecto_agente', ['proyecto_agente.agente', '=', 'agente.id'])
+ ->where('proyecto_agente.proyecto', $this->id)
+ ->orderByAsc('agente.abreviacion')
+ ->findMany();
+ }
+ return $this->agentes;
+ }
+ public function operadores()
+ {
+ if (!isset($this->operadores)) {
+ $this->operadores = \Model::factory(Agente::class)
+ ->select('agente.*')
+ ->select('agente_tipo.id', 'agente_tipo')
+ ->join('agente_tipo', ['agente_tipo.agente', '=', 'agente.id'])
+ ->join('proyecto_agente', ['proyecto_agente.agente', '=', 'agente_tipo.id'])
+ ->where('agente_tipo.tipo', 19)
+ ->where('proyecto_agente.proyecto', $this->id)
+ ->orderByAsc('agente.abreviacion')
+ ->groupBy('agente_tipo.id')
+ ->findMany();
+ }
+ return $this->operadores;
+ }
+ public function operadoresVigentes()
+ {
+ return $this->hasMany(ProyectoAgente::class, 'proyecto')
+ ->select('proyecto_agente.*')
+ ->join('agente_tipo', ['agente_tipo.id', '=', 'proyecto_agente.agente'])
+ ->rawJoin('JOIN (SELECT e1.* FROM estado_proyecto_agente e1 JOIN (SELECT agente, MAX(id) AS id FROM estado_proyecto_agente GROUP BY agente) e0 ON e0.id = e1.id)', ['ep.agente', '=', 'proyecto_agente.id'], 'ep')
+ ->where('agente_tipo.tipo', 19)
+ ->where('ep.tipo', 1)
+ ->findMany();
+ }
+ public function promociones()
+ {
+ if (!isset($this->promociones)) {
+ $this->promociones = \Model::factory(Promocion::class)
+ ->select('promocion.*')
+ ->join('promocion_venta', ['promocion_venta.promocion', '=', 'promocion.id'])
+ ->join('venta', ['venta.id', '=', 'promocion_venta.venta'])
+ ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad'])
+ ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal'])
+ ->where('unidad.proyecto', $this->id)
+ ->groupBy('promocion.id')
+ ->orderByAsc('promocion.titulo')
+ ->findMany();
+ }
+ return $this->promociones;
+ }
+ public function pisos()
+ {
+ if ($this->pisos == 0) {
+ $pisos = $this->has_many(Unidad::class, 'proyecto')->where('tipo', 1)->max('piso');
+ if (!$pisos) {
+ return 0;
+ }
+ $this->pisos = $pisos;
+ $this->save();
+ }
+ return $this->pisos;
+ }
+ public function cuotasHoy()
+ {
+ if (!isset($this->cuotas) or !isset($this->cuotas->hoy)) {
+ $cuotas = [];
+ if (isset($this->cuotas)) {
+ $cuotas = (array) $this->cuotas;
+ }
+ $f = Carbon::today(config('app.timezone'));
+ $cuotas['hoy'] = model(Venta::class)
+ ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad'])
+ ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal'])
+ ->join('cuota', ['cuota.pie', '=', 'venta.pie'])
+ ->join('pago', ['pago.id', '=', 'cuota.pago'])
+ ->raw_join('JOIN (SELECT e1.* FROM (SELECT pago, MAX(id) AS id FROM estado_pago GROUP BY pago) e0 JOIN estado_pago e1 ON e1.id = e0.id)', ['ep.pago', '=', 'pago.id'], 'ep')
+ ->where('unidad.proyecto', $this->id)
+ ->where('venta.estado', 1)
+ ->where('pago.fecha', $f->format('Y-m-d'))
+ ->whereLt('ep.estado', 1)
+ ->whereGte('ep.estado', 0)
+ ->count('cuota.id');
+ $this->cuotas = (object) $cuotas;
+ }
+ return $this->cuotas->hoy;
+ }
+ public function cuotasPendientes()
+ {
+ if (!isset($this->cuotas) or !isset($this->cuotas->pendientes)) {
+ $cuotas = [];
+ if (isset($this->cuotas)) {
+ $cuotas = (array) $this->cuotas;
+ }
+ $f = Carbon::today(config('app.timezone'));
+ $cuotas['pendientes'] = model(Cuota::class)
+ ->join('venta', ['cuota.pie', '=', 'venta.pie'])
+ ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad'])
+ ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal'])
+ ->join('pago', ['pago.id', '=', 'cuota.pago'])
+ ->raw_join('JOIN (SELECT e1.* FROM (SELECT pago, MAX(id) AS id FROM estado_pago GROUP BY pago) e0 JOIN estado_pago e1 ON e1.id = e0.id)', ['ep.pago', '=', 'pago.id'], 'ep')
+ ->where('unidad.proyecto', $this->id)
+ ->where('venta.estado', 1)
+ ->whereLt('pago.fecha', $f->format('Y-m-d'))
+ ->whereLt('ep.estado', 1)
+ ->whereGte('ep.estado', 0)
+ ->count('cuota.id');
+ $this->cuotas = (object) $cuotas;
+ }
+ return $this->cuotas->pendientes;
+ }
+ public function cuotasMes()
+ {
+ if (!isset($this->cuotas) or !isset($this->cuotas->mes)) {
+ $cuotas = [];
+ if (isset($this->cuotas)) {
+ $cuotas = (array) $this->cuotas;
+ }
+ $f = Carbon::today(config('app.timezone'));
+ $cuotas['mes'] = model(Cuota::class)
+ ->join('venta', ['cuota.pie', '=', 'venta.pie'])
+ ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad'])
+ ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal'])
+ ->join('pago', ['pago.id', '=', 'cuota.pago'])
+ ->raw_join('JOIN (SELECT e1.* FROM (SELECT pago, MAX(id) AS id FROM estado_pago GROUP BY pago) e0 JOIN estado_pago e1 ON e1.id = e0.id)', ['ep.pago', '=', 'pago.id'], 'ep')
+ ->where('unidad.proyecto', $this->id)
+ ->where('venta.estado', 1)
+ ->whereGt('pago.fecha', $f->format('Y-m-d'))
+ ->whereLte('pago.fecha', $f->copy()->addMonth(1)->format('Y-m-d'))
+ ->where('ep.estado', 0)
+ ->findMany();
+ $this->cuotas = (object) $cuotas;
+ }
+ return $this->cuotas->mes;
+ }
+ public function tiposMediciones()
+ {
+ $tipos = $this->has_many_through(\Incoviba\nuevo\Venta\TipoMedicion::class, \Incoviba\nuevo\Venta\ProyectoTipoMedicion::class, 'proyecto_id', 'tipo_medicion_id');
+ if ($tipos) {
+ return $tipos->orderByAsc('descripcion')->findMany();
+ }
+ return null;
+ }
+ public function superficie($tipo = 'total')
+ {
+ if (!isset($this->superficies) or !isset($this->superficies->{$tipo})) {
+ $superficies = [];
+ if (isset($this->superficies)) {
+ $superficies = (array) $this->superficies;
+ }
+ switch (strtolower($tipo)) {
+ case 'total':
+ $superficies['total'] = $this->superficie('snt') + $this->superficie('bnt');
+ break;
+ case 'terreno':
+ $superficies['terreno'] = $this->superficie_terreno;
+ break;
+ case 'sobre_nivel':
+ case 'snt':
+ $superficies['snt'] = $superficies['sobre_nivel'] = $this->superficie_sobre_nivel;
+ break;
+ case 'bajo_nivel':
+ case 'bnt':
+ $superficies['bnt'] = $superficies['bajo_nivel'] = $this->superficie_bajo_nivel;
+ break;
+ case 'vendible':
+ $superficies['vendible'] = 0;
+ if ($this->unidades()) {
+ $metros = $this->hasMany(Unidad::class, 'proyecto')->selectExpr('SUM(m2 + logia + terraza /2)', 'metros')->where('tipo', 1)->groupBy('proyecto')->findOne();
+ $superficies['vendible'] = $metros->metros;
+ }
+ break;
+ case 'vendida':
+ $superficies['vendida'] = 0;
+ if ($this->ventas()) {
+ $metros = model(Venta::class)
+ ->selectExpr('SUM(unidad.m2 + unidad.logia + unidad.terraza / 2)', 'metros')
+ ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad'])
+ ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal'])
+ ->where('unidad.proyecto', $this->id)
+ ->where('venta.estado', 1)
+ ->where('unidad.tipo', 1)
+ ->groupBy('unidad.proyecto')
+ ->findOne();
+ if ($metros) {
+ $superficies['vendida'] = $metros->metros;
+ }
+ }
+ break;
+ case 'por vender':
+ $superficies['por vender'] = $this->superficie('vendible') - $this->superficie('vendida');
+ break;
+ default:
+ return 0;
+ }
+ $this->superficies = (object) $superficies;
+ }
+ return $this->superficies->{$tipo};
+ }
+ public function setDireccion(array $data)
+ {
+ if (!is_numeric($data['comuna'])) {
+ $comuna = model(Comuna::class)->where('descripcion', $data['comuna'])->findOne();
+ $data['comuna'] = $comuna->id;
+ }
+ $direccion = model(Direccion::class)
+ ->where('calle', $data['calle'])
+ ->where('numero', $data['numero'])
+ ->where('extra', $data['extra'])
+ ->where('comuna', $data['comuna'])
+ ->findOne();
+ $this->direccion = $direccion->id;
+ }
+ public function addAgente(array $data)
+ {
+ $data = ['agente' => $data['agente'], 'tipo' => $data['tipo']];
+ $agente = (new Factory(AgenteTipo::class))->create($data);
+ $agente->save();
+ $this->agentes []= $agente;
+ }
+ protected $tipologias;
+ public function tipologias()
+ {
+ if ($this->tipologias == null) {
+ $pts = $this->proyectoTipoUnidades();
+ $tipologias = [];
+ foreach ($pts as $pt) {
+ if ($pt->tipologia()) {
+ if (!isset($tipologias[$pt->tipologia()->tipologia->descripcion])) {
+ $tipologias[$pt->tipologia()->tipologia->descripcion] = (object) ['tipologia' => $pt->tipologia()->tipologia, 'tipos' => []];
+ }
+ $tipologias[$pt->tipologia()->tipologia->descripcion]->tipos []= $pt;
+ continue;
+ }
+ }
+ $this->tipologias = $tipologias;
+ }
+ return $this->tipologias;
+ }
+ public function pagares()
+ {
+ return $this->hasMany(Pagare::class, 'proyecto')->findMany();
+ }
+ protected $cierres;
+ public function cierres(int $vigentes = 0)
+ {
+ if (!isset($this->cierres[$vigentes]) or $this->cierres[$vigentes] == null) {
+ $orm = model(Cierre::class)
+ ->select('cierre.*')
+ ->rawJoin('join (select e1.* from estado_cierre e1 join (select cierre, max(id) as id from estado_cierre group by cierre) e0 on e0.id = e1.id)', ['ec.cierre', '=', 'cierre.id'], 'ec')
+ ->join('tipo_estado_cierre', ['tipo_estado_cierre.id', '=', 'ec.tipo'])
+ ->join('proyecto', ['proyecto.id', '=', 'cierre.proyecto'])
+ ->join('unidad_cierre', ['unidad_cierre.cierre', '=', 'cierre.id'])
+ ->join('unidad', ['unidad.id', '=', 'unidad_cierre.unidad'])
+ ->where('proyecto.id', $this->id)
+ ->where('unidad_cierre.principal', 1)
+ ->orderByAsc('proyecto.descripcion')
+ ->orderByDesc('tipo_estado_cierre.vigente')
+ ->orderByAsc('cierre.fecha')
+ ->orderByExpr('LPAD(unidad.descripcion, 4, "0")')
+ ->groupBy('cierre.id');
+ switch ($vigentes) {
+ case Cierre::VIGENTES:
+ $orm = $orm->where('tipo_estado_cierre.vigente', 1);
+ break;
+ case Cierre::NO_VIGENTES:
+ $orm = $orm->where('tipo_estado_cierre.vigente', 0);
+ break;
+ case Cierre::VIGENTES + 1:
+ $orm = $orm
+ ->where('tipo_estado_cierre.vigente', 1)
+ ->whereNotLike('tipo_estado_cierre.descripcion', 'promesado')
+ ;
+ break;
+ case Cierre::VIGENTES + 2:
+ $orm = $orm
+ ->where('tipo_estado_cierre.vigente', 1)
+ ->whereLike('tipo_estado_cierre.descripcion', 'promesado')
+ ;
+ break;
+ }
+ $this->cierres[$vigentes] = $orm->findMany();
+ }
+ return $this->cierres[$vigentes];
+ }
+ public function tipos() {
+ return $this->hasMany(ProyectoTipoUnidad::class, 'proyecto')->findMany();
+ }
+}
+
+class Departamentos {
+ public $cantidad;
+ public $precio;
+ public $mts;
+ public $uf_m2;
+ public function __construct() {
+ $this->cantidad = 0;
+ $base = [
+ 'minimo' => 1000000,
+ 'promedio' => 0,
+ 'maximo' => -1
+ ];
+ $this->precio = (object) $base;
+ $this->mts = (object) [
+ 'totales' => (object) array_merge($base, ['total' => 0]),
+ 'vendibles' => (object) array_merge($base, ['total' => 0])
+ ];
+ $this->uf_m2 = (object) $base;
+ }
+ protected function setMin(&$var, $val) {
+ if ($var > $val) {
+ $var = $val;
+ }
+ }
+ protected function setMax(&$var, $val) {
+ if ($var < $val) {
+ $var = $val;
+ }
+ }
+ public function addPrecio($val) {
+ $this->precio->promedio += $val;
+ $this->setMin($this->precio->minimo, $val);
+ $this->setMax($this->precio->maximo, $val);
+ $this->uf_m2->promedio += $val;
+
+ return $this;
+ }
+ public function addMts($name, $val) {
+ $this->mts->$name->total += $val;
+ $this->mts->$name->promedio += $val;
+ $this->setMin($this->mts->{$name}->minimo, $val);
+ $this->setMax($this->mts->{$name}->maximo, $val);
+
+ return $this;
+ }
+ public function addUfM2($val) {
+ $this->setMin($this->uf_m2->minimo, $val);
+ $this->setMax($this->uf_m2->maximo, $val);
+
+ return $this;
+ }
+ public function setPromedios() {
+ $this->precio->promedio /= $this->cantidad;
+ $this->mts->totales->promedio /= $this->cantidad;
+ $this->mts->vendibles->promedio /= $this->cantidad;
+ $this->uf_m2->promedio /= $this->mts->vendibles->total;
+
+ return $this;
+ }
+};
+class BaseValores {
+ public $ingreso;
+ public $departamentos;
+ public $otros;
+ public $bono;
+ public $comision;
+ public $premios;
+
+ public function __construct() {
+ $this->ingreso = (object) [
+ 'neto' => 0,
+ 'bruto' => 0,
+ 'pagado' => 0,
+ 'abonado' => 0
+ ];
+ $this->departamentos = new Departamentos();
+ $this->otros = (object) [
+ 'cantidad' => 0,
+ 'valor' => 0
+ ];
+ $this->bono = (object) [
+ 'cantidad' => 0,
+ 'valor' => 0
+ ];
+ $this->comision = 0;
+ $this->premios = [];
+ }
+ public function basePremios(array $premios) {
+ foreach ($premios as $premio) {
+ $this->premios[$premio->descripcion] = 0;
+ }
+ $this->premios = (object) $this->premios;
+
+ return $this;
+ }
+ protected $total_premios;
+ public function premios() {
+ if ($this->total_premios == null) {
+ $this->total_premios = array_reduce((array) $this->premios, function($sum, $item) {
+ return $sum + $item;
+ });
+ }
+ return $this->total_premios;
+ }
+};
diff --git a/src/old/Proyecto/ProyectoAgente.php b/src/old/Proyecto/ProyectoAgente.php
new file mode 100644
index 0000000..dba7430
--- /dev/null
+++ b/src/old/Proyecto/ProyectoAgente.php
@@ -0,0 +1,54 @@
+belongsTo(Proyecto::class, 'proyecto')->findOne();
+ }
+ public function agente()
+ {
+ return $this->belongsTo(AgenteTipo::class, 'agente')->findOne();
+ }
+ public function estado()
+ {
+ return $this->hasMany(EstadoProyectoAgente::class, 'agente')
+ ->orderByDesc('id')->findOne();
+ }
+ public function estados()
+ {
+ return $this->hasMany(EstadoProyectoAgente::class, 'agente')->findMany();
+ }
+ public function unidadesBloqueadas()
+ {
+ return $this->hasMany(UnidadBloqueada::class, 'agente')->findMany();
+ }
+ public function new()
+ {
+ parent::save();
+ $tipo = model(TipoEstadoProyectoAgente::class)->where('descripcion', 'vigente')->findOne();
+ $data = [
+ 'agente' => $this->id,
+ 'fecha' => $this->fecha,
+ 'tipo' => $tipo->id
+ ];
+ $estado = model(EstadoProyectoAgente::class)->create($data);
+ $estado->save();
+ }
+}
+?>
diff --git a/src/old/Proyecto/ProyectoTipoUnidad.php b/src/old/Proyecto/ProyectoTipoUnidad.php
new file mode 100644
index 0000000..abe9d0d
--- /dev/null
+++ b/src/old/Proyecto/ProyectoTipoUnidad.php
@@ -0,0 +1,160 @@
+belongsTo(Proyecto::class, 'proyecto')->findOne();
+ }
+ public function unidades()
+ {
+ return $this->hasMany(Unidad::class, 'pt')->orderByExpr('LPAD(subtipo, 3, "0")')->orderByExpr('LPAD(descripcion, 4, "0")')->findMany();
+ }
+ public function tipo()
+ {
+ return $this->belongsTo(TipoUnidad::class, 'tipo')->findOne();
+ }
+ public function m2($tipo = 'vendible')
+ {
+ return $this->m2 + $this->logia + $this->terraza / (($tipo == 'vendible') ? 2 : 1);
+ }
+ public function lineas()
+ {
+ if ($this->lineas == null) {
+ $lineas = [];
+ foreach ($this->unidades() as $unidad) {
+ if (array_search($unidad->subtipo, $lineas) === false) {
+ $lineas []= $unidad->subtipo;
+ }
+ }
+ sort($lineas);
+ $this->lineas = implode(', ', $lineas);
+ }
+ return $this->lineas;
+ }
+ public function precio($fecha = null)
+ {
+ $sum = 0;
+ $cnt = 0;
+ foreach ($this->unidades() as $unidad) {
+ if ($unidad->precio($fecha)) {
+ $sum += $unidad->precio($fecha)->valor;
+ $cnt ++;
+ }
+ }
+ if ($cnt == 0) {
+ return 0;
+ }
+ return $sum / $cnt;
+ }
+ protected $precios;
+ public function precioSubtipo($subtipo, $fecha = null)
+ {
+ if (!isset($this->precios[$subtipo])) {
+ $sum = 0;
+ $cnt = 0;
+ foreach ($this->unidades() as $unidad) {
+ if ($unidad->subtipo == $subtipo and $unidad->precio($fecha)) {
+ $sum += $unidad->precio($fecha)->valor;
+ $cnt ++;
+ }
+ }
+ if ($this->precios == null) {
+ $this->precios = [];
+ }
+ $prom = 0;
+ if ($cnt > 0) {
+ $prom = $sum / $cnt;
+ }
+ $this->precios[$subtipo] = $prom;
+ }
+ return $this->precios[$subtipo];
+ }
+ public function setPrecios($fecha, $valor)
+ {
+ foreach ($this->unidades() as $unidad) {
+ $unidad->setPrecio($fecha, $valor);
+ }
+ }
+ public function setPreciosSubtipo($subtipo, $fecha, $valor)
+ {
+ foreach ($this->unidades() as $unidad) {
+ if ($unidad->subtipo == $subtipo) {
+ $unidad->setPrecio($fecha, $valor);
+ }
+ }
+ }
+ protected $tipologia;
+ public function tipologia()
+ {
+ if ($this->tipologia == null) {
+ $tipologias = $this->hasMany(TipoTipologia::class, 'tipo')->findMany();
+ if (!$tipologias) {
+ $this->tipologia = false;
+ return false;
+ }
+ usort($tipologias, function($a, $b) {
+ return $a->elemento()->orden - $b->elemento()->orden;
+ });
+ $tipologia = ['tipologia' => $tipologias[0]->tipologia(), 'detalles' => $tipologias];
+ $resumen = [];
+ foreach ($tipologias as $t) {
+ if (strpos($t->elemento()->descripcion, 'cocina ') !== false) {
+ $resumen []= $t->elemento()->abreviacion;
+ continue;
+ }
+ $resumen []= $t->cantidad . '' . $t->elemento()->abreviacion;
+ }
+ $tipologia['descripcion'] = implode('/', $resumen);
+ $this->tipologia = (object) $tipologia;
+ }
+ return $this->tipologia;
+ }
+ protected $ventas;
+ public function ventas($order = 'departamento')
+ {
+ if ($this->ventas == null) {
+ $ventas = model(Venta::class)
+ ->select('venta.*')
+ ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad'])
+ ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal'])
+ ->join('proyecto_tipo_unidad', ['proyecto_tipo_unidad.id', '=', 'unidad.pt'])
+ ->rawJoin('JOIN (SELECT e1.* FROM estado_venta e1 JOIN (SELECT venta, MAX(id) AS id FROM estado_venta GROUP BY venta) e0 ON e0.id = e1.id)', ['ev.venta', '=', 'venta.id'], 'ev')
+ ->join('tipo_estado_venta', ['tipo_estado_venta.id', '=', 'ev.estado'])
+ ->where('tipo_estado_venta.activa', 1)
+ ->where('proyecto_tipo_unidad.id', $this->id);
+ switch (strtolower($order)) {
+ case 'fecha':
+ $ventas = $ventas->orderByAsc('venta.fecha');
+ case 'departamento':
+ default:
+ $ventas = $ventas->orderByExpr('LPAD(unidad.descripcion, 4, "0")');
+ break;
+ }
+ $ventas = $ventas->findMany();
+ $this->ventas = $ventas;
+ }
+ return $this->ventas;
+ }
+}
diff --git a/src/old/Proyecto/RelacionAgentes.php b/src/old/Proyecto/RelacionAgentes.php
new file mode 100644
index 0000000..bf29ce5
--- /dev/null
+++ b/src/old/Proyecto/RelacionAgentes.php
@@ -0,0 +1,16 @@
+
diff --git a/src/old/Proyecto/RenovacionPagare.php b/src/old/Proyecto/RenovacionPagare.php
new file mode 100644
index 0000000..783f4f9
--- /dev/null
+++ b/src/old/Proyecto/RenovacionPagare.php
@@ -0,0 +1,90 @@
+belongsTo(Pagare::class, 'pagare')->findOne();
+ }
+ public function fecha(\DateTime $fecha = null)
+ {
+ if ($fecha == null) {
+ return Carbon::parse($this->fecha, config('app.timezone'));
+ }
+ $this->fecha = $fecha->format('Y-m-d');
+ }
+ public function fechaBanco(\DateTime $fecha = null)
+ {
+ if ($fecha == null) {
+ return Carbon::parse($this->fecha_banco, config('app.timezone'));
+ }
+ $this->fecha_banco = $fecha->format('Y-m-d');
+ }
+ public function vencimiento()
+ {
+ return $this->fecha()->addDays($this->duracion);
+ }
+ public function uf()
+ {
+ if ($this->uf == 0) {
+ $uf = uf($this->fecha());
+ if ($uf->total > 0) {
+ $this->uf = $uf->uf->value;
+ $this->save();
+ }
+ }
+ return $this->uf;
+ }
+ protected $valores;
+ public function valor($tipo = 'ufs')
+ {
+ if ($this->valores == null) {
+ $valores = [];
+ switch (strtolower($this->pagare()->moneda()->descripcion)) {
+ case 'uf':
+ $valores = (object) ['uf' => $this->insoluto, 'pesos' => $this->insoluto * $this->uf()];
+ break;
+ case 'pesos':
+ $valores = (object) ['uf' => $this->insoluto / $this->uf(), 'pesos' => $this->insoluto];
+ break;
+ }
+ $this->valores = $valores;
+ }
+ switch (strtolower($tipo)) {
+ case 'uf':
+ case 'ufs':
+ return $this->valores->uf;
+ case 'peso':
+ case 'pesos':
+ return $this->valores->pesos;
+ }
+ }
+ protected $intereses_arr;
+ public function intereses($tipo = 'ufs') {
+ if ($this->intereses_arr == null) {
+ $this->intereses_arr = (object) ['uf' => $this->intereses / $this->uf(), 'pesos' => $this->intereses];
+ }
+ switch (strtolower($tipo)) {
+ case 'uf':
+ case 'ufs':
+ return $this->intereses_arr->uf;
+ case 'peso':
+ case 'pesos':
+ return $this->intereses_arr->pesos;
+ }
+ }
+}
diff --git a/src/old/Proyecto/TipoAgente.php b/src/old/Proyecto/TipoAgente.php
new file mode 100644
index 0000000..3611f44
--- /dev/null
+++ b/src/old/Proyecto/TipoAgente.php
@@ -0,0 +1,24 @@
+hasManyThrough(Agente::class, AgenteTipo::class, 'tipo', 'agente')->findMany();
+ }
+}
+?>
diff --git a/src/old/Proyecto/TipoCobro.php b/src/old/Proyecto/TipoCobro.php
new file mode 100644
index 0000000..20adb76
--- /dev/null
+++ b/src/old/Proyecto/TipoCobro.php
@@ -0,0 +1,17 @@
+
diff --git a/src/old/Proyecto/TipoElemento.php b/src/old/Proyecto/TipoElemento.php
new file mode 100644
index 0000000..a7e636b
--- /dev/null
+++ b/src/old/Proyecto/TipoElemento.php
@@ -0,0 +1,12 @@
+
diff --git a/src/old/Proyecto/TipoEstadoProyecto.php b/src/old/Proyecto/TipoEstadoProyecto.php
new file mode 100644
index 0000000..d65896c
--- /dev/null
+++ b/src/old/Proyecto/TipoEstadoProyecto.php
@@ -0,0 +1,23 @@
+belongs_to(EtapaProyecto::class, 'etapa')->findOne();
+ }
+}
+?>
diff --git a/src/old/Proyecto/TipoEstadoProyectoAgente.php b/src/old/Proyecto/TipoEstadoProyectoAgente.php
new file mode 100644
index 0000000..deb2c51
--- /dev/null
+++ b/src/old/Proyecto/TipoEstadoProyectoAgente.php
@@ -0,0 +1,12 @@
+
diff --git a/src/old/Proyecto/TipoTipologia.php b/src/old/Proyecto/TipoTipologia.php
new file mode 100644
index 0000000..a6cdc3d
--- /dev/null
+++ b/src/old/Proyecto/TipoTipologia.php
@@ -0,0 +1,27 @@
+belongsTo(ProyectoTipoUnidad::class, 'tipo')->findOne();
+ }
+ public function tipologia()
+ {
+ return $this->belongsTo(Tipologia::class, 'tipologia')->findOne();
+ }
+ public function elemento()
+ {
+ return $this->belongsTo(TipoElemento::class, 'elemento')->findOne();
+ }
+}
diff --git a/src/old/Proyecto/Tipologia.php b/src/old/Proyecto/Tipologia.php
new file mode 100644
index 0000000..eab84d8
--- /dev/null
+++ b/src/old/Proyecto/Tipologia.php
@@ -0,0 +1,12 @@
+belongs_to(Pago::class, 'pago')->findOne();
+ }
+}
+?>
diff --git a/src/old/Venta/Cierre.php b/src/old/Venta/Cierre.php
new file mode 100644
index 0000000..e0fb88e
--- /dev/null
+++ b/src/old/Venta/Cierre.php
@@ -0,0 +1,335 @@
+select('cierre.*')
+ ->join('unidad_cierre', ['unidad_cierre.cierre', '=', 'cierre.id'])
+ ->where('cierre.proyecto', $proyecto->id)
+ ->where('unidad_cierre.unidad', $unidad->id)
+ ->where('cierre.precio', $precio);
+ }
+ public static function vigentes()
+ {
+ return model(Cierre::class)
+ ->select('cierre.*')
+ ->join('estado_cierre', ['estado_cierre.cierre', '=', 'cierre.id'])
+ ->join('tipo_estado_cierre', ['tipo_estado_cierre.id', '=', 'estado_cierre.tipo'])
+ ->join('proyecto', ['proyecto.id', '=', 'cierre.proyecto'])
+ ->where('tipo_estado_cierre.vigente', 1)
+ ->orderByAsc('proyecto.descripcion')
+ ->orderByAsc('cierre.fecha')
+ ->groupBy('cierre.id')
+ ->findMany();
+ }
+ public static function proyectos()
+ {
+ return model(Proyecto::class)
+ ->select('proyecto.*')
+ ->join('cierre', ['proyecto.id', '=', 'cierre.proyecto'])
+ ->join('estado_cierre', ['estado_cierre.cierre', '=', 'cierre.id'])
+ ->join('tipo_estado_cierre', ['tipo_estado_cierre.id', '=', 'estado_cierre.tipo'])
+ ->where('tipo_estado_cierre.vigente', 1)
+ ->orderByAsc('proyecto.descripcion')
+ ->orderByAsc('cierre.fecha')
+ ->groupBy('proyecto.id')
+ ->findMany();
+ }
+
+ public function proyecto()
+ {
+ return $this->belongsTo(Proyecto::class, 'proyecto')->findOne();
+ }
+ public function unidades()
+ {
+ return $this->hasMany(UnidadCierre::class, 'cierre')->where('principal', 0)->findMany();
+ }
+ public function unidadPrincipal()
+ {
+ return $this->hasMany(UnidadCierre::class, 'cierre')->where('principal', 1)->findOne();
+ }
+ public function fecha(\DateTime $fecha = null)
+ {
+ if ($fecha == null) {
+ return Carbon::parse($this->fecha, config('app.timezone'));
+ }
+ $this->fecha = $fecha->format('Y-m-d');
+ }
+ public function propietario()
+ {
+ $propietario = $this->belongsTo(Propietario::class, 'propietario');
+ if ($propietario) {
+ return $propietario->findOne();
+ }
+ return false;
+ }
+ public function uf_m2()
+ {
+ return $this->neto() / $this->unidadPrincipal()->unidad()->m2();
+ }
+ public function neto()
+ {
+ $valor = $this->precio;
+ foreach ($this->unidades() as $unidad) {
+ $valor -= $unidad->unidad()->precio($this->fecha())->valor;
+ }
+ foreach ($this->valores() as $v) {
+ if ($v->tipo()->descripcion == 'pie') {
+ continue;
+ }
+ $valor -= $v->valor;
+ }
+ return $valor;
+ }
+ public function valores()
+ {
+ return $this->hasMany(ValorCierre::class, 'cierre')->findMany();
+ }
+ public function valor($tipo = 'pie')
+ {
+ return $this->hasMany(ValorCierre::class, 'cierre')
+ ->select('valor_cierre.*')
+ ->join('tipo_valor_cierre', ['tipo_valor_cierre.id', '=', 'valor_cierre.tipo'])
+ ->where('tipo_valor_cierre.descripcion', $tipo)
+ ->findOne();
+ }
+ public function estados()
+ {
+ return $this->hasMany(EstadoCierre::class, 'cierre')->findMany();
+ }
+ public function estado(\DateTime $fecha = null)
+ {
+ if ($fecha == null) {
+ $estado = $this->hasMany(EstadoCierre::class, 'cierre')->orderByDesc('id')->findOne();
+ if ($estado->tipo()->vigente == 1 and $this->oldest()) {
+ if ($this->promesa() and $estado->tipo()->descripcion != 'promesado') {
+ $tipo = model(TipoEstadoCierre::class)->where('descripcion', 'promesado')->findOne();
+ $data = [
+ 'cierre' => $this->id,
+ 'tipo' => $tipo->id,
+ 'fecha' => $this->promesa()->fecha
+ ];
+ $estado = model(EstadoCierre::class)->create($data);
+ $estado->save();
+ }
+ }
+ } else {
+ $estado = $this->hasMany(EstadoCierre::class, 'cierre')->whereLte('fecha', $fecha->format('Y-m-d'))->orderByDesc('id')->findOne();
+ }
+ return $estado;
+ }
+ public function new(\DateTime $fecha)
+ {
+ $this->save();
+ $tipo = model(TipoEstadoCierre::class)->where('descripcion', 'revisado')->findOne();
+ $data = [
+ 'cierre' => $this->id,
+ 'tipo' => $tipo->id,
+ 'fecha' => $fecha->format('Y-m-d')
+ ];
+ $estado = model(EstadoCierre::class)->create($data);
+ $estado->save();
+
+ if ($this->other()) {
+ $this->replace($fecha);
+ }
+ }
+ protected function cierresUnidad() {
+ $up = $this->unidadPrincipal();
+ if (!$up) {
+ return false;
+ }
+ $up = $up->id;
+ $cierres = model(Cierre::class)
+ ->select('cierre.*')
+ ->join('unidad_cierre', ['unidad_cierre.cierre', '=', 'cierre.id'])
+ ->where('unidad_cierre.unidad', $up)
+ ->findMany();
+ $id = $this->id;
+ $cierres = array_filter($cierres, function($item) use ($id) {
+ return ($id != $item->id);
+ });
+ return $cierres;
+ }
+ protected function other(): bool {
+ $cierres = $this->cierresUnidad();
+ if ($cierres and count($cierres) > 0) {
+ return true;
+ }
+ return false;
+ }
+ protected function oldest(): bool {
+ if ($this->other()) {
+ $last = $this->cierresUnidad()[count($this->cierresUnidad()) - 1];
+ if ($last->fecha < $this->fecha) {
+ return true;
+ }
+ return false;
+ }
+ return true;
+ }
+ protected function replace(\DateTime $fecha) {
+ $cierres = $this->cierresUnidad();
+ $tipo = model(TipoEstadoCierre::class)->where('descripcion', 'abandonado')->findOne();
+ array_walk($cierres, function($item) use ($tipo, $fecha) {
+ $data = [
+ 'cierre' => $item->id,
+ 'tipo' => $tipo->id,
+ 'fecha' => $fecha->format('Y-m-d')
+ ];
+ $estado = model(EstadoCierre::class)->create($data);
+ $estado->save();
+ });
+ }
+ public function addUnidad(array $data)
+ {
+ $data['cierre'] = $this->id;
+ $unidad = model(UnidadCierre::class)->create($data);
+ $unidad->save();
+ }
+ public function addValor(array $data)
+ {
+ $data['cierre'] = $this->id;
+ $tipo = model(TipoValorCierre::class)->where('descripcion', $data['tipo'])->findOne();
+ $data['tipo'] = $tipo->id;
+ $valor = model(ValorCierre::class)->create($data);
+ $valor->save();
+ }
+ public static function evaluar($precio_neto, $unidad, $fecha, $relacionado = false)
+ {
+ $precio_oferta = round($precio_neto, 2);
+ $precio_lista = round($unidad->precio($fecha)->valor * (($relacionado) ? (1 - 0.06) : 1), 2);
+ if ($precio_oferta >= $precio_lista) {
+ return true;
+ }
+ return false;
+ }
+ public function guardar(object $input)
+ {
+ $this->proyecto = $input->proyecto->id;
+ $this->precio = $input->precio;
+ $this->fecha = $input->fecha->format('Y-m-d');
+ $this->relacionado = 0;
+ if (isset($input->relacionado) and $input->relacionado) {
+ $this->relacionado = 1;
+ }
+ if (isset($input->subrelacionado) and $input->subrelacionado) {
+ $this->relacionado = 2;
+ }
+ $fecha = Carbon::today(config('app.timezone'));
+ $this->new($fecha);
+
+ $data = [
+ 'unidad' => $input->departamento->id,
+ 'principal' => 1
+ ];
+ $this->addUnidad($data);
+
+ foreach ($input->unidades as $unidad) {
+ $data = ['unidad' => $unidad->id];
+ $this->addUnidad($data);
+ }
+
+ if (isset($input->pie)) {
+ $data = [
+ 'tipo' => 'pie',
+ 'valor' => $input->pie
+ ];
+ $this->addValor($data);
+ }
+ if (isset($input->bono)) {
+ $data = [
+ 'tipo' => 'bono pie',
+ 'valor' => $input->bono
+ ];
+ $this->addValor($data);
+ }
+ if (isset($input->promocion)) {
+ $data = [
+ 'tipo' => 'premio',
+ 'valor' => $input->promocion
+ ];
+ $this->addValor($data);
+ }
+ if (isset($input->operador)) {
+ $data = [
+ 'tipo' => 'operador',
+ 'valor' => $input->operador * $this->precio / 100
+ ];
+ $this->addValor($data);
+ }
+ }
+ public function aprobar(\DateTime $fecha)
+ {
+ $tipo = model(TipoEstadoCierre::class)->where('descripcion', 'aprobado')->findOne();
+ $data = [
+ 'cierre' => $this->id,
+ 'tipo' => $tipo->id
+ ];
+ $estado = (new Factory(EstadoCierre::class))->where($data)->find();
+ if (!$estado) {
+ $data['fecha'] = $fecha->format('Y-m-d');
+ $estado = model(EstadoCierre::class)->create($data);
+ $estado->save();
+ }
+ }
+ public function rechazar(\DateTime $fecha)
+ {
+ $tipo = model(TipoEstadoCierre::class)->where('descripcion', 'rechazado')->findOne();
+ $data = [
+ 'cierre' => $this->id,
+ 'tipo' => $tipo->id
+ ];
+ $estado = (new Factory(EstadoCierre::class))->where($data)->find();
+ if (!$estado) {
+ $data['fecha'] = $fecha->format('Y-m-d');
+ $estado = model(EstadoCierre::class)->create($data);
+ $estado->save();
+ }
+ }
+ protected $promesa;
+ public function promesa()
+ {
+ if ($this->promesa == null) {
+ $propiedad = model(Propiedad::class)->where('unidad_principal', $this->unidadPrincipal()->unidad)->findOne();
+ if (!$propiedad) {
+ return false;
+ }
+ $this->promesa = model(Venta::class)->where('propiedad', $propiedad->id)->where('estado', 1)->findOne();
+ if ($this->promesa != null and $this->propietario == 0) {
+ $this->propietario = $this->promesa->propietario;
+ $this->save();
+ }
+ }
+ return $this->promesa;
+ }
+ public function isRelacionado() {
+ return ($this->relacionado == 1) ? true : false;
+ }
+ public function isSubrelacionado() {
+ return ($this->relacionado == 2) ? true : false;
+ }
+ public function periodo() {
+ $today = Carbon::today(config('app.timezone'));
+ $dif = $today->diffInDays($this->fecha());
+ return $dif;
+ }
+}
diff --git a/src/old/Venta/Comentario.php b/src/old/Venta/Comentario.php
new file mode 100644
index 0000000..f6953ab
--- /dev/null
+++ b/src/old/Venta/Comentario.php
@@ -0,0 +1,22 @@
+belongsTo(Venta::class, 'venta')->findOne();
+ }
+}
+?>
diff --git a/src/old/Venta/Credito.php b/src/old/Venta/Credito.php
new file mode 100644
index 0000000..33d1315
--- /dev/null
+++ b/src/old/Venta/Credito.php
@@ -0,0 +1,29 @@
+belongs_to(Pago::class, 'pago')->findOne();
+ }
+ public function venta()
+ {
+ return $this->hasOne(Venta::class, 'credito')->findOne();
+ }
+}
+?>
diff --git a/src/old/Venta/Cuota.php b/src/old/Venta/Cuota.php
new file mode 100644
index 0000000..e52aeb1
--- /dev/null
+++ b/src/old/Venta/Cuota.php
@@ -0,0 +1,72 @@
+belongs_to(Pago::class, 'pago')->findOne();
+ }
+ public function pie()
+ {
+ return $this->belongs_to(Pie::class, 'pie')->findOne();
+ }
+ public function uf()
+ {
+ if ($this->uf == 0) {
+ $uf = $this->pago()->uf();
+ if ($uf == 1) {
+ $uf = $this->pie()->uf();
+ }
+ $this->uf = $uf;
+ }
+ return $this->uf;
+ }
+ public function valor($tipo = 'pesos')
+ {
+ $valor = $this->pago()->valor;
+ if ($tipo == 'pesos') {
+ return $valor;
+ }
+ $uf = $this->uf();
+ if ($uf == 0) {
+ return 0;
+ }
+ return $valor / $uf;
+ }
+ public function numero()
+ {
+ if ($this->numero == '') {
+ $cuotas = $this->pie()->cuotas('fecha');
+ $n = 0;
+ foreach ($cuotas as $cuota) {
+ $n ++;
+ if ($cuota->id == $this->id) {
+ $this->numero = $n;
+ $this->save();
+ break;
+ }
+ }
+ }
+ return $this->numero;
+ }
+}
+?>
diff --git a/src/old/Venta/Entrega.php b/src/old/Venta/Entrega.php
new file mode 100644
index 0000000..035a227
--- /dev/null
+++ b/src/old/Venta/Entrega.php
@@ -0,0 +1,21 @@
+
diff --git a/src/old/Venta/Escritura.php b/src/old/Venta/Escritura.php
new file mode 100644
index 0000000..09eb21d
--- /dev/null
+++ b/src/old/Venta/Escritura.php
@@ -0,0 +1,24 @@
+belongs_to(Pago::class, 'pago')->findOne();
+ }
+}
+?>
diff --git a/src/old/Venta/EstadoCierre.php b/src/old/Venta/EstadoCierre.php
new file mode 100644
index 0000000..e3ec49a
--- /dev/null
+++ b/src/old/Venta/EstadoCierre.php
@@ -0,0 +1,30 @@
+belongsTo(Cierre::class, 'cierre')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongsTo(TipoEstadoCierre::class, 'tipo')->findOne();
+ }
+ public function fecha(\DateTime $fecha = null)
+ {
+ if ($fecha == null) {
+ return Carbon::parse($this->fecha, config('app.timezone'));
+ }
+ $this->fecha = $fecha->format('Y-m-d');
+ }
+}
diff --git a/src/old/Venta/EstadoPago.php b/src/old/Venta/EstadoPago.php
new file mode 100644
index 0000000..7f18da1
--- /dev/null
+++ b/src/old/Venta/EstadoPago.php
@@ -0,0 +1,27 @@
+belongs_to(TipoEstadoPago::class, 'estado')->findOne();
+ }
+ public function fecha()
+ {
+ return Carbon::parse($this->fecha, config('app.timezone'));
+ }
+}
+?>
diff --git a/src/old/Venta/EstadoPrecio.php b/src/old/Venta/EstadoPrecio.php
new file mode 100644
index 0000000..58c3657
--- /dev/null
+++ b/src/old/Venta/EstadoPrecio.php
@@ -0,0 +1,33 @@
+belongsTo(Precio::class, 'precio')->findOne();
+ }
+ public function fecha($fecha = null)
+ {
+ if ($fecha == null) {
+ return Carbon::parse($this->fecha, config('app.timezone'));
+ }
+ if (is_a($fecha, \DateTime::class)) {
+ $fecha = $fecha->format('Y-m-d');
+ }
+ $this->fecha = $fecha;
+ }
+ public function estado()
+ {
+ return $this->belongsTo(TipoEstadoPrecio::class, 'estado')->findOne();
+ }
+}
diff --git a/src/old/Venta/EstadoProblema.php b/src/old/Venta/EstadoProblema.php
new file mode 100644
index 0000000..c6b8ce2
--- /dev/null
+++ b/src/old/Venta/EstadoProblema.php
@@ -0,0 +1,17 @@
+
diff --git a/src/old/Venta/EstadoUnidadBloqueada.php b/src/old/Venta/EstadoUnidadBloqueada.php
new file mode 100644
index 0000000..f11ea1b
--- /dev/null
+++ b/src/old/Venta/EstadoUnidadBloqueada.php
@@ -0,0 +1,30 @@
+belongsTo(UnidadBloqueada::class, 'unidad')->findOne();
+ }
+ public function fecha(\DateTime $fecha = null)
+ {
+ if ($fecha == null) {
+ return Carbon::parse($this->fecha, config('app.timezone'));
+ }
+ $this->fecha = $fecha->format('Y-m-d');
+ }
+ public function tipo()
+ {
+ return $this->belongsTo(TipoEstadoUnidadBloqueada::class, 'tipo')->findOne();
+ }
+}
diff --git a/src/old/Venta/EstadoVenta.php b/src/old/Venta/EstadoVenta.php
new file mode 100644
index 0000000..5e75070
--- /dev/null
+++ b/src/old/Venta/EstadoVenta.php
@@ -0,0 +1,27 @@
+belongsTo(Venta::class, 'venta')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongsTo(TipoEstadoVenta::class, 'estado')->findOne();
+ }
+ public function fecha()
+ {
+ return Carbon::parse($this->fecha, config('app.timezone'));
+ }
+}
diff --git a/src/old/Venta/Pago.php b/src/old/Venta/Pago.php
new file mode 100644
index 0000000..d4c2910
--- /dev/null
+++ b/src/old/Venta/Pago.php
@@ -0,0 +1,156 @@
+belongs_to(Banco::class, 'banco');
+ if ($banco) {
+ return $banco->findOne();
+ }
+ return null;
+ }
+ public function tipo()
+ {
+ return $this->belongs_to(TipoPago::class, 'tipo')->findOne();
+ }
+ public function estados($order = 'fecha', $direction = 'desc')
+ {
+ $estados = $this->has_many(EstadoPago::class, 'pago');
+ if ($direction == 'desc') {
+ $estados->orderByDesc($order);
+ if ($order != 'id') {
+ $estados->orderByDesc('id');
+ }
+ } else {
+ $estados->orderByAsc($order);
+ if ($order != 'id') {
+ $estados->orderByAsc('id');
+ }
+ }
+ return $estados->findMany();
+ }
+ public function estado()
+ {
+ $estado = $this->has_many(EstadoPago::class, 'pago')->order_by_desc('id')->findOne();
+ return $estado;
+ }
+ public function fecha()
+ {
+ return Carbon::parse($this->fecha, config('app.timezone'));
+ }
+ public function uf()
+ {
+ if ($this->uf == 0) {
+ $uf = uf($this->fecha);
+ if (!$uf or $uf->total == 0) {
+ return 1;
+ }
+ if ($uf->total > 0) {
+ $this->uf = $uf->uf->value;
+ $this->save();
+ }
+ }
+ return $this->uf;
+ }
+ public function valor($tipo = 'pesos')
+ {
+ $valor = $this->valor;
+ if ($tipo == 'ufs') {
+ $uf = $this->uf();
+ if ($uf == 1) {
+ $uf = $this->fuente()[0]->obj->uf();
+ }
+ $valor /= $uf;
+ if ($this->asociado() and $this->asociado == 0) {
+ $valor += $this->asociado()->valor('ufs');
+ }
+ return $valor;
+ }
+ if ($this->asociado() and $this->asociado == 0) {
+ $valor += $this->asociado()->valor();
+ }
+ return $valor;
+ }
+ public function new()
+ {
+ $this->save();
+
+ $estado = \Model::factory(EstadoPago::class)->create();
+ $estado->pago = $this->id;
+ $estado->fecha = $this->fecha;
+ $estado->estado = 0;
+ $estado->save();
+ }
+ public function newPagado()
+ {
+ $this->new();
+
+ $estado = \Model::factory(EstadoPago::class)->create();
+ $estado->pago = $this->id;
+ $estado->fecha = $this->fecha;
+ $estado->estado = 1;
+ $estado->save();
+ }
+ public function fuente()
+ {
+ $results = [];
+ $cuota = model(Cuota::class)->where('pago', $this->id)->findOne();
+ if ($cuota) {
+ $results []= (object) ['tipo' => 'cuota', 'obj' => $cuota];
+ }
+ $credito = model(Credito::class)->where('pago', $this->id)->findOne();
+ if ($credito) {
+ $results []= (object) ['tipo' => 'credito', 'obj' => $credito];
+ }
+ $escritura = model(Escritura::class)->where('pago', $this->id)->findOne();
+ if ($escritura) {
+ $results []= (object) ['tipo' => 'escritura', 'obj' => $escritura];
+ }
+ $subsidio = model(Subsidio::class)->where('pago', $this->id)->findOne();
+ if ($subsidio) {
+ $results []= (object) ['tipo' => 'subsidio', 'obj' => $subsidio];
+ }
+ $bono = model(BonoPie::class)->where('pago', $this->id)->findOne();
+ if ($bono) {
+ $results []= (object) ['tipo' => 'bono_pie', 'obj' => $bono];
+ }
+ return $results;
+ }
+ public function asociado()
+ {
+ if ($this->asociado == 0) {
+ return $this->hasOne(Pago::class, 'asociado')->findOne();
+ }
+ return $this->belongsTo(Pago::class, 'asociado')->findOne();
+ }
+
+ public static function filterEstado(\ORM $orm)
+ {
+ return $orm->rawJoin(
+ 'JOIN (SELECT ep.* FROM (SELECT pago, MAX(id) AS id FROM estado_pago GROUP BY pago) e0 JOIN estado_pago ep ON ep.id = e0.id)',
+ ['estado_pago.pago', '=', 'pago.id'],
+ 'estado_pago'
+ );
+ }
+}
+?>
diff --git a/src/old/Venta/Pie.php b/src/old/Venta/Pie.php
new file mode 100644
index 0000000..40f29d7
--- /dev/null
+++ b/src/old/Venta/Pie.php
@@ -0,0 +1,225 @@
+asociado != 0) {
+ return $this->asociado()->cuotas();
+ }
+ $cuotas = $this->hasMany(Cuota::class, 'pie')
+ ->select('cuota.*')
+ ->join('pago', ['pago.id', '=', 'cuota.pago'])
+ ->rawJoin('JOIN (SELECT e1.* FROM (SELECT pago, MAX(id) AS id FROM estado_pago GROUP BY pago) e0 JOIN estado_pago e1 ON e1.id = e0.id)', ['ep.pago', '=', 'pago.id'], 'ep')
+ ->join('tipo_estado_pago', ['tipo_estado_pago.id', '=', 'ep.estado'])
+ ->whereNotEqual('tipo_estado_pago.descripcion', 'reemplazado')
+ ->whereNotEqual('tipo_estado_pago.descripcion', 'anulado');
+ switch ($order) {
+ case 'numero':
+ case 'number':
+ default:
+ $cuotas = $cuotas->orderByAsc('cuota.numero');
+ case 'fecha':
+ case 'date':
+ $cuotas = $cuotas->orderByAsc('pago.fecha')
+ ->orderByDesc('pago.valor');
+ break;
+ }
+ $cuotas = $cuotas->findMany();
+ return $cuotas;
+ }
+ public function pagadas()
+ {
+ $estado = model(TipoEstadoPago::class)->where('descripcion', 'depositado')->findOne();
+ $cuotas = $this->cuotas();
+ foreach ($cuotas as $i => &$cuota) {
+ if ($cuota->pago()->estado()->estado < $estado->id) {
+ unset($cuotas[$i]);
+ }
+ }
+ array_values($cuotas);
+ return $cuotas;
+ }
+ public function abonadas()
+ {
+ $estado = model(TipoEstadoPago::class)->where('descripcion', 'abonado')->findOne();
+ $cuotas = $this->pagadas();
+ foreach ($cuotas as $i => &$cuota) {
+ if ($cuota->pago()->estado()->estado != $estado->id) {
+ unset($cuotas[$i]);
+ }
+ }
+ array_values($cuotas);
+ return $cuotas;
+ }
+ public function rebotadas()
+ {
+ $estado = model(TipoEstadoPago::class)->where('descripcion', 'devuelto')->findOne();
+ $cuotas = $this->cuotas();
+ foreach ($cuotas as $i => &$cuota) {
+ if ($cuota->pago()->estado()->estado != $estado->id) {
+ unset($cuotas[$i]);
+ }
+ }
+ array_values($cuotas);
+ return $cuotas;
+ }
+ public function valorPesos()
+ {
+ return $this->valor * $this->uf();
+ }
+ public function valorPagado($tipo = 'uf')
+ {
+ $cuotas = $this->pagadas();
+ $sum = 0;
+ foreach ($cuotas as $cuota) {
+ $pago = $cuota->pago();
+ if ($tipo == 'uf' or $tipo == 'ufs') {
+ if ($pago->uf() == 0) {
+ $sum += $pago->valor / $this->uf();
+ continue;
+ }
+ $sum += $pago->valor / $pago->uf();
+ } else {
+ $sum += $pago->valor;
+ }
+ }
+
+ return $sum * $this->proporcion();
+ }
+ public function valorAbonado($tipo = 'uf')
+ {
+ $cuotas = $this->abonadas();
+ $sum = 0;
+ foreach ($cuotas as $cuota) {
+ $pago = $cuota->pago();
+ if ($tipo == 'uf' or $tipo == 'ufs') {
+ if ($pago->uf() == 0) {
+ $sum += $pago->valor / $this->uf();
+ continue;
+ }
+ $sum += $pago->valor / $pago->uf;
+ } else {
+ $sum += $pago->valor;
+ }
+ }
+
+ return $sum * $this->proporcion();
+ }
+ public function reajuste()
+ {
+ $reajuste = $this->belongsTo(Pago::class, 'reajuste');
+ if ($reajuste) {
+ $reajuste = $reajuste->findOne();
+ return $reajuste;
+ }
+ return null;
+ }
+ public function venta()
+ {
+ return $this->has_one(Venta::class, 'pie')->findOne();
+ }
+ public function asociado()
+ {
+ $pie = $this->belongs_to(Pie::class, 'asociado')->findOne();
+ if ($pie) {
+ return $pie;
+ }
+ return null;
+ }
+ private $asociados = null;
+ public function asociados()
+ {
+ if ($this->asociados == null) {
+ $pie = $this->has_many(Pie::class, 'asociado');
+ if (!$pie) {
+ return null;
+ }
+ $asociados = $pie->findMany();
+ usort($asociados, function($a, $b) {
+ return strcmp($a->venta()->unidad()->descripcion, $b->venta()->unidad()->descripcion);
+ });
+ $this->asociados = $asociados;
+ }
+ return $this->asociados;
+ }
+ public function proporcion()
+ {
+ $pie = $this;
+ if ($this->asociado != 0) {
+ $pie = $this->asociado();
+ }
+ if ($pie->asociados() != null) {
+ $pies = $pie->asociados();
+ $base = $pie->valor;
+ foreach ($pies as $p) {
+ $base += $p->valor;
+ }
+
+ return $this->valor / $base;
+ }
+ return 1;
+ }
+ public function pendientes()
+ {
+ return count($this->cuotas()) - count($this->pagadas());
+ }
+ public function pagos($estado = 0)
+ {
+ $pagos = model(Pago::class)
+ ->select('pago.*')
+ ->join('cuota', ['cuota.pago', '=', 'pago.id'])
+ ->filter('filterEstado')
+ ->where('estado_pago.estado', $estado)
+ ->where('cuota.pie', $this->id)
+ ->findMany();
+ if ($this->reajuste != 0 and $this->reajuste()->estado()->estado == $estado) {
+ $pagos []= $this->reajuste();
+ }
+ return $pagos;
+ }
+ public function uf()
+ {
+ if ($this->uf == 0) {
+ $uf = uf($this->fecha);
+ if (!$uf) {
+ return 1;
+ }
+ if ($uf->total > 0) {
+ $this->uf = $uf->uf->value;
+ $this->save();
+ }
+ }
+ return $this->uf;
+ }
+ public function valor($tipo = 'pesos')
+ {
+ switch ($tipo) {
+ case 'uf':
+ case 'ufs':
+ return $this->valor;
+ break;
+ case 'peso':
+ case 'pesos':
+ default:
+ return $this->valorPesos();
+ break;
+ }
+ }
+}
+?>
diff --git a/src/old/Venta/Precio.php b/src/old/Venta/Precio.php
new file mode 100644
index 0000000..a80c5ed
--- /dev/null
+++ b/src/old/Venta/Precio.php
@@ -0,0 +1,81 @@
+belongsTo(Unidad::class, 'unidad')->findOne();
+ }
+ public function estados()
+ {
+ return $this->hasMany(EstadoPrecio::class, 'precio')->findMany();
+ }
+ public function estado()
+ {
+ return \model(EstadoPrecio::class)
+ ->select('estado_precio.*')
+ ->rawJoin('JOIN (SELECT precio, MAX(id) AS id FROM estado_precio GROUP BY precio)', ['e0.id', '=', 'estado_precio.id'], 'e0')
+ ->where('estado_precio.precio', $this->id)
+ ->findOne();
+ }
+ public function inicio()
+ {
+ return \model(EstadoPrecio::class)
+ ->where('estado_precio.precio', $this->id)
+ ->orderByAsc('id')
+ ->findOne();
+ }
+ public function vigente()
+ {
+ if ($this->estado()->estado()->descripcion == 'vigente') {
+ return true;
+ }
+ return false;
+ }
+ public function reemplazar($fecha)
+ {
+ if ($this->estado()->estado()->descripcion == 'reemplazado') {
+ return;
+ }
+ $tipo = model(TipoEstadoPrecio::class)->where('descripcion', 'reemplazado')->findOne();
+ $data = [
+ 'precio' => $this->id,
+ 'fecha' => $fecha->format('Y-m-d'),
+ 'estado' => $tipo->id
+ ];
+ $estado = model(EstadoPrecio::class)->create($data);
+ $estado->save();
+ }
+ public function actualizar($fecha)
+ {
+ $tipo = model(TipoEstadoPrecio::class)->where('descripcion', 'vigente')->findOne();
+ $data = [
+ 'precio' => $this->id,
+ 'fecha' => $fecha->format('Y-m-d'),
+ 'estado' => $tipo->id
+ ];
+ $estado = model(EstadoPrecio::class)->create($data);
+ $estado->save();
+ }
+ public function new($fecha)
+ {
+ $this->save();
+
+ $tipo = model(TipoEstadoPrecio::class)->where('descripcion', 'vigente')->findOne();
+ $data = [
+ 'precio' => $this->id,
+ 'fecha' => $fecha->format('Y-m-d'),
+ 'estado' => $tipo->id
+ ];
+ $estado = model(EstadoPrecio::class)->create($data);
+ $estado->save();
+ }
+}
diff --git a/src/old/Venta/Problema.php b/src/old/Venta/Problema.php
new file mode 100644
index 0000000..080b363
--- /dev/null
+++ b/src/old/Venta/Problema.php
@@ -0,0 +1,16 @@
+
diff --git a/src/old/Venta/Promocion.php b/src/old/Venta/Promocion.php
new file mode 100644
index 0000000..5515566
--- /dev/null
+++ b/src/old/Venta/Promocion.php
@@ -0,0 +1,23 @@
+belongsTo(Proyecto::class, 'proyecto')->findOne();
+ }
+}
+?>
diff --git a/src/old/Venta/PromocionVenta.php b/src/old/Venta/PromocionVenta.php
new file mode 100644
index 0000000..641f3a5
--- /dev/null
+++ b/src/old/Venta/PromocionVenta.php
@@ -0,0 +1,24 @@
+belongsTo(Promocion::class, 'promocion')->findOne();
+ }
+ public function venta()
+ {
+ return $this->belongsTo(Venta::class, 'venta')->findOne();
+ }
+}
+?>
diff --git a/src/old/Venta/Propiedad.php b/src/old/Venta/Propiedad.php
new file mode 100644
index 0000000..f99a3a0
--- /dev/null
+++ b/src/old/Venta/Propiedad.php
@@ -0,0 +1,117 @@
+belongs_to(Unidad::class, 'unidad_principal')->findOne();
+ }
+ protected $unidades;
+ public function unidades() {
+ if ($this->unidades == null) {
+ $this->unidades = $this->hasMany(PropiedadUnidad::class, 'propiedad')->findMany();
+ }
+ return $this->unidades;
+ }
+ protected $departamentos;
+ public function departamentos() {
+ if ($this->departamentos == null) {
+ $this->departamentos = array_map(function($item) {
+ return $item->unidad();
+ }, array_filter($this->unidades(), function($item) {
+ return ($item->unidad()->tipo()->descripcion == 'departamento');
+ }));
+ }
+ return $this->departamentos;
+ }
+ public function estacionamientos($mod = null)
+ {
+ if ($this->estacionamientos_arr == null) {
+ if (($unidades = $this->unidades()) !== false) {
+ $estacionamientos = array_filter($unidades, function($item) {
+ return ($item->unidad()->tipo()->descripcion == 'estacionamiento');
+ });
+ $this->estacionamientos_arr = array_map(function($item) {
+ return $item->unidad();
+ }, $estacionamientos);
+ } else {
+ $ests = explode(';', $this->estacionamientos);
+ $estacionamientos = [];
+ foreach ($ests as $e) {
+ $estacionamiento = \Model::factory(Unidad::class)->findOne($e);
+ if ($estacionamiento) {
+ $estacionamientos []= $estacionamiento;
+ }
+ }
+ $this->estacionamientos_arr = $estacionamientos;
+ }
+ }
+ if ($mod != null) {
+ switch ($mod) {
+ case 'array':
+ $result = [];
+ foreach ($this->estacionamientos_arr as $est) {
+ $result []= $est->descripcion;
+ }
+ return $result;
+ }
+ }
+ return $this->estacionamientos_arr;
+ }
+ public function bodegas($mod = null)
+ {
+ if ($this->bodegas_arr == null) {
+ if (($unidades = $this->unidades()) !== false) {
+ $bodegas = array_filter($unidades, function($item) {
+ return ($item->unidad()->tipo()->descripcion == 'bodega');
+ });
+ $this->bodegas_arr = array_map(function($item) {
+ return $item->unidad();
+ }, $bodegas);
+ } else {
+ $bods = explode(';', $this->bodegas);
+ $bodegas = [];
+ foreach ($bods as $b) {
+ $bodega = \Model::factory(Unidad::class)->findOne($b);
+ if ($bodega) {
+ $bodegas []= $bodega;
+ }
+ }
+ $this->bodegas_arr = $bodegas;
+ }
+ }
+ if ($mod != null) {
+ switch ($mod) {
+ case 'array':
+ $result = [];
+ foreach ($this->bodegas_arr as $bod) {
+ $result []= $bod->descripcion;
+ }
+ return $result;
+ }
+ }
+ return $this->bodegas_arr;
+ }
+ public function venta()
+ {
+ return $this->has_one(Venta::class, 'propiedad')->findOne();
+ }
+}
+?>
diff --git a/src/old/Venta/PropiedadUnidad.php b/src/old/Venta/PropiedadUnidad.php
new file mode 100644
index 0000000..b3f9b81
--- /dev/null
+++ b/src/old/Venta/PropiedadUnidad.php
@@ -0,0 +1,25 @@
+propiedad_model == null) {
+ $this->propiedad_model = $this->belongsTo(Propiedad::class, 'propiedad')->findOne();
+ }
+ return $this->propiedad_model;
+ }
+ protected $unidad_model;
+ public function unidad() {
+ if ($this->unidad_model == null) {
+ $this->unidad_model = $this->belongsTo(Unidad::class, 'unidad')->findOne();
+ }
+ return $this->unidad_model;
+ }
+ protected $is_principal;
+ public function isPrincipal() {
+ return ($this->principal == 0) ? false : true;
+ }
+}
diff --git a/src/old/Venta/Propietario.php b/src/old/Venta/Propietario.php
new file mode 100644
index 0000000..353a30a
--- /dev/null
+++ b/src/old/Venta/Propietario.php
@@ -0,0 +1,66 @@
+belongs_to(Direccion::class, 'direccion')->findOne();
+ }
+ public function nombreCompleto($ap = false)
+ {
+ $str = '';
+ if ($ap) {
+ $str = $this->apellido_paterno . ' ' . $this->apellido_materno . ', ' . $this->nombres;
+ } else {
+ $str = $this->nombres . ' ' . $this->apellido_paterno . ' ' . $this->apellido_materno;
+ }
+ return $str;
+ }
+ public function representante()
+ {
+ $r = $this->belongsTo(Propietario::class, 'representante', 'rut');
+ if ($r) {
+ return $r->findOne();
+ }
+ return null;
+ }
+ public function ventas() {
+ return $this->hasMany(Venta::class, 'propietario', 'rut')
+ ->select('venta.*')
+ ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad'])
+ ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal'])
+ ->join('proyecto', ['proyecto.id', '=', 'unidad.proyecto'])
+ ->orderByAsc('proyecto.descripcion')
+ ->orderByExpr("LPAD(unidad.descripcion, 4, '0')")
+ ->findMany();
+ }
+ public function rut()
+ {
+ return format('rut', $this->rut) . '-' . $this->dv;
+ }
+}
+?>
diff --git a/src/old/Venta/Subsidio.php b/src/old/Venta/Subsidio.php
new file mode 100644
index 0000000..7728f41
--- /dev/null
+++ b/src/old/Venta/Subsidio.php
@@ -0,0 +1,44 @@
+belongs_to(Pago::class, 'pago')->findOne();
+ }
+ public function subsidio()
+ {
+ $pago = $this->belongs_to(Pago::class, 'subsidio');
+ if ($pago) {
+ return $pago->findOne();
+ }
+ return null;
+ }
+ public function total($tipo = 'pesos')
+ {
+ $sum = 0;
+ if ($tipo == 'pesos') {
+ $sum = $this->pago()->valor;
+ if ($this->subsidio != 0) {
+ $sum += $this->subsidio()->valor;
+ }
+ } else {
+ $sum = $this->pago()->valor('ufs');
+ if ($this->subsidio != 0) {
+ $sum += $this->subsidio()->valor('ufs');
+ }
+ }
+ return $sum;
+ }
+}
+?>
diff --git a/src/old/Venta/TipoEstadoCierre.php b/src/old/Venta/TipoEstadoCierre.php
new file mode 100644
index 0000000..881e3ac
--- /dev/null
+++ b/src/old/Venta/TipoEstadoCierre.php
@@ -0,0 +1,13 @@
+
diff --git a/src/old/Venta/TipoEstadoPrecio.php b/src/old/Venta/TipoEstadoPrecio.php
new file mode 100644
index 0000000..43aee68
--- /dev/null
+++ b/src/old/Venta/TipoEstadoPrecio.php
@@ -0,0 +1,12 @@
+activo == 1) {
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/src/old/Venta/TipoEstadoVenta.php b/src/old/Venta/TipoEstadoVenta.php
new file mode 100644
index 0000000..28105d1
--- /dev/null
+++ b/src/old/Venta/TipoEstadoVenta.php
@@ -0,0 +1,21 @@
+hasMany(EstadoVenta::class, 'estado')->findMany();
+ }
+ public function activa()
+ {
+ return ($this->activa == 1) ? true : false;
+ }
+}
diff --git a/src/old/Venta/TipoPago.php b/src/old/Venta/TipoPago.php
new file mode 100644
index 0000000..8fc3efb
--- /dev/null
+++ b/src/old/Venta/TipoPago.php
@@ -0,0 +1,17 @@
+
diff --git a/src/old/Venta/TipoUnidad.php b/src/old/Venta/TipoUnidad.php
new file mode 100644
index 0000000..731f8cd
--- /dev/null
+++ b/src/old/Venta/TipoUnidad.php
@@ -0,0 +1,17 @@
+
diff --git a/src/old/Venta/TipoValorCierre.php b/src/old/Venta/TipoValorCierre.php
new file mode 100644
index 0000000..a35385c
--- /dev/null
+++ b/src/old/Venta/TipoValorCierre.php
@@ -0,0 +1,12 @@
+belongs_to(Proyecto::class, 'proyecto')->findOne();
+ }
+ protected $propiedad;
+ public function propiedad()
+ {
+ if ($this->propiedad == null) {
+ $this->propiedad = $this->hasMany(PropiedadUnidad::class, 'unidad')->findOne();
+ }
+ return $this->propiedad;
+
+ if ($this->tipo()->descripcion == 'departamento') {
+ $propiedad = $this->has_one(Propiedad::class, 'unidad_principal');
+ if ($propiedad) {
+ return $propiedad->findOne();
+ }
+ return null;
+ }
+ if ($this->tipo()->descripcion == 'estacionamiento') {
+ // id | id; | ;id | ;id;
+ $propiedad = model(Propiedad::class)->whereLike('estacionamientos', $this->id)->findOne();
+ if ($propiedad) {
+ return $propiedad;
+ }
+ $propiedad = model(Propiedad::class)->whereLike('estacionamientos', '%;' . $this->id)->findOne();
+ if ($propiedad) {
+ return $propiedad;
+ }
+ $propiedad = model(Propiedad::class)->whereLike('estacionamientos', $this->id . ';%')->findOne();
+ if ($propiedad) {
+ return $propiedad;
+ }
+ $propiedad = model(Propiedad::class)->whereLike('estacionamientos', '%;' . $this->id . ';%')->findOne();
+ if ($propiedad) {
+ return $propiedad;
+ }
+ return null;
+ }
+ if ($this->tipo()->descripcion == 'bodega') {
+ // id | id; | ;id | ;id;
+ $propiedad = model(Propiedad::class)->whereLike('bodegas', $this->id)->findOne();
+ if ($propiedad) {
+ return $propiedad;
+ }
+ $propiedad = model(Propiedad::class)->whereLike('bodegas', '%;' . $this->id)->findOne();
+ if ($propiedad) {
+ return $propiedad;
+ }
+ $propiedad = model(Propiedad::class)->whereLike('bodegas', $this->id . ';%')->findOne();
+ if ($propiedad) {
+ return $propiedad;
+ }
+ $propiedad = model(Propiedad::class)->whereLike('bodegas', '%;' . $this->id . ';%')->findOne();
+ if ($propiedad) {
+ return $propiedad;
+ }
+ return null;
+ }
+ }
+ public function tipo()
+ {
+ return $this->belongs_to(TipoUnidad::class, 'tipo')->findOne();
+ }
+ private $venta = null;
+ public function venta()
+ {
+ if ($this->venta == null) {
+ $propiedad = $this->propiedad();
+ if ($propiedad) {
+ $venta = $propiedad->propiedad()->venta();
+ if ($venta) {
+ $this->venta = $venta;
+ }
+ }
+ }
+ return $this->venta;
+ }
+ private $m2t = null;
+ public function m2($tipo = 'vendible')
+ {
+ if ($this->m2t == null or !isset($this->m2t->{$tipo})) {
+ if ($this->m2t == null) {
+ $this->m2t = [];
+ } else {
+ $this->m2t = (Array) $this->m2t;
+ }
+
+ $this->m2t[$tipo] = $this->tipologia()->m2($tipo);
+ $this->m2t = (object) $this->m2t;
+ }
+ return $this->m2t->{$tipo};
+ }
+ public function precios()
+ {
+ return $this->hasMany(Precio::class, 'unidad')->findMany();
+ }
+ public function precio($fecha = null)
+ {
+ if ($fecha == null) {
+ return \model(Precio::class)
+ ->select('precio.*')
+ ->rawJoin('JOIN (SELECT e1.* FROM (SELECT precio, MAX(id) AS id FROM estado_precio GROUP BY precio) e0 JOIN estado_precio e1 ON e1.id = e0.id)', ['ep.precio', '=', 'precio.id'], 'ep')
+ ->where('unidad', $this->id)
+ ->where('ep.estado', 1)
+ ->findOne();
+ }
+ return \model(Precio::class)
+ ->select('precio.*')
+ ->join('estado_precio', ['ep.precio', '=', 'precio.id'], 'ep')
+ ->where('precio.unidad', $this->id)
+ ->where('ep.estado', 1)
+ ->whereLte('ep.fecha', $fecha->format('Y-m-d'))
+ ->orderByDesc('ep.fecha')
+ ->orderByDesc('ep.id')
+ ->findOne();
+ }
+ public function setPrecio($fecha, $valor)
+ {
+ $exists = false;
+ // Dejar valores antiguos reemplazados (estado = 'reemplazado')
+ foreach ($this->precios() as $precio) {
+ if (!$precio->vigente()) {
+ continue;
+ }
+ // Ya existe precio a este valor
+ if ($precio->valor == $valor) {
+ // La fecha es anterior
+ if ($precio->estado()->fecha != $fecha->format('Y-m-d')) {
+ $precio->actualizar($fecha);
+ }
+ $exists = true;
+ continue;
+ }
+ $precio->reemplazar($fecha);
+ }
+ if ($exists) {
+ return;
+ }
+ // Agregar precio
+ $data = [
+ 'unidad' => $this->id,
+ 'valor' => $valor
+ ];
+ $precio = model(Precio::class)->create($data);
+ $precio->new($fecha);
+ }
+ public function tipologia()
+ {
+ return $this->belongsTo(ProyectoTipoUnidad::class, 'pt')->findOne();
+ }
+ protected $is_vendida;
+ public function isVendida() {
+ if ($this->is_vendidad == null) {
+ $this->is_vendida = false;
+ $p = $this->propiedad();
+ if ($p) {
+ $v = $p->venta();
+ if ($v) {
+ $this->is_vendida = true;
+ }
+ }
+ }
+ return $this->is_vendida;
+ }
+ protected $cierres;
+ public function cierres() {
+ if ($this->cierres == null) {
+ $ucs = $this->hasMany(UnidadCierre::class, 'unidad')->findMany();
+ if (!$ucs) {
+ $this->cierres = false;
+ return $this->cierres;
+ }
+ $cierres = [];
+ foreach ($ucs as $uc) {
+ $c = $uc->cierre();
+ if ($c) {
+ $cierres []= $c;
+ }
+ }
+ usort($cierres, function($a, $b) {
+ return $a->fecha()->diffInDays($b->fecha());
+ });
+ $this->cierres = $cierres;
+ }
+ return $this->cierres;
+ }
+ public function cierre() {
+ if ($this->cierres()) {
+ return $this->cierres[count($this->cierres) - 1];
+ }
+ return false;
+ }
+ protected $is_reservada;
+ public function isReservada() {
+ if ($this->is_reservada == null) {
+ $this->is_reservada = false;
+ if (!$this->isVendida() and $this->cierres() !== false) {
+ $this->is_reservada = true;
+ }
+ }
+ return $this->is_reservada;
+ }
+ protected $linea;
+ public function linea() {
+ if ($this->linea == null) {
+ if ($this->tipo == 1) {
+ $this->linea = (int) \substr($this->descripcion, -2);
+ }
+ }
+ return $this->linea;
+ }
+}
+?>
diff --git a/src/old/Venta/UnidadBloqueada.php b/src/old/Venta/UnidadBloqueada.php
new file mode 100644
index 0000000..dc05771
--- /dev/null
+++ b/src/old/Venta/UnidadBloqueada.php
@@ -0,0 +1,42 @@
+belongsTo(ProyectoAgente::class, 'agente')->findOne();
+ }
+ public function unidad()
+ {
+ return $this->belongsTo(Unidad::class, 'unidad')->findOne();
+ }
+ public function estados()
+ {
+ return $this->hasMany(EstadoUnidadBloqueada::class, 'unidad')->orderByAsc('fecha')->findMany();
+ }
+ public function estado()
+ {
+ return $this->hasMany(EstadoUnidadBloqueada::class, 'unidad')->orderByDesc('fecha')->findOne();
+ }
+ public function new(\DateTime $fecha)
+ {
+ parent::save();
+ $tipo = model(TipoEstadoUnidadBloqueada::class)->where('descripcion', 'bloqueada')->findOne();
+ $data = [
+ 'unidad' => $this->id,
+ 'fecha' => $fecha->format('Y-m-d'),
+ 'tipo' => $tipo->id
+ ];
+ $estado = model(EstadoUnidadBloqueada::class)->create($data);
+ $estado->save();
+ }
+}
diff --git a/src/old/Venta/UnidadCierre.php b/src/old/Venta/UnidadCierre.php
new file mode 100644
index 0000000..4da11c8
--- /dev/null
+++ b/src/old/Venta/UnidadCierre.php
@@ -0,0 +1,22 @@
+belongsTo(Cierre::class, 'cierre')->findOne();
+ }
+ public function unidad()
+ {
+ return $this->belongsTo(Unidad::class, 'unidad')->findOne();
+ }
+}
diff --git a/src/old/Venta/ValorCierre.php b/src/old/Venta/ValorCierre.php
new file mode 100644
index 0000000..e5fd823
--- /dev/null
+++ b/src/old/Venta/ValorCierre.php
@@ -0,0 +1,22 @@
+belongsTo(Cierre::class, 'cierre')->findOne();
+ }
+ public function tipo()
+ {
+ return $this->belongsTo(TipoValorCierre::class, 'tipo')->findOne();
+ }
+}
diff --git a/src/old/Venta/Venta.php b/src/old/Venta/Venta.php
new file mode 100644
index 0000000..549911a
--- /dev/null
+++ b/src/old/Venta/Venta.php
@@ -0,0 +1,515 @@
+belongs_to(Propietario::class, 'propietario', 'rut')->findOne();
+ }
+ public function propiedad()
+ {
+ return $this->belongs_to(Propiedad::class, 'propiedad')->findOne();
+ }
+ public function bonoPie()
+ {
+ $bono = $this->belongs_to(BonoPie::class, 'bono_pie');
+ if ($bono) {
+ return $bono->findOne();
+ }
+ return null;
+ }
+ public function pie()
+ {
+ $pie = $this->belongs_to(Pie::class, 'pie');
+ if ($pie) {
+ return $pie->findOne();
+ }
+ return null;
+ }
+ public function entrega()
+ {
+ if ($this->entrega != '0') {
+ return $this->belongs_to(Entrega::class, 'entrega')->findOne();
+ }
+ return null;
+ }
+ public function fecha()
+ {
+ return Carbon::parse($this->fecha, new \DateTimeZone(config('app.timezone')));
+ }
+ public function proyecto()
+ {
+ return $this->propiedad()->unidad()->proyecto();
+ }
+ public function unidad()
+ {
+ return $this->propiedad()->unidad();
+ }
+ public function agente()
+ {
+ $agente = $this->belongs_to(ProyectoAgente::class, 'agente');
+ if ($agente) {
+ return $agente->findOne();
+ }
+ return null;
+ }
+ public function comision()
+ {
+ if (!isset($this->comision)) {
+ $pa = $this->agente();
+ if ($pa and $pa->agente()->tipo == 19) {
+ $this->comision = $pa->comision / 100;
+ } else {
+ $this->comision = 0;
+ }
+ }
+ return $this->comision;
+ }
+ public function valorComision()
+ {
+ $bono_pie = $this->bonoPie();
+ if ($this->bono_pie != 0) {
+ $bono_pie = $bono_pie->pago()->valor('ufs');
+ } else {
+ $bono_pie = 0;
+ }
+ return ($this->valor_uf - $bono_pie) * $this->comision();
+ }
+ protected $superficie_departamentos;
+ public function superficie() {
+ if ($this->superficie_departamentos == null) {
+ $this->superficie_departamentos = array_reduce($this->propiedad()->departamentos(), function($sum, $item) {
+ return $sum + $item->m2();
+ });
+ }
+ return $this->superficie_departamentos;
+ }
+ protected $valor_departamentos;
+ public function valorDepartamentos() {
+ if ($this->valor_departamentos == null) {
+ $fecha = $this->fecha();
+ $this->valor_departamentos = array_reduce($this->propiedad()->departamentos(), function($sum, $item) use ($fecha) {
+ return $sum + $item->precio($fecha)->valor;
+ });
+ }
+ return $this->valor_departamentos;
+ }
+ protected $valor_unidades;
+ public function valorUnidades() {
+ if ($this->valor_unidades == null) {
+ $fecha = $this->fecha();
+ $this->valor_unidades = array_reduce($this->propiedad()->unidades(), function($sum, $item) use ($fecha) {
+ return $sum + $item->unidad()->precio($fecha)->valor;
+ });
+ }
+ return $this->valor_unidades;
+ }
+ public function valorEstacionamientos()
+ {
+ $estacionamientos = $this->propiedad()->estacionamientos();
+ $sum = 0;
+ foreach ($estacionamientos as $estacionamiento) {
+ $sum += $estacionamiento->precio($this->fecha())->valor;
+ }
+ return $sum;
+ }
+ public function valorBodegas()
+ {
+ $bodegas = $this->propiedad()->bodegas();
+ $sum = 0;
+ foreach ($bodegas as $bodega) {
+ $sum += $bodega->precio($this->fecha())->valor;
+ }
+ return $sum;
+ }
+ public function valorEstacionamientosYBodegas()
+ {
+ return $this->valorEstacionamientos() + $this->valorBodegas();
+ }
+ public function valorCorredora()
+ {
+ if ($this->valor_corredora == null) {
+ $bono_pie = $this->bonoPie();
+ if ($this->bono_pie != 0) {
+ $bono_pie = $bono_pie->pago()->valor('ufs');
+ } else {
+ $bono_pie = 0;
+ }
+ $promos = 0;
+ $ps = $this->promociones();
+ if (count($ps) > 0) {
+ foreach ($ps as $promo) {
+ $promos += $promo->valor;
+ }
+ }
+ $this->valor_corredora = $this->valor_uf - $bono_pie - $promos;
+ }
+ return $this->valor_corredora;
+ }
+ public function valorFinal()
+ {
+ if (!isset($this->valor_neto)) {
+ $comision = $this->valorComision();
+ $bono_pie = $this->bonoPie();
+ if ($this->bono_pie != 0) {
+ $bono_pie = $bono_pie->pago()->valor('ufs');
+ } else {
+ $bono_pie = 0;
+ }
+ $ests = $this->valorEstacionamientos();
+ $bods = $this->valorBodegas();
+ $promos = 0;
+ $ps = $this->promociones();
+ if (count($ps) > 0) {
+ foreach ($ps as $promo) {
+ $promos += $promo->valor;
+ }
+ }
+ $this->valor_neto = $this->valor_uf - $bono_pie - $comision - $ests - $bods - $promos;
+ }
+ return $this->valor_neto;
+ }
+ public function uf_m2()
+ {
+ $m2 = array_reduce($this->propiedad()->departamentos(), function($sum, $item) {
+ return $sum + $item->m2();
+ });
+ return $this->valorFinal() / $m2;
+ }
+ public function escritura()
+ {
+ $escritura = $this->belongs_to(Escritura::class, 'escritura');
+ if ($escritura) {
+ return $escritura->findOne();
+ }
+ return null;
+ }
+ public function credito()
+ {
+ $credito = $this->belongs_to(Credito::class, 'credito');
+ if ($credito) {
+ return $credito->findOne();
+ }
+ return null;
+ }
+ public function comentarios()
+ {
+ return $this->has_many(Comentario::class, 'venta')->findMany();
+ }
+ public function subsidio()
+ {
+ $subsidio = $this->belongs_to(Subsidio::class, 'subsidio');
+ if ($subsidio) {
+ return $subsidio->findOne();
+ }
+ return null;
+ }
+
+ public function resciliacion()
+ {
+ $res = $this->belongs_to(Pago::class, 'resciliacion');
+ if ($res) {
+ return $res->findOne();
+ }
+ return null;
+ }
+ public function postventas()
+ {
+ $postventas = $this->has_many(\Incoviba\nuevo\Venta\Postventa::class, 'venta_id');
+ if ($postventas) {
+ return $postventas->findMany();
+ }
+ return null;
+ }
+ public function promociones()
+ {
+ if ($this->promociones == null) {
+ $pvs = model(PromocionVenta::class)->where('venta', $this->id)->findMany();
+ $this->promociones = $pvs;
+ }
+ return $this->promociones;
+ }
+ public function devolucion()
+ {
+ $devolucion = $this->belongsTo(Pago::class, 'devolucion');
+ if ($devolucion) {
+ return $devolucion->findOne();
+ }
+ return null;
+ }
+ public function anticipo($tipo = 'ufs')
+ {
+ if (!isset($this->anticipo[$tipo])) {
+ $anticipo = 0;
+ if ($this->pie != 0) {
+ if ($tipo == 'ufs') {
+ $anticipo += $this->pieReajustado($tipo);
+ } else {
+ $anticipo += $this->pie()->valorPagado($tipo);
+ }
+ if ($this->pie()->reajuste != 0) {
+ $anticipo += $this->pie()->reajuste()->valor($tipo);
+ }
+ }
+ if ($this->escritura != 0) {
+ $anticipo += $this->escritura()->pago()->valor($tipo);
+ }
+ if ($this->saldo('ufs') > 0) {
+ $anticipo -= $this->saldo($tipo);
+ }
+ $this->anticipo[$tipo] = $anticipo;
+ }
+
+ return $this->anticipo[$tipo];
+ }
+ public function saldo($tipo = 'ufs')
+ {
+ if (!isset($this->saldo[$tipo])) {
+ if ($tipo == 'pesos') {
+ $this->saldo[$tipo] = $this->saldo() * $this->uf();
+ return $this->saldo[$tipo];
+ }
+ $saldo = $this->valor($tipo);
+ if ($this->bono_pie != 0) {
+ $saldo -= $this->bonoPie()->pago()->valor($tipo);
+ }
+ if ($this->pie != 0) {
+ $saldo -= $this->pie()->valorPagado($tipo);
+ if ($this->pie()->reajuste != 0) {
+ $saldo -= $this->pie()->reajuste()->valor($tipo);
+ }
+ }
+ if ($this->escritura != 0) {
+ $saldo -= $this->escritura()->pago()->valor($tipo);
+ }
+ if ($this->subsidio != 0) {
+ $saldo -= $this->subsidio()->total($tipo);
+ }
+ if ($this->credito != 0) {
+ $saldo -= $this->credito()->pago()->valor($tipo);
+ }
+ if ($this->devolucion) {
+ $saldo += $this->devolucion()->valor($tipo);
+ }
+ if ($this->resciliacion) {
+ $saldo += $this->resciliacion()->valor($tipo);
+ }
+ $this->saldo[$tipo] = -$saldo;
+ }
+
+ return $this->saldo[$tipo];
+ }
+ public function valor($tipo = 'ufs')
+ {
+ if ($tipo == 'ufs') {
+ return $this->valor_uf;
+ }
+ return $this->valor_uf * $this->uf();
+ }
+ protected $valores;
+ public function valorPagado($tipo = 'ufs')
+ {
+ if ($this->valores == null or !isset($this->valores->pagado->ufs)) {
+ $valores = [];
+ if (isset($this->valores)) {
+ $valores = (array) $valores;
+ }
+ $valores['pagado'] = (object) ['ufs' => 0, 'pesos' => 0];
+ if ($this->pie()) {
+ $valores['pagado']->ufs = $this->pie()->valorPagado();
+ $valores['pagado']->pesos = $this->pie()->valorPagado('pesos');
+ }
+ $this->valores = (object) $valores;
+ }
+ return $this->valores->pagado->{$tipo};
+ }
+ public function valorAbonado($tipo = 'ufs')
+ {
+ if ($this->valores == null or !isset($this->valores->abonado->{$tipo})) {
+ $valores = [];
+ if (isset($this->valores)) {
+ $valores = (array) $valores;
+ }
+ $valores['abonado'] = (object) ['ufs' => 0, 'pesos' => 0];
+ if ($this->pie()) {
+ $valores['abonado']->ufs = $this->pie()->valorAbonado();
+ $valores['abonado']->pesos = $this->pie()->valorAbonado('pesos');
+ }
+ $this->valores = (object) $valores;
+ }
+ return $this->valores->abonado->{$tipo};
+ }
+ public function pagado($tipo = 'ufs')
+ {
+ if (!isset($this->pagado[$tipo])) {
+ if (abs($this->saldo()) / $this->valor() > 0.01 or $tipo == 'pesos') {
+ $total = 0;
+ $total += $this->anticipo($tipo);
+
+ if ($this->subsidio != 0) {
+ $total += $this->subsidio()->total($tipo);
+ }
+ if ($this->credito != 0) {
+ $total += $this->credito()->pago()->valor($tipo);
+ }
+ if ($this->devolucion) {
+ $total -= $this->devolucion()->valor($tipo);
+ }
+ if ($this->resciliacion) {
+ $total -= $this->resciliacion()->valor($tipo);
+ }
+
+ $this->pagado[$tipo] = $total;
+ } else {
+ $this->pagado[$tipo] = $this->valor($tipo);
+ }
+ }
+ return $this->pagado[$tipo];
+ }
+ public function pieReajustado($tipo = 'ufs')
+ {
+ if (abs($this->saldo()) / $this->valor() > 0.01) {
+ return $this->pie()->valorPagado($tipo);
+ }
+ $valor = $this->pie()->valorPagado($tipo) - $this->saldo($tipo);
+ return $valor;
+ }
+ public function uf()
+ {
+ if ($this->uf == null) {
+ $f = $this->fecha();
+ $uf = uf($f);
+ if ($uf == null) {
+ return 1;
+ }
+ $this->uf = $uf->uf->value;
+ }
+
+ return $this->uf;
+ }
+ public function pagos($estado = 0)
+ {
+ $results = [];
+ if ($this->pie != 0) {
+ $results = array_merge($results, $this->pie()->pagos($estado));
+ }
+ if ($this->escritura != 0 and $this->escritura()->pago() and $this->escritura()->pago()->estado()->estado == $estado) {
+ $results []= $this->escritura()->pago();
+ }
+ if ($this->credito != 0 and $this->credito()->pago()->estado()->estado == $estado) {
+ $results []= $this->credito()->pago();
+ }
+ if ($this->subsidio != 0 and $this->subsidio()->pago()->estado()->estado == $estado) {
+ $results []= $this->subsidio()->pago();
+ }
+
+ usort($results, function($a, $b) {
+ return $a->estado()->fecha()->diffInDays($b->estado()->fecha(), false);
+ });
+ return $results;
+ }
+ public function new()
+ {
+ parent::save();
+ $tipo = model(TipoEstadoVenta::class)->where('descripcion', 'vigente')->findOne();
+ $data = [
+ 'venta' => $this->id,
+ 'estado' => $tipo->id,
+ 'fecha' => $this->fecha
+ ];
+ $estado = model(EstadoVenta::class)->create($data);
+ $estado->save();
+ }
+ public function estados()
+ {
+ return $this->hasMany(EstadoVenta::class, 'venta')->findMany();
+ }
+ public function estado($estado = null)
+ {
+ if ($estado == null) {
+ return model(EstadoVenta::class)
+ ->select('estado_venta.*')
+ ->rawJoin('JOIN (SELECT venta, MAX(id) AS id FROM estado_venta GROUP BY venta)', ['estado_venta.id', '=', 'e0.id'], 'e0')
+ ->where('estado_venta.venta', $this->id)
+ ->findOne();
+ }
+ return model(EstadoVenta::class)
+ ->select('estado_venta.*')
+ ->join('tipo_estado_venta', ['tipo_estado_venta.id', '=', 'estado_venta.estado'])
+ ->where('estado_venta.venta', $this->id)
+ ->where('tipo_estado_venta.descripcion', $estado)
+ ->orderByDesc('estado_venta.fecha')
+ ->findOne();
+ }
+ public function firmar(Carbon $fecha)
+ {
+ $estado = $this->estado();
+ if ($estado->tipo()->descripcion == 'firmado por inmobiliaria') {
+ return true;
+ }
+ $tipo = model(TipoEstadoVenta::class)->where('descripcion', 'firmado por inmobiliaria')->findOne();
+ $data = [
+ 'venta' => $this->id,
+ 'estado' => $tipo->id,
+ 'fecha' => $fecha->format('Y-m-d')
+ ];
+ $estado = model(EstadoVenta::class)->create($data)->save();
+ return true;
+ }
+ public function archivar(Carbon $fecha)
+ {
+ $estado = $this->estado();
+ if ($estado->estado()->tipo()->descripcion == 'archivado') {
+ return true;
+ }
+ $tipo = model(TipoEstadoVenta::class)->where('descripcion', 'archivado')->findOne();
+ $data = [
+ 'venta' => $this->id,
+ 'estado' => $tipo->id,
+ 'fecha' => $fecha->format('Y-m-d')
+ ];
+ $estado = model(EstadoVenta::class)->create($data)->save();
+ return true;
+ }
+}
+?>