From 90754413a04134aa0a34be25219eec0929032a3a Mon Sep 17 00:00:00 2001 From: Aldarien Date: Thu, 25 Mar 2021 21:10:44 -0300 Subject: [PATCH] App control --- app/Alias/Excel/Style/Mes.php | 18 + app/Alias/Format.php | 12 + app/Alias/Model.php | 87 +++ app/Alias/NewEstado.php | 20 + app/Alias/NewModel.php | 9 + app/Alias/NewTipo.php | 15 + app/Alias/OldModel.php | 8 + app/Alias/PHPExcel.php | 155 ++++ app/Contract/Auth.php | 27 + app/Contract/Route.php | 27 + app/Controller/API/Unidades.php | 44 ++ app/Controller/Admin.php | 233 ++++++ app/Controller/Ajax.php | 215 ++++++ app/Controller/Auth.php | 56 ++ app/Controller/Bonos.php | 57 ++ app/Controller/Buscar.php | 340 +++++++++ app/Controller/Cierres.php | 428 +++++++++++ app/Controller/Comentarios.php | 39 + app/Controller/Contabilidad.php | 100 +++ app/Controller/Creditos.php | 207 ++++++ app/Controller/Cuotas.php | 230 ++++++ app/Controller/Devoluciones.php | 19 + app/Controller/Escrituras.php | 212 ++++++ app/Controller/FormaPago.php | 98 +++ app/Controller/Informes.php | 950 ++++++++++++++++++++++++ app/Controller/Informes.php.save | 901 ++++++++++++++++++++++ app/Controller/Inmobiliarias.php | 74 ++ app/Controller/Operadores.php | 47 ++ app/Controller/Other.php | 71 ++ app/Controller/Pagares.php | 271 +++++++ app/Controller/Pagos.php | 358 +++++++++ app/Controller/Pies.php | 104 +++ app/Controller/Postventas.php | 69 ++ app/Controller/Precios.php | 177 +++++ app/Controller/Propietarios.php | 129 ++++ app/Controller/ProyectoTipoUnidades.php | 77 ++ app/Controller/Proyectos.php | 327 ++++++++ app/Controller/Reajustes.php | 90 +++ app/Controller/Registros.php | 39 + app/Controller/Subsidios.php | 184 +++++ app/Controller/Temas.php | 111 +++ app/Controller/Unidades.php | 126 ++++ app/Controller/UnidadesBloqueadas.php | 83 +++ app/Controller/Ventas.php | 623 ++++++++++++++++ app/Definition/Controller.php | 31 + app/Definition/hasEstado.php | 38 + app/Definition/hasRUT.php | 20 + app/Exception/PropertyNotFound.php | 16 + app/Helper/Color.php | 169 +++++ app/Helper/Line.php | 61 ++ app/Helper/functions.php | 140 ++++ app/Service/Auth.php | 163 ++++ app/Service/Borrador.php | 118 +++ app/Service/DBToModel.php | 158 ++++ app/Service/Factory.php | 204 +++++ app/Service/Informador.php | 463 ++++++++++++ app/Service/Register.php | 34 + app/Service/Replacer.php | 127 ++++ app/Service/Route.php | 131 ++++ 59 files changed, 9340 insertions(+) create mode 100644 app/Alias/Excel/Style/Mes.php create mode 100644 app/Alias/Format.php create mode 100644 app/Alias/Model.php create mode 100644 app/Alias/NewEstado.php create mode 100644 app/Alias/NewModel.php create mode 100644 app/Alias/NewTipo.php create mode 100644 app/Alias/OldModel.php create mode 100644 app/Alias/PHPExcel.php create mode 100644 app/Contract/Auth.php create mode 100644 app/Contract/Route.php create mode 100644 app/Controller/API/Unidades.php create mode 100644 app/Controller/Admin.php create mode 100644 app/Controller/Ajax.php create mode 100644 app/Controller/Auth.php create mode 100644 app/Controller/Bonos.php create mode 100644 app/Controller/Buscar.php create mode 100644 app/Controller/Cierres.php create mode 100644 app/Controller/Comentarios.php create mode 100644 app/Controller/Contabilidad.php create mode 100644 app/Controller/Creditos.php create mode 100644 app/Controller/Cuotas.php create mode 100644 app/Controller/Devoluciones.php create mode 100644 app/Controller/Escrituras.php create mode 100644 app/Controller/FormaPago.php create mode 100644 app/Controller/Informes.php create mode 100644 app/Controller/Informes.php.save create mode 100644 app/Controller/Inmobiliarias.php create mode 100644 app/Controller/Operadores.php create mode 100644 app/Controller/Other.php create mode 100644 app/Controller/Pagares.php create mode 100644 app/Controller/Pagos.php create mode 100644 app/Controller/Pies.php create mode 100644 app/Controller/Postventas.php create mode 100644 app/Controller/Precios.php create mode 100644 app/Controller/Propietarios.php create mode 100644 app/Controller/ProyectoTipoUnidades.php create mode 100644 app/Controller/Proyectos.php create mode 100644 app/Controller/Reajustes.php create mode 100644 app/Controller/Registros.php create mode 100644 app/Controller/Subsidios.php create mode 100644 app/Controller/Temas.php create mode 100644 app/Controller/Unidades.php create mode 100644 app/Controller/UnidadesBloqueadas.php create mode 100644 app/Controller/Ventas.php create mode 100644 app/Definition/Controller.php create mode 100644 app/Definition/hasEstado.php create mode 100644 app/Definition/hasRUT.php create mode 100644 app/Exception/PropertyNotFound.php create mode 100644 app/Helper/Color.php create mode 100644 app/Helper/Line.php create mode 100644 app/Helper/functions.php create mode 100644 app/Service/Auth.php create mode 100644 app/Service/Borrador.php create mode 100644 app/Service/DBToModel.php create mode 100644 app/Service/Factory.php create mode 100644 app/Service/Informador.php create mode 100644 app/Service/Register.php create mode 100644 app/Service/Replacer.php create mode 100644 app/Service/Route.php diff --git a/app/Alias/Excel/Style/Mes.php b/app/Alias/Excel/Style/Mes.php new file mode 100644 index 0000000..368246b --- /dev/null +++ b/app/Alias/Excel/Style/Mes.php @@ -0,0 +1,18 @@ +setNumFormat('mmm-YY'); + $format->setAlign('center'); + } +} diff --git a/app/Alias/Format.php b/app/Alias/Format.php new file mode 100644 index 0000000..f2067aa --- /dev/null +++ b/app/Alias/Format.php @@ -0,0 +1,12 @@ + \ No newline at end of file diff --git a/app/Alias/Model.php b/app/Alias/Model.php new file mode 100644 index 0000000..9f8f579 --- /dev/null +++ b/app/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/app/Alias/NewEstado.php b/app/Alias/NewEstado.php new file mode 100644 index 0000000..4bf9089 --- /dev/null +++ b/app/Alias/NewEstado.php @@ -0,0 +1,20 @@ +fecha, config('app.timezone')); + } +} +?> \ No newline at end of file diff --git a/app/Alias/NewModel.php b/app/Alias/NewModel.php new file mode 100644 index 0000000..1c513b4 --- /dev/null +++ b/app/Alias/NewModel.php @@ -0,0 +1,9 @@ + \ No newline at end of file diff --git a/app/Alias/NewTipo.php b/app/Alias/NewTipo.php new file mode 100644 index 0000000..b5fa3fb --- /dev/null +++ b/app/Alias/NewTipo.php @@ -0,0 +1,15 @@ + \ No newline at end of file diff --git a/app/Alias/OldModel.php b/app/Alias/OldModel.php new file mode 100644 index 0000000..b3f9730 --- /dev/null +++ b/app/Alias/OldModel.php @@ -0,0 +1,8 @@ + diff --git a/app/Alias/PHPExcel.php b/app/Alias/PHPExcel.php new file mode 100644 index 0000000..de0ac75 --- /dev/null +++ b/app/Alias/PHPExcel.php @@ -0,0 +1,155 @@ +name = $name; + $this->filename = $filename; + } + public function addColumns($fields) + { + $columns = []; + foreach ($fields as $i => $field) { + if (is_object($field)) { + if (isset($field->style)) { + $style = $this->getExcelStyle($field->style); + } else { + $style = $this->getExcelStyle(); + } + $column = new ExcelHelper\Column($field->name, $field->name, 10, $style); + } elseif (is_array($field)) { + if (isset($field['style'])) { + $style = $this->getExcelStyle($field['style']); + } else { + $style = $this->getExcelStyle(); + } + $column = new ExcelHelper\Column($field['name'], $field['name'], 10, $style); + } else { + $style = $this->getExcelStyle(); + $column = new ExcelHelper\Column($field, $field, 10, $style); + } + $columns []= $column; + } + $collection = new ExcelHelper\ColumnCollection($columns); + $this->columns = $collection; + } + protected function getExcelStyle($style = 'text') + { + switch (strtolower($style)) { + case 'date': + return new ExcelHelper\CellStyle\Date(); + case 'mes': + return new Excel\Style\Mes(); + case 'currency': + case 'amount': + return new ExcelHelper\CellStyle\Amount(); + case 'number': + case 'integer': + return new ExcelHelper\CellStyle\Integer(); + case 'percent': + case 'percentage': + return new ExcelHelper\CellStyle\Percentage(); + case 'text': + case 'string': + default: + return new ExcelHelper\CellStyle\Text(); + } + } + public function addData($data) + { + if ($this->data == null) { + $this->data = []; + } + $this->data = array_merge($data); + } + public function addRow($rowData) + { + if ($this->data == null) { + $this->data = []; + } + $this->data []= $rowData; + } + public function addTotals($totals) + { + $columns = (array) $this->columns; + $columns = array_pop($columns); + $ts = []; + foreach ($columns as $column) { + $col = $column->getHeading(); + if (isset($totals[$col])) { + $ts[$col] = $this->getTotal($col, $totals[$col]); + continue; + } + $ts[$col] = ''; + } + $this->data []= $ts; + } + protected function getTotal($col, $aggr) + { + $col_num = $this->getColNumber($col); + $col = $this->getColName($col_num); + switch(strtolower($aggr)) { + case 'sum': + $num = 109; + break; + case 'count': + $num = 102; + break; + case 'counta': + $num = 103; + break; + default: + $num = 0; + } + if ($num > 0) { + $end = count($this->data) + 2; + $str = "=SUBTOTAL({$num};{$col}3:{$col}{$end})"; + return $str; + } + return $aggr; + } + protected function getColNumber($col) + { + $columns = (array) $this->columns; + $columns = array_keys(array_pop($columns)); + return array_search($col, $columns); + } + protected function getColName($col_num) + { + $cols = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + $N = strlen($cols); + $name = ''; + if ($col_num > $N) { + $name .= $cols[floor($col_num / $N)]; + $col_num = $N * ($col_num / $N - floor($col_num / $N)); + } + $name .= $cols[$col_num]; + return $name; + } + public function informe() + { + header("Content-Type: application/octet-stream; charset=utf-8"); + header('Content-Transfer-Encoding: binary'); + header('Content-Disposition: attachment; filename="' . $this->filename . '"'); + header('Cache-Control: max-age=0'); + + $pE = new ExcelHelper\TableWorkbook('php://output'); + $ws = $pE->addWorksheet($this->name); + + $table = new ExcelHelper\Table($ws, 0, 0, $this->name, new \ArrayIterator($this->data)); + $table->setColumnCollection($this->columns); + + $pE->writeTable($table); + + $pE->close(); + } +} diff --git a/app/Contract/Auth.php b/app/Contract/Auth.php new file mode 100644 index 0000000..fb2e3b6 --- /dev/null +++ b/app/Contract/Auth.php @@ -0,0 +1,27 @@ + \ No newline at end of file diff --git a/app/Contract/Route.php b/app/Contract/Route.php new file mode 100644 index 0000000..fd4a84c --- /dev/null +++ b/app/Contract/Route.php @@ -0,0 +1,27 @@ + \ No newline at end of file diff --git a/app/Controller/API/Unidades.php b/app/Controller/API/Unidades.php new file mode 100644 index 0000000..d136445 --- /dev/null +++ b/app/Controller/API/Unidades.php @@ -0,0 +1,44 @@ +findOne($id_proyecto); + if (!$proyecto) { + throw new \InvalidArgumentException('Proyecto identificado por ' . $id_proyecto . ' no existe.'); + } + $unidades = $proyecto->unidades($id_tipo); + $unidades = array_filter($unidades, function($item) { + return !$item->isReservada(); + }); + $unidades = array_map(function($item) { + return $item->asArray(); + }, $unidades); + usort($unidades, function($a, $b) { + $ap = strpos($a['descripcion'], ' '); + $ad = $a['descripcion']; + if ($ap != false) { + $ad = substr($ad, 0, $ap); + } + $bd = $b['descripcion']; + $bp = strpos($b['descripcion'], ' '); + if ($bp != false) { + $bd = substr($bd, 0, $bp); + } + return strcmp( + str_pad($ad, 4, '0', \STR_PAD_LEFT), + str_pad($bd, 4, '0', \STR_PAD_LEFT) + ); + }); + $output = array_values($unidades); + return json_encode($output); + } +} diff --git a/app/Controller/Admin.php b/app/Controller/Admin.php new file mode 100644 index 0000000..137057c --- /dev/null +++ b/app/Controller/Admin.php @@ -0,0 +1,233 @@ +list(); + } + public static function listNamespaces() + { + $base = [ + 'Common', + 'Inmobiliaria', + 'Proyecto', + 'Venta' + ]; + $nss = [ + 'Incoviba' => [ + 'old' => $base, + 'new' => $base + ] + ]; + + echo json_encode(['namespaces' => self::collapseMultiArray($nss)]); + } + protected static function collapseMultiArray($array, $level = '') + { + $output = []; + foreach ($array as $key => $subarray) { + if (is_array($subarray)) { + $output = array_merge($output, self::collapseMultiArray($subarray, $level . '\\' . $key)); + } else { + $output []= $level . '\\' . $subarray; + } + } + + return $output; + } + public static function createModel() + { + $db = post('database'); + $ns = post('namespace'); + $table = post('table'); + + $modeler = new DBToModel($db); + echo $modeler->create($ns, $table); + } + public static function list_roles() + { + $roles = \Model::factory(\Incoviba\common\Role::class)->findMany(); + echo view('admin.roles.list', compact('roles')); + } + public static function add_role() + { + echo view('admin.roles.add'); + } + public static function do_add_role() + { + $role = \Model::factory(\Incoviba\common\Role::class)->where('description', post('description'))->findOne(); + if ($role === false) { + $role = \Model::factory(\Incoviba\common\Role::class)->create(['description' => post('description')]); + $role->save(); + } + header('Location: ' . nUrl('admin', 'add_role')); + } + public static function role() + { + $role = \Model::factory(\Incoviba\common\Role::class)->findOne(get('role')); + $actions = model(Action::class)->orderByAsc('description')->findMany(); + $permissions = []; + foreach ($actions as $action) { + $permissions []= (object) ['description' => $action->description, 'status' => false, 'inherited' => false]; + } + array_walk($permissions, function(&$el, $i, $role) { + if ($role->checkAccess($el->description)) { + $el->status = true; + if ($role->isInherited($el->description)) { + $el->inherited = true; + } + } + }, $role); + echo view('admin.roles.show', compact('role', 'permissions')); + } + public static function add_role_permissions() + { + $role = \Model::factory(\Incoviba\common\Role::class)->findOne(get('role')); + $locations = \Model::factory(\Incoviba\common\Location::class)->findMany(); + $actions = model(\Incoviba\common\Action::class)->findMany(); + echo view('admin.roles.add_permissions', compact('role', 'locations', 'actions')); + } + public static function do_add_role_permissions() + { + $role = \Model::factory(\Incoviba\common\Role::class)->findOne(get('role')); + $actions = model(\Incoviba\common\Action::class)->findMany(); + foreach ($actions as $action) { + $p = \Model::factory(\Incoviba\common\Permission::class)->where('type', 2)->where('ext_id', $role->id)->where('action_id', $action->id)->findOne(); + if (array_search($action->id, post('allowed'))) { + if (!$p) { + $data = [ + 'type' => 2, + 'ext_id' => $role->id, + 'action_id' => $action->id + ]; + $p = model(\Incoviba\common\Permission::class)->create($data); + } + $p->status = 1; + } else { + if ($p !== false) { + $p->status = 0; + } + } + if ($p !== false) { + $p->save(); + } + } + header('Location: ' . nUrl('admin', 'role', ['role' => $role->id])); + } + public static function list_users() + { + $users = \Model::factory(\Incoviba\common\User::class)->orderByAsc('name')->findMany(); + echo view('admin.users.list', compact('users')); + } + public static function add_user() + { + echo view('admin.users.add'); + } + public static function do_add_user() + { + $user = \Model::factory(\Incoviba\common\User::class)->where('name', post('name'))->findOne(); + if ($user === false) { + $user = \Model::factory(\Incoviba\common\User::class)->create(); + $user->name = post('name'); + $user->password(post('password')); + + $user->save(); + } + header('Location: ' . url('', ['p' => 'admin', 'a' => 'add_user'])); + } + public static function user() + { + $user = \Model::factory(\Incoviba\common\User::class)->findOne(get('user')); + echo view('admin.users.show', compact('user')); + } + public static function add_user_role() + { + if (get('user') !== false) { + $user = \Model::factory(\Incoviba\common\User::class)->findOne(get('user')); + $roles = \Model::factory(\Incoviba\common\Role::class)->findMany(); + return view('admin.users.add_role', compact('user', 'roles')); + } elseif (get('role') !== false) { + $role = \Model::factory(\Incoviba\common\Role::class)->findOne(get('role')); + $users = \Model::factory(\Incoviba\common\User::class)->findMany(); + return view('admin.roles.add_users', compact('users', 'role')); + } + } + public static function do_add_user_role() + { + if (get('user') !== false) { + $user = \Model::factory(\Incoviba\common\User::class)->findOne(get('user')); + foreach (post('role') as $r_id) { + $role = \Model::factory(\Incoviba\common\Role::class)->findOne($r_id); + + $usrRl = \Model::factory(\Incoviba\common\UserRole::class)->where('user', $user->id)->where('role', $role->id)->findOne(); + if ($usrRl === false) { + $usrRl = \Model::factory(\Incoviba\common\UserRole::class)->create(['user' => $user->id, 'role' => $role->id]); + $usrRl->save(); + } + } + header('Location: ' . url('', ['p' => 'admin', 'a' => 'user', 'user' => $user->id])); + } elseif (get('role') !== false) { + $role = \Model::factory(\Incoviba\common\Role::class)->findOne(get('role')); + foreach (post('users') as $u_id) { + $user = \Model::factory(\Incoviba\common\User::class)->findOne($u_id); + + $usrRl = \Model::factory(\Incoviba\common\UserRole::class)->where('user', $user->id)->where('role', $role->id)->findOne(); + if ($usrRl === false) { + $usrRl = \Model::factory(\Incoviba\common\UserRole::class)->create(['user' => $user->id, 'role' => $role->id]); + $usrRl->save(); + } + } + header('Location: ' . url('', ['p' => 'admin', 'a' => 'role', 'role' => $role->id])); + } + } + public static function remove_user_role() + { + $q = "DELETE FROM user_roles WHERE user = ? AND role = ?"; + $st = \ORM::getDb()->prepare($q); + $st->execute([get('user'), get('role')]); + header('Location: ' . nUrl('admin')); + } + public static function delete_user() + { + $q = "DELETE FROM user_roles WHERE user = ?"; + $st = \ORM::getDb()->prepare($q); + $st->execute([get('user')]); + $q = "DELETE FROM logins WHERE user = ?"; + $st = \ORM::getDb()->prepare($q); + $st->execute([get('user')]); + $q = "DELETE FROM permissions WHERE type = 1 AND ext_id = ?"; + $st = \ORM::getDb()->prepare($q); + $st->execute([get('user')]); + $user = \model(\Incoviba\common\User::class)->findOne(get('user')); + $user->delete(); + header('Location: ' . nUrl('admin', 'list_users')); + } + public static function reset_user() + { + $user = model(\Incoviba\common\User::class)->findOne(get('user')); + $user->password('123456'); + $user->save(); + header('Location: ' . nUrl('admin', 'user', ['user' => $user->id])); + } +} +?> diff --git a/app/Controller/Ajax.php b/app/Controller/Ajax.php new file mode 100644 index 0000000..912c979 --- /dev/null +++ b/app/Controller/Ajax.php @@ -0,0 +1,215 @@ +whereNotEqual('nombre', '')->order_by_asc('nombre')->findMany(); + foreach ($bancos as &$banco) { + $banco = $banco->as_array('nombre')['nombre']; + } + return json_encode($bancos); + } + protected static function buscarBanco() + { + $q = get('q'); + if ($q == null) { + $q = get('query'); + if ($q == null) { + return ''; + } + } + $bancos = \Model::factory(\Incoviba\old\Common\Banco::class)->whereLike('nombre', '%' . $q . '%')->order_by_asc('nombre')->findMany(); + foreach ($bancos as &$banco) { + $banco = $banco->as_array('nombre')['nombre']; + } + return json_encode($bancos); + } + public static function comunas() + { + $id = post('region'); + $comunas = \Model::factory(\Incoviba\old\Common\Comuna::class) + ->select('comuna.*') + ->join('provincia', ['provincia.id', '=', 'comuna.provincia']) + ->where('provincia.region', $id) + ->order_by_asc('comuna.descripcion') + ->findMany(); + + foreach ($comunas as &$comuna) { + $comuna = $comuna->as_array('id', 'descripcion'); + } + return json_encode($comunas); + } + public static function propietario() + { + $id = post('rut'); + $propietario = \Model::factory(\Incoviba\old\Venta\Propietario::class)->where('rut', $id)->findOne(); + if ($propietario) { + $propietario = $propietario->as_array(); + return json_encode($propietario); + } + return null; + } + public static function direccion() + { + $id = post('direccion'); + $direccion = \Model::factory(\Incoviba\old\Common\Direccion::class)->findOne($id); + $comuna = $direccion->comuna(); + $provincia = $comuna->provincia(); + $region = $provincia->region(); + $direccion = $direccion->as_array(); + $direccion['comuna'] = $comuna->as_array(); + $direccion['comuna']['provincia'] = $provincia->as_array(); + $direccion['comuna']['provincia']['region'] = $region->as_array(); + return json_encode($direccion); + } + public static function tipo_unidades() + { + $id = post('proyecto'); + $proyecto = \Model::factory(\Incoviba\old\Proyecto\Proyecto::class)->findOne($id); + $tipos = $proyecto->tipoUnidades(); + foreach ($tipos as &$tipo) { + $tipo = $tipo->as_array(); + } + return json_encode($tipos); + } + public static function unidades() + { + $id_proyecto = post('proyecto'); + $id_tipo = post('tipo'); + + $proyecto = model(\Incoviba\old\Proyecto\Proyecto::class)->findOne($id_proyecto); + $unidades = $proyecto->unidadesDisponibles($id_tipo); + foreach ($unidades as &$unidad) { + $tipologia = $unidad->tipologia(); + $unidad = $unidad->as_array(); + $unidad['tipologia'] = $tipologia->as_array(); + if ($tipologia->tipologia()) { + $unidad['tipologia']['tipologia'] = (array) $tipologia->tipologia(); + continue; + } + $unidad['tipologia']['tipologia'] = ['descripcion' => $tipologia->abreviacion]; + } + return json_encode($unidades); + } + public static function unidades_precios() + { + $proyecto = model(\Incoviba\old\Proyecto\Proyecto::class)->findOne(post('proyecto')); + $unidades = $proyecto->unidades(); + usort($unidades, function($a, $b) { + $t = $a->tipo - $b->tipo; + if ($t == 0) { + return (int) $a->descripcion - (int) $b->descripcion; + } + return $t; + }); + $output = []; + foreach ($unidades as $u) { + $info = [ + 'id' => $u->id, + 'abreviacion' => $u->abreviacion, + 'descripcion' => $u->descripcion, + 'valor' => '--' + ]; + if ($u->precio()) { + $info['valor'] = format('ufs', $u->precio()->valor, null, true); + } + $output []= $info; + } + return json_encode($output); + } + public static function operadores() + { + $id_proyecto = post('proyecto'); + $proyecto = \Model::factory(\Incoviba\old\Proyecto\Proyecto::class)->findOne($id_proyecto); + $operadores = $proyecto->operadores(); + foreach ($operadores as &$operador) { + $operador = [ + 'id' => $operador->id, + 'abreviacion' => $operador->abreviacion + ]; + } + return json_encode($operadores); + } + public static function promociones() + { + $id = post('proyecto'); + $proyecto = \Model::factory(\Incoviba\old\Proyecto\Proyecto::class)->findOne($id); + $promociones = $proyecto->promociones(); + foreach ($promociones as &$promocion) { + $promocion = $promocion->as_array(); + } + return json_encode($promociones); + } + public static function nombres() + { + $nss = model(Propietario::class)->select('nombres')->orderByAsc('nombres')->findMany(); + $nombres = []; + foreach ($nss as $n) { + $ns = explode(' ', $n->nombres); + foreach ($ns as $nombre) { + $nombres []= $nombre; + } + } + $nombres = array_values(array_unique($nombres)); + return json_encode($nombres); + } + public static function apellidos() + { + $aps = model(Propietario::class)->select('apellido_paterno')->orderByAsc('apellido_paterno')->findMany(); + $apellidos = []; + foreach ($aps as $ap) { + $apellidos []= $ap->apellido_paterno; + } + $aps = model(Propietario::class)->select('apellido_materno')->orderByAsc('apellido_materno')->findMany(); + foreach ($aps as $ap) { + $apellidos []= $ap->apellido_paterno; + } + $apellidos = array_values(array_unique($apellidos)); + sort($apellidos); + return json_encode($apellidos); + } + public static function calles() + { + $results = model(Direccion::class)->select('calle')->orderByAsc('calle')->findMany(); + $calles = []; + foreach ($results as $result) { + $calles []= $result->calle; + } + $calles = array_values(array_unique($calles)); + return json_encode($calles); + } + public static function inmobiliarias() + { + $q = post('rut'); + $inmobiliaria = model(Inmobiliaria::class)->findOne($q); + return json_encode($inmobiliaria->as_array()); + } +} +?> diff --git a/app/Controller/Auth.php b/app/Controller/Auth.php new file mode 100644 index 0000000..c7ca497 --- /dev/null +++ b/app/Controller/Auth.php @@ -0,0 +1,56 @@ + 'auth', 'a' => 'login'])); + } + } + public static function logout() + { + sAuth::logout(); + header('Location: .'); + } + public static function check_pass() + { + if (\password_verify(post('password'), sAuth::User()->password)) { + return 'OK'; + } + return 'KO'; + } + public static function change_pass() + { + return view('auth.change_pass'); + } + public static function do_change_pass() + { + if (\password_verify(post('old'), sAuth::User()->password)) { + if (post('new') == post('new2')) { + $user = sAuth::User(); + $user->password(post('new')); + $user->save(); + header('Location: .'); + die(); + } + } + header('Location: ' . url('', ['p' => 'auth', 'a' => 'change_pass'])); + } +} +?> diff --git a/app/Controller/Bonos.php b/app/Controller/Bonos.php new file mode 100644 index 0000000..837c3f0 --- /dev/null +++ b/app/Controller/Bonos.php @@ -0,0 +1,57 @@ +findOne($id_venta); + return view('ventas.bonos.add', compact('venta')); + } + public static function do_add() + { + $id_venta = get('venta'); + $venta = model(Venta::class)->findOne($id_venta); + if ($venta->bono_pie != 0) { + header('Location: ' . nUrl('ventas', 'show', ['venta' => $venta->id])); + return; + } + $uf = uf($venta->fecha()); + $valor = post('valor'); + $data = [ + 'fecha' => $venta->fecha, + 'valor' => $valor * $uf->uf->value, + 'tipo' => 8, + 'uf' => $uf->uf->value + ]; + $pago = model(Pago::class)->create($data); + $pago->save(); + $data = [ + 'valor' => $valor, + 'pago' => $pago->id + ]; + $bono = model(BonoPie::class)->create($data); + $bono->save(); + $venta->bono_pie = $bono->id; + $venta->save(); + header('Location: ' . nUrl('ventas', 'show', ['venta' => $venta->id])); + } + public static function edit() + { + $id_venta = get('venta'); + $venta = model(Venta::class)->findOne($id_venta); + return view('ventas.bonos.edit', compact('venta')); + } + public static function do_edit() + { + d(post()); + } +} diff --git a/app/Controller/Buscar.php b/app/Controller/Buscar.php new file mode 100644 index 0000000..ef62a9e --- /dev/null +++ b/app/Controller/Buscar.php @@ -0,0 +1,340 @@ + $results]); + } + protected static function getResults() + { + $q = get('q'); + if ($q == null) { + $q = get('query'); + } + $t = get('t'); + if ($t == null) { + $t = get('tipo'); + } + $t = urldecode($t); + if ($t == null) { + $t = 'cualquiera'; + } + + $results = null; + if ($q != null) { + $q = urldecode($q); + $results = self::buscar($q, $t); + } + return $results; + } + public static function buscar($query, $tipo) + { + $method = 'buscar' . str_replace(' ', '', ucwords($tipo)); + if (is_callable(['self', $method])) { + $results = self::$method(self::prepareQuery($query)); + $results = self::removeDuplicates($results); + $results = self::sort($results); + return $results; + } + return []; + } + protected static function prepareQuery($query) + { + $query = str_replace('"', '"', $query); + $data = explode(' ', $query); + $regex = "~(?=\\S)[^'\"\\s]*(?:'[^']*'[^'\"\\s]*|\"[^\"]*\"[^'\"\\s]*)*~"; + preg_match_all($regex, $query, $data); + $data = $data[0]; + foreach ($data as &$l) { + $l = str_replace('"', '', str_replace("'", '', $l)); + } + if (is_array($data) and count($data) == 1) { + $data = $data[0]; + } + return $data; + } + protected static function removeDuplicates($results) + { + $output = []; + foreach ($results as $result) { + if (array_search($result, $output) === false) { + $output []= $result; + } + } + return $output; + } + protected static function sort($results) + { + usort($results, function($a, $b) { + $py = strcmp($a->proyecto()->descripcion, $b->proyecto()->descripcion); + if ($py == 0) { + if (!method_exists($a, 'unidad') and !method_exists($b, 'unidad')) { + return $a->descripcion - $b->descripcion; + } + if (!method_exists($a, 'unidad')) { + return $a->descripcion - $b->unidad()->descripcion; + } + if (!method_exists($b, 'unidad')) { + return $a->unidad()->descripcion - $b->descripcion; + } + + $u = $a->unidad()->descripcion - $b->unidad()->descripcion; + if ($u == 0) { + return strcmp($a->propietario()->apellido_paterno, $b->propietario()->apellido_paterno); + } + return $u; + } + return $py; + }); + return $results; + } + protected static function buscarCualquiera($query) + { + $results = []; + foreach (self::$tipos as $tipo) { + if ($tipo == 'cualquiera') { + continue; + } + $method = 'buscar' . str_replace(' ', '', ucwords($tipo)); + + if (is_callable(['self', $method])) { + $results = array_merge($results, self::$method($query)); + } + } + return $results; + } + protected static function buscarDepartamento($query) + { + if (is_array($query)) { + $results = []; + foreach ($query as $segment) { + $results = array_merge($results, self::buscarDepartamento($segment)); + } + } else { + $results = \Model::factory(Venta::class) + ->select('venta.*') + ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad']) + ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal']) + ->whereLike('unidad.descripcion', '%' . $query . '%') + ->findMany(); + } + return $results; + } + protected static function buscarEstacionamiento($query) + { + if (is_array($query)) { + $results = []; + foreach ($query as $segment) { + $results = array_merge($results, self::buscarEstacionamiento($segment)); + } + } else { + $results = \Model::factory(Venta::class) + ->select('venta.*') + ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad']) + ->join('unidad', "`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('unidad.descripcion', $query) + ->findMany(); + } + return $results; + } + protected static function buscarBodega($query) + { + if (is_array($query)) { + $results = []; + foreach ($query as $segment) { + $results = array_merge($results, self::buscarBodega($segment)); + } + } else { + $results = \Model::factory(Venta::class) + ->select('venta.*') + ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad']) + ->join('unidad', "`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('unidad.descripcion', $query) + ->findMany(); + } + return $results; + } + protected static function buscarPropietario($query) + { + if (is_array($query)) { + $results = []; + foreach ($query as $segment) { + $results = array_merge($results, self::buscarPropietario($segment)); + } + } else { + $results = self::buscarPropietarioNombres($query); + $results = array_merge($results, self::buscarPropietarioApellido($query)); + $results = array_merge($results, self::buscarPropietarioNombreCompleto($query)); + } + return $results; + } + protected static function buscarPropietarioNombres($query) + { + $results = \Model::factory(Venta::class) + ->select('venta.*') + ->join('propietario', ['propietario.rut', '=', 'venta.propietario']) + ->whereLike('propietario.nombres', '%' . $query . '%') + ->findMany(); + return $results; + } + protected static function buscarPropietarioApellido($query) + { + $results = \Model::factory(Venta::class) + ->select('venta.*') + ->join('propietario', ['propietario.rut', '=', 'venta.propietario']) + ->whereAnyIs([ + ['propietario.apellido_paterno' => '%' . $query . '%'], + ['propietario.apellido_materno' => '%' . $query . '%'] + ], 'LIKE') + ->findMany(); + return $results; + } + protected static function buscarPropietarioNombreCompleto($query) + { + $results = \Model::factory(Venta::class) + ->select('venta.*') + ->join('propietario', ['propietario.rut', '=', 'venta.propietario']) + ->whereRaw("CONCAT_WS(' ', propietario.nombres, propietario.apellido_paterno, propietario.apellido_materno) LIKE '%" . $query . "%'") + ->findMany(); + return $results; + } + protected static function buscarPrecioVenta($query) + { + if (is_array($query)) { + $results = []; + foreach ($query as $segment) { + $results = array_merge($results, self::buscarPrecioVenta($segment)); + } + } else { + $query = str_replace([',', '.'], ['.', ''], $query); + $results = \Model::factory(Venta::class)->where('valor_uf', $query)->findMany(); + } + return $results; + } + protected static function buscarProyecto($query) + { + if (is_array($query)) { + $results = []; + foreach ($query as $segment) { + $results = array_merge($results, self::buscarProyecto($segment)); + } + } else { + $results = model(Venta::class) + ->select('venta.*') + ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad']) + ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal']) + ->join('proyecto', ['proyecto.id', '=', 'unidad.proyecto']) + ->whereLike('proyecto.descripcion', '%' . $query . '%') + ->findMany(); + } + return $results; + } + protected static function buscarPago($query) + { + if (is_array($query)) { + $results = []; + foreach ($query as $segment) { + $results = array_merge($results, self::buscarPrecioVenta($segment)); + } + } else { + $query = str_replace(',', '.', str_replace('.', '', $query)); + $query2 = (float) $query; + if ($query != $query2) { + return []; + } + if (!is_float($query2)) { + return []; + } + $query = $query2; + $results = self::buscarValorCuota($query); + $results = array_merge($results, self::buscarReajuste($query)); + $results = array_merge($results, self::buscarEscritura($query)); + $results = array_merge($results, self::buscarSubsidio($query)); + $results = array_merge($results, self::buscarCredito($query)); + } + return $results; + } + protected static function buscarValorCuota($query) + { + $results = \Model::factory(Venta::class) + ->select('venta.*') + ->join('cuota', ['cuota.pie', '=', 'venta.pie']) + ->join('pago', ['pago.id', '=', 'cuota.pago']) + ->whereRaw("`pago`.`valor` = " . $query . " OR `pago`.`valor` / `pago`.`uf` = " . $query) + ->findMany(); + return $results; + } + protected static function buscarReajuste($query) + { + $results = \Model::factory(Venta::class) + ->select('venta.*') + ->join('pie', ['pie.id', '=', 'venta.pie']) + ->join('pago', ['pago.id', '=', 'pie.reajuste']) + ->whereRaw("`pago`.`valor` = " . $query . " OR `pago`.`valor` / `pago`.`uf` = " . $query) + ->findMany(); + return $results; + } + protected static function buscarEscritura($query) + { + $results = \Model::factory(Venta::class) + ->select('venta.*') + ->join('escritura', ['escritura.id', '=', 'venta.escritura']) + ->join('pago', ['pago.id', '=', 'escritura.pago']) + ->whereRaw("`pago`.`valor` = " . $query . " OR `pago`.`valor` / `pago`.`uf` = " . $query) + ->findMany(); + return $results; + } + protected static function buscarSubsidio($query) + { + $results = \Model::factory(Venta::class) + ->select('venta.*') + ->join('subsidio', ['subsidio.id', '=', 'venta.subsidio']) + ->join('pago', ['pago.id', '=', 'subsidio.pago']) + ->whereRaw("`pago`.`valor` = " . $query . " OR `pago`.`valor` / `pago`.`uf` = " . $query) + ->findMany(); + return $results; + } + protected static function buscarCredito($query) + { + $results = \Model::factory(Venta::class) + ->select('venta.*') + ->join('credito', ['credito.id', '=', 'venta.credito']) + ->join('pago', ['pago.id', '=', 'credito.pago']) + ->whereRaw("`pago`.`valor` = " . $query . " OR `pago`.`valor` / `pago`.`uf` = " . $query) + ->findMany(); + return $results; + } + protected static function buscarUnidad($query) + { + if (is_array($query)) { + $results = []; + foreach ($query as $segment) { + $results = array_merge($results, self::buscarUnidad($segment)); + } + } else { + $results = model(Unidad::class)->where('descripcion', $query)->findMany(); + foreach ($results as $i => $u) { + if ($u->venta()) { + unset($results[$i]); + } + } + } + return $results; + } +} +?> diff --git a/app/Controller/Cierres.php b/app/Controller/Cierres.php new file mode 100644 index 0000000..077a5ce --- /dev/null +++ b/app/Controller/Cierres.php @@ -0,0 +1,428 @@ +select('proyecto.*') + ->join('estado_proyecto', ['estado.proyecto', '=', 'proyecto.id'], 'estado') + ->join('tipo_estado_proyecto', ['tipo.id', '=', 'estado.estado'], 'tipo') + ->join('etapa_proyecto', ['etapa.id', '=', 'tipo.etapa'], 'etapa') + ->whereGte('etapa.orden', 3) + ->orderByAsc('proyecto.descripcion') + ->groupBy('proyecto.id') + ->findMany(); + $regiones = model(Region::class)->order_by_asc('numeracion')->findMany(); + return view('ventas.cierres.add', compact('proyectos', 'regiones')); + } + public static function agregar() + { + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $id_proyecto = post('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id_proyecto); + $id_agente = post('agente'); + $agente = model(Agente::class)->findOne($id_agente); + + $direccion = model(Direccion::class) + ->where('calle', post('calle')) + ->where('numero', post('numero')) + ->where('extra', post('extra')) + ->where('comuna', post('comuna')) + ->findOne(); + if (!$direccion) { + $data = [ + 'calle' => post('calle'), + 'numero' => post('numero'), + 'extra' => post('extra'), + 'comuna' => post('comuna') + ]; + $direccion = model(Direccion::class)->create($data); + $direccion->save(); + } + + list($rut, $dv) = explode('-', str_replace('.', '', post('rut'))); + $propietario = model(Propietario::class)->findOne($rut); + if (!$propietario) { + $data = [ + 'rut' => $rut, + 'dv' => $dv, + 'nombres' => trim(post('nombres')), + 'apellido_paterno' => post('paterno'), + 'apellido_materno' => post('materno'), + 'sexo' => post('sexo'), + 'estado_civil' => post('estado_civil'), + 'profesion' => post('profesion'), + 'direccion' => $direccion->id, + 'telefono' => post('codigo_telefono') . post('telefono'), + 'email' => post('email') . '@' . post('email_domain'), + 'representante' => 0, + 'otro' => 0 + ]; + $propietario = model(Propietario::class)->create($data); + $propietario->save(); + } + + $unis = json_decode(post('unidades')); + $id_principal = array_shift($unis); + $unidad = model(Unidad::class)->findOne(post('unidad' . $id_principal)); + $u = model(U::class)->findOne($unidad->id); + if (!$u) { + $unidad->save(); + } + $data = [ + 'unidad_id' => $unidad->id + ]; + $reserva = model(Reserva::class)->create($data); + $reserva->save(); + foreach ($unis as $id_unidad) { + $unidad = model(Unidad::class)->findOne(post('unidad' . $id_unidad)); + $data = [ + 'reserva_id' => $reserva->id, + 'unidad_id' => $unidad->id + ]; + $ur = model(UnidadReserva::class)->create($data); + $ur->save(); + } + + $data = [ + 'proyecto_id' => $proyecto->id, + 'agente_id' => $agente->id, + 'propietario_rut' => $propietario->rut, + 'reserva_id' => $reserva->id, + 'fecha' => $f->format('Y-m-d'), + 'valor' => correctNumber(post('valor')), + 'pie' => correctNumber(post('pie')), + 'credito' => correctNumber(post('credito')), + 'estado' => 1 + ]; + $cierre = model(Cierre::class)->create($data); + $cierre->save(); + header('Location: ' . url('', ['p' => 'cierres', 'a' => 'list'])); + } + public static function list() + { + $proyectos = Cierre::proyectos(); + + return view('ventas.cierres.list', compact('proyectos')); + } + public static function show() + { + $id = get('cierre'); + $cierre = model(Cierre::class)->findOne($id); + + return view('ventas.cierres.show', compact('cierre')); + } + public static function guardar() + { + $proyecto = \model(Proyecto::class)->findOne(post('proyecto')); + $fecha = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $unidad = \model(Unidad::class)->findOne(post('departamento')); + $relacionado = (post('relacionado') === true) ? true : false; + $subrelacionado = (post('subrelacionado') === true) ? true : false; + $precio = (float) post('precio') ?: 0; + $input = [ + 'proyecto' => $proyecto, + 'fecha' => $fecha, + 'departamento' => $unidad, + 'precio' => $precio, + 'relacionado' => $relacionado, + 'subrelacionado' => $subrelacionado, + 'unidades' => [], + 'pie' => (float) post('pie') + ]; + $ebs = 0; + if (post('unidades') != '') { + $unidades = json_decode(html_entity_decode(post('unidades')), true); + foreach ($unidades as $un) { + $u = \model(Unidad::class)->findOne($un); + $input['unidades'] []= $u; + if ($u->precio($fecha) !== false) { + $ebs += $u->precio($fecha)->valor; + } + } + } + $promo = 0; + if (post('promocion') != null) { + $promo = (float) post('promocion'); + $input['promocion'] = $promo; + } + $bono = 0; + if (post('bono') != null) { + $bono = (float) post('bono'); + $input['bono'] = $bono; + } + $operador = 0; + if (post('operador') != null) { + $operador = ($precio - $bono - $promo) * (float) post('operador') / 100; + $input['operador'] = $operador; + } + + $cierre = Cierre::find($proyecto, $unidad, $precio)->findOne(); + if ($cierre === false) { + $cierre = model(Cierre::class)->create(); + $cierre->guardar((object) $input); + } + $output = ['status' => 'ok', 'cierre' => $cierre->asArray()]; + return json_encode($output); + } + public static function aprobar() + { + $fecha = Carbon::today(config('app.timezone')); + $cierre = model(Cierre::class)->findOne(post('cierre')); + if ($cierre->estado()->tipo()->descripcion == "revisado" or $cierre->estado()->tipo()->descripcion == "rechazado") { + $cierre->aprobar($fecha); + return json_encode(['estado' => 'aprobado']); + } + return json_encode(['estado' => 'no vigente']); + } + public static function rechazar() + { + $fecha = Carbon::today(config('app.timezone')); + $cierre = model(Cierre::class)->findOne(post('cierre')); + if ($cierre->estado()->tipo()->vigente == 1) { + $cierre->rechazar($fecha); + return json_encode(['estado' => 'rechazado']); + } + return json_encode(['estado' => 'no vigente']); + } + public static function abandonar() + { + $id = get('cierre'); + $cierre = model(Cierre::class)->findOne($id); + $tipo = model(TipoEstadoCierre::class)->where('descripcion', 'abandonado')->findOne(); + $today = Carbon::today(config('app.timezone')); + $data = [ + 'cierre' => $cierre->id, + 'tipo' => $tipo->id, + 'fecha' => $today->format('Y-m-d') + ]; + $estado = model(EstadoCierre::class)->create($data); + $estado->save(); + header('Location: ' . url('', ['p' => 'cierres', 'a' => 'list'])); + } + public static function promesar() + { + $id = get('cierre'); + $cierre = model(Cierre::class)->findOne($id); + $tipo = model(TipoEstadoCierre::class)->where('descripcion', 'promesado')->findOne(); + $today = Carbon::today(config('app.timezone')); + $data = [ + 'cierre' => $cierre->id, + 'tipo' => $tipo->id, + 'fecha' => $today->format('Y-m-d') + ]; + $estado = model(EstadoCierre::class)->create($data); + $estado->save(); + header('Location: ' . url('', ['p' => 'cierres', 'a' => 'show', 'cierre' => $cierre->id])); + } + public static function borrador() + { + $id = get('cierre'); + $cierre = model(Cierre::class)->findOne($id); + + $borrador = new Borrador($cierre); + d($borrador->show()); + $borrador->create(); + } + public static function evalue() + { + $proyectos = \model(Proyecto::class)->orderByAsc('descripcion')->findMany(); + return view('ventas.cierres.evaluar', compact('proyectos')); + } + public static function evaluar() + { + $proyecto = \model(Proyecto::class)->findOne(post('proyecto')); + $fecha = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $unidad = \model(Unidad::class)->findOne(post('departamento')); + $relacionado = (post('relacionado') === 'true') ? true : false; + $subrelacionado = (post('subrelacionado') === 'true') ? true : false; + $precio = (float) post('precio') ?: 0; + $neto = $precio; + $ebs = 0; + if (post('unidades') != '') { + $unidades = json_decode(html_entity_decode(post('unidades')), true); + foreach ($unidades as $un) { + $u = \model(Unidad::class)->findOne($un); + if ($u->precio($fecha) !== false) { + $ebs += $u->precio($fecha)->valor; + } + } + } + $promocion = 0; + if (post('promocion') != null) { + $promocion = (float) post('promocion'); + } + $bono = 0; + if (post('bono') != null) { + $bono = (float) post('bono'); + } + $operador = 0; + if (post('operador') != null) { + $operador = ($precio - $bono - $promocion) * (float) post('operador') / 100; + } + $rel = 0; + if ($relacionado) { + $rel = ($unidad->precio($fecha)->valor) * 6 / 100; + } + if ($subrelacionado) { + $rel = ($unidad->precio($fecha)->valor) * 3 / 100; + } + $neto = $precio - $bono - $promocion - $operador - $ebs; + + $output = [ + 'unidad' => [ + 'tipo' => [ + 'nombre' => $unidad->tipologia()->nombre, + 'tipologia' => $unidad->tipologia()->tipologia()->descripcion + ], + 'superficie' => format('m2', $unidad->m2()) . ' m²' + ], + 'oferta' => [ + 'bruto' => format('ufs', $precio, null, true), + 'neto' => format('ufs', $neto, null, true), + 'uf_m2' => format('ufs', $neto / $unidad->m2('vendible'), null, true) . '/m²', + 'fecha' => format('shortDate', $unidad->precio($fecha)->inicio()->fecha()) + ], + 'lista' => [ + 'precio' => format('ufs', $unidad->precio($fecha)->valor, null, true), + 'uf_m2' => format('ufs', $unidad->precio($fecha)->valor / $unidad->m2('vendible'), null, true) . '/m²' + ], + 'precios' => [ + 'bruto' => format('ufs', $precio, null, true), + 'neto' => format('ufs', $neto, null, true), + 'departamento' => format('ufs', $unidad->precio($fecha)->valor, null, true), + 'relacionado' => format('ufs', $unidad->precio($fecha)->valor - $rel, null, true), + 'fecha' => format('shortDate', $unidad->precio($fecha)->inicio()->fecha()) + ], + 'uf_m2' => [ + 'neto' => format('ufs', $neto / $unidad->m2('vendible'), null, true) . '/m²', + 'departamento' => format('ufs', $unidad->precio($fecha)->valor / $unidad->m2('vendible'), null, true) . '/m²', + 'relacionado' => format('ufs', ($unidad->precio($fecha)->valor - $rel) / $unidad->m2('vendible'), null, true) . '/²' + ], + 'evaluacion' => Cierre::evaluar($neto, $unidad, $fecha, $rel), + 'estado' => ['id' => 0, 'descripcion' => 'no existe'] + ]; + if ($rel > 0) { + $output ['relacionado'] = [ + 'precio' => format('ufs', $unidad->precio($fecha)->valor - $rel, null, true), + 'uf_m2' => format('ufs', ($unidad->precio($fecha)->valor - $rel) / $unidad->m2('vendible'), null, true) . '/²' + ]; + } + $estado = Cierre::find($proyecto, $unidad, $precio)->findOne(); + if ($estado) { + $output['estado'] = [ + 'id' => $estado->estado()->tipo()->id, + 'cierre' => $estado->id, + 'descripcion' => $estado->estado()->tipo()->descripcion, + 'fecha' => format('shortDate', $estado->estado()->fecha) + ]; + } + + return json_encode($output); + } + public static function edit() + { + $cierre = model(Cierre::class)->findOne(get('cierre')); + $proyectos = model(Proyecto::class)->findMany(); + $regiones = model(Region::class)->findMany(); + $valores = model(TipoValorCierre::class)->findMany(); + return view('ventas.cierres.edit', compact('cierre', 'proyectos', 'regiones', 'valores')); + } + public static function do_edit() + { + $cierre = model(Cierre::class)->findOne(get('cierre')); + + $data = [ + 'calle' => post('calle'), + 'numero' => post('numero'), + 'extra' => post('extra'), + 'comuna' => post('comuna') + ]; + $direccion = (new Factory(Direccion::class))->where($data)->find(); + if (!$direccion) { + $direccion = model(Direccion::class)->create($data); + $direccion->save(); + } + if (post('rut') != '') { + $data = [ + 'rut' => explode('-', str_replace('.', '', post('rut')))[0], + ]; + $propietario = (new Factory(Propietario::class))->where($data)->find(); + if (!$propietario) { + $data = array_merge($data, [ + 'nombres' => post('nombres'), + 'apellido_paterno' => post('paterno'), + 'apellido_materno' => post('materno'), + 'dv' => (post('rut')) ? explode('-', str_replace('.', '', post('rut')))[1] : '', + 'sexo' => post('sexo'), + 'estado_civil' => post('estado_civil'), + 'profesion' => post('profesion'), + 'telefono' => post('codigo_telefono') . post('telefono'), + 'email' => post('email') . '@' . post('email_domain'), + 'direccion' => $direccion->id + ]); + $propietario = model(Propietario::class)->create($data); + $propietario->save(); + } + } + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $data = [ + 'proyecto' => post('proyecto'), + 'precio' => post('precio'), + 'fecha' => $f->format('Y-m-d'), + 'relacionado' => (post('relacionado')) ? 1 : 0, + 'propietario' => (isset($propietario) and $propietario) ? $propietario->rut : 0 + ]; + foreach ($data as $field => $value) { + if ($value != $cierre->$field) { + $cierre->$field = $value; + } + } + $cierre->save(); + + $valores = model(TipoValorCierre::class)->findMany(); + foreach ($valores as $valor) { + if (post($valor->descripcion) == '') { + continue; + } + if ($cierre->valor($valor->descripcion)) { + if ($cierre->valor($valor->descripcion)->valor != post($valor->descripcion)) { + $v = $cierre->valor($valor->descripcion); + $v->valor = post($valor->descripcion); + $v->save(); + } + continue; + } + $data = [ + 'tipo' => $valor->descripcion, + 'valor' => post($valor->descripcion) + ]; + $cierre->addValor($data); + } + header('Location: ' . nUrl('cierres', 'show', ['cierre' => $cierre->id])); + } +} +?> diff --git a/app/Controller/Comentarios.php b/app/Controller/Comentarios.php new file mode 100644 index 0000000..494fcc6 --- /dev/null +++ b/app/Controller/Comentarios.php @@ -0,0 +1,39 @@ +findOne(get('venta')); + echo view('ventas.comentarios.add', compact('venta')); + } + public static function agregar() + { + $venta = \Model::factory(\Incoviba\old\Venta\Venta::class)->findOne(get('venta')); + if ($venta === false) { + throw new Exception('Venta no existe.'); + } + $data = [ + 'venta' => $venta->id, + 'fecha' => \Carbon\Carbon::now(config('app.timezone'))->format('Y-m-d H:i:s'), + 'texto' => post('comentario') + ]; + $comentario = \Model::factory(\Incoviba\old\Venta\Comentario::class)->create($data); + $comentario->save(); + header('Location: ' . nUrl('ventas', 'show', ['venta' => $venta->id])); + } + public static function delete() + { + $comentario = \Model::factory(\Incoviba\old\Venta\Comentario::class)->findOne(get('comentario')); + $venta = $comentario->venta(); + $comentario->estado = 0; + $comentario->save(); + header('Location: ' . nUrl('ventas', 'show', ['venta' => $venta->id])); + } +} +?> diff --git a/app/Controller/Contabilidad.php b/app/Controller/Contabilidad.php new file mode 100644 index 0000000..4b19a77 --- /dev/null +++ b/app/Controller/Contabilidad.php @@ -0,0 +1,100 @@ +orderByAsc('descripcion')->findMany(); + foreach ($proyectos as &$proyecto) { + $arr = $proyecto->asArray(); + $arr['direccion'] = $proyecto->direccion()->asArray(); + $arr['direccion']['comuna'] = $proyecto->direccion()->comuna()->asArray(); + $arr['inmobiliaria'] = $proyecto->inmobiliaria()->asArray(); + $proyecto = $arr; + } + return json_encode(compact('proyectos')); + } + public static function get_fechas() { + $id_proyecto = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id_proyecto); + $cuotas = []; + foreach ($proyecto->ventas() as $venta) { + $cs = $venta->pie()->cuotas(); + $cuotas = array_merge($cs, array_filter($cs, function($item) { + $tipo = $item->pago()->estado()->tipo(); + return ($tipo == 'depositado' or $tipo == 'abonado'); + })); + } + $fechas = array_map(function($item) { + return [ + 'timestamp' => $item->pago()->estado()->fecha()->timestamp, + 'short' => $item->pago()->estado()->fecha()->format('Y-m-d'), + 'long' => $item->pago()->estado()->fecha()->format('d / m / Y') + ]; + }, $cuotas); + usort($fechas, function($a, $b) { + return $b['timestamp'] - $a['timestamp']; + }); + return json_encode(compact('fechas')); + } + public static function get_pagos_fechas() { + $id_proyecto = get('proyecto'); + $fecha = Carbon::parse(get('fecha')); + $proyecto = model(Proyecto::class)->findOne($id_proyecto); + $pagos = []; + foreach ($proyecto->ventas() as $venta) { + foreach ($venta->pie()->cuotas() as $cuota) { + if ($cuota->pago()->estado()->fecha() == $fecha) { + $pagos []= [ + 'Departamento' => $venta->propiedad()->unidad()->descripcion, + 'Valor' => [ + 'UF' => $cuota->pago()->valor('ufs'), + 'Pesos' => $cuota->pago()->valor() + ], + 'Numero' => $cuota->numero(), + 'Total' => $venta->pie()->cuotas + ]; + break; + } + } + } + return json_encode(compact('pagos')); + } + public static function pagos_fecha() { + $fecha = Carbon::now(); + return view('contabilidad.pagos', compact('fecha')); + } + public static function show_pagos() { + $id_proyecto = get('proyecto'); + $fecha = Carbon::parse(get('fecha')); + $proyecto = model(Proyecto::class)->findOne($id_proyecto); + $pagos = []; + foreach ($proyecto->ventas() as $venta) { + foreach ($venta->pie()->cuotas() as $cuota) { + if ($cuota->pago()->estado()->fecha() == $fecha) { + $pagos []= (object) [ + 'Departamento' => $venta->propiedad()->unidad()->descripcion, + 'Valor' => (object) [ + 'UF' => $cuota->pago()->valor('ufs'), + 'Pesos' => $cuota->pago()->valor() + ], + 'Numero' => $cuota->numero(), + 'Total' => $venta->pie()->cuotas + ]; + break; + } + } + } + return view('contabilidad.pago', compact('proyecto', 'fecha', 'pagos')); + } +} diff --git a/app/Controller/Creditos.php b/app/Controller/Creditos.php new file mode 100644 index 0000000..60a72da --- /dev/null +++ b/app/Controller/Creditos.php @@ -0,0 +1,207 @@ +findOne($id); + return view('ventas.creditos.add', compact('venta')); + } + public static function agregado() + { + $id = get('venta'); + if ($id == null) { + header('Location: .'); + } + $venta = \Model::factory(Venta::class)->findOne($id); + + $banco = \Model::factory(Banco::class)->where('nombre', post('banco'))->findOne(); + $f = Carbon::createFromDate(post('y'), post('m'), post('d'), config('app.timezone')); + $uf = uf($f); + + $pago = \Model::factory(Pago::class)->create(); + $pago->banco = $banco->id; + $pago->fecha = $f->format('Y-m-d'); + $pago->uf = $uf->uf->value; + $pago->valor = post('valor') * $pago->uf; + $pago->tipo = 2; + + $credito = \Model::factory(Credito::class)->create(); + $credito->banco = $pago->banco; + $credito->valor = $pago->valor; + $credito->fecha = $pago->fecha; + $credito->uf = $pago->uf; + + $pago->new(); + + $credito->pago = $pago->id; + $credito->save(); + + $venta->credito = $credito->id; + $venta->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function pagar() + { + $id = get('venta'); + $venta = \Model::factory(Venta::class)->findOne($id); + return view('ventas.creditos.pagar', compact('venta')); + } + public static function pagando() + { + $id = get('venta'); + $venta = \Model::factory(Venta::class)->findOne($id); + $valor = str_replace(',', '.', str_replace('.', '', post('valor'))); + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + + $pago = $venta->credito()->pago(); + if ($pago->valor != $valor) { + $pago->valor = $valor; + } + + $estado = \Model::factory(EstadoPago::class)->create(); + $estado->pago = $pago->id; + $estado->fecha = $f->format('Y-m-d'); + $estado->estado = 1; + $estado->save(); + + if ($pago->is_dirty('valor')) { + $pago->save(); + } + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function abonar() + { + $id = get('venta'); + $venta = \Model::factory(Venta::class)->findOne($id); + return view('ventas.creditos.abonar', compact('venta')); + } + public static function abonando() + { + $id = get('venta'); + $venta = \Model::factory(Venta::class)->findOne($id); + $valor = str_replace(',', '.', str_replace('.', '', post('valor'))); + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + + $pago = $venta->credito()->pago(); + if ($pago->valor != $valor) { + $pago->valor = $valor; + } + + $estado = \Model::factory(EstadoPago::class)->create(); + $estado->pago = $pago->id; + $estado->fecha = $f->format('Y-m-d'); + $estado->estado = 2; + + $estado->save(); + + if ($pago->is_dirty('valor')) { + $pago->save(); + } + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function show() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + return view('ventas.creditos.show', compact('venta')); + } + public static function edit() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + return view('ventas.creditos.edit', compact('venta')); + } + public static function editado() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + $pago = $venta->credito()->pago(); + + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $uf = uf($f); + $banco = model(Banco::class)->where('nombre', post('banco'))->findOne(); + $valor = correctNumber(post('valor')) * $uf->uf->value; + + $fields = ['valor', 'uf', 'fecha', 'banco']; + $data = ['valor' => $valor, 'uf' => $uf->uf->value, 'fecha' => $f->format('Y-m-d'), 'banco' => $banco->id]; + + $change = false; + foreach ($fields as $field) { + if ($pago->$field != $data[$field]) { + $change = true; + $pago->$field = $data[$field]; + if ($field == 'fecha') { + $eps = $pago->estados(); + foreach ($eps as $ep) { + if ($ep->estado == 0) { + $ep->fecha = $data[$field]; + $ep->save(); + break; + } + } + } + } + } + + if ($change) { + $pago->save(); + } + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function remove() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + $pago = $venta->credito()->pago(); + $f = Carbon::today(config('app.timezone')); + + $data = [ + 'pago' => $pago->id, + 'estado' => -3, + 'fecha' => $f->format('Y-m-d') + ]; + $estado = model(EstadoPago::class)->create($data); + $estado->save(); + $venta->credito = 0; + $venta->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function pendientes() + { + $creditos = model(Credito::class) + ->select('credito.*') + ->join('venta', ['venta.credito', '=', 'credito.id']) + ->join('pago', ['pago.id', '=', 'credito.pago']) + ->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') + ->whereLt('estado_pago.estado', 2) + ->where('venta.estado', 1) + ->orderByAsc('estado_pago.fecha') + ->findMany(); + return view('ventas.creditos.pendientes', compact('creditos')); + } +} +?> diff --git a/app/Controller/Cuotas.php b/app/Controller/Cuotas.php new file mode 100644 index 0000000..4d457ba --- /dev/null +++ b/app/Controller/Cuotas.php @@ -0,0 +1,230 @@ +findOne($id); + + return view('ventas.pies.cuotas.show', compact('cuota')); + } + public static function edit() + { + $id = get('cuota'); + $cuota = \Model::factory(Cuota::class)->findOne($id); + return view('ventas.pies.cuotas.edit', compact('cuota')); + } + public static function editar() + { + $id = get('cuota'); + $cuota = \Model::factory(Cuota::class)->findOne($id); + + $cuota->numero = post('numero'); + $cuota->{'valor_$'} = post('valor'); + $banco = \Model::factory(\Incoviba\old\Common\Banco::class)->where('nombre', post('banco'))->findOne(); + if ($banco) { + $cuota->banco = $banco->id; + } else { + $cuota->banco = 0; + } + $f = \Carbon\Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $cuota->fecha = $f->format('Y-m-d'); + $pago = $cuota->pago(); + $pago->valor = post('valor'); + $pago->banco = $banco->id; + $pago->identificador = post('identificador'); + $pago->fecha = $f->format('Y-m-d'); + $uf = uf($f); + if ($uf->total > 0) { + $pago->uf = $uf->uf->value; + } else { + $pago->uf = 0; + } + + $pago->save(); + $cuota->save(); + header('Location: ' . url('', ['p' => 'pies', 'a' => 'resumen', 'pie' => $cuota->pie()->id])); + } + public static function edited() + { + $id = get('cuota'); + $cuota = \Model::factory(Cuota::class)->findOne($id); + $pago = $cuota->pago(); + foreach ($_POST as $key => $value) { + $pago->$key = $value; + } + $pago->save(); + } + public static function pendientes() + { + $f = \Carbon\Carbon::today(config('app.timezone')); + $cuotas = \Model::factory(Cuota::class) + ->select('cuota.*') + ->join('pago', ['pago.id', '=', 'cuota.pago']) + ->join('venta', ['venta.pie', '=', 'cuota.pie']) + ->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('ep.estado', 0) + ->where('venta.estado', 1) + ->whereLte('pago.fecha', $f->format('Y-m-d')) + ->order_by_asc('pago.fecha') + ->findMany(); + $sum = 0; + if (count($cuotas) > 0) { + $sum = array_reduce($cuotas, function($carry, $item) { + $carry += $item->pago()->valor; + return $carry; + }); + } + setlocale(LC_TIME, 'es'); + return view('ventas.pies.cuotas.pendientes', compact('cuotas', 'sum')); + } + public static function depositar() + { + $id = post('cuota'); + $cuota = \Model::factory(Cuota::class)->findOne($id); + if ($cuota->pago()->estado()->estado == 1) { + return 'ok'; + } + $estado = \Model::factory(EstadoPago::class)->create(); + $estado->pago = $cuota->pago()->id; + $estado->estado = 1; + $f = Carbon::parse(post('fecha'), config('app.timezone')); + $estado->fecha = $f->format('Y-m-d'); + $estado->save(); + return 'ok'; + } + public static function remove() + { + $id = get('cuota'); + $cuota = \Model::factory(Cuota::class)->findOne($id); + + $estado = \Model::factory(EstadoPago::class)->create(); + $estado->pago = $cuota->pago()->id; + $estado->estado = -3; + $f = Carbon::today(config('app.timezone')); + $estado->fecha = $f->format('Y-m-d'); + $estado->save(); + header('Location: ' . url('', ['p' => 'pies', 'a' => 'resumen', 'pie' => $cuota->pie()->id])); + } + public static function para_abonar() + { + $cuotas = \Model::factory(Cuota::class) + ->select('cuota.*') + ->join('pago', ['pago.id', '=', 'cuota.pago']) + ->join('venta', ['venta.pie', '=', 'cuota.pie']) + ->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('ep.estado', 1) + ->where('venta.estado', 1) + ->order_by_asc('ep.fecha') + ->findMany(); + $ini = get('start'); + if ($ini == null) { + $ini = 0; + } + $n = get('step'); + if ($n == 0) { + $n = 30; + } + $total = count($cuotas); + $cuotas = array_slice($cuotas, $ini, $n); + $pages = ceil($total / $n); + $current = ($ini + $n) / $n; + return view('ventas.pies.cuotas.abonar', compact('cuotas', 'total', 'pages', 'current')); + } + public static function abonar() + { + $id = post('cuota'); + $cuota = \Model::factory(Cuota::class)->findOne($id); + if ($cuota->pago()->estado()->estado == 2) { + return 'ok'; + } + $estado = \Model::factory(EstadoPago::class)->create(); + $estado->pago = $cuota->pago()->id; + $estado->estado = 2; + $f = Carbon::parse(post('fecha'), config('app.timezone')); + $estado->fecha = $f->format('Y-m-d'); + $estado->save(); + return 'ok'; + } + public static function rebotar() + { + $id = post('cuota'); + $cuota = \Model::factory(Cuota::class)->findOne($id); + if ($cuota->pago()->estado()->estado == -1) { + return 'ok'; + } + $estado = \Model::factory(EstadoPago::class)->create(); + $estado->pago = $cuota->pago()->id; + $estado->estado = -1; + $f = Carbon::parse(post('fecha'), config('app.timezone')); + $estado->fecha = $f->format('Y-m-d'); + $estado->save(); + return 'ok'; + } + public static function add() + { + $id = get('pie'); + $pie = \Model::factory(Pie::class)->findOne($id); + return view('ventas.pies.cuotas.add', compact('pie')); + } + public static function agregar() + { + $id = get('pie'); + $pie = \Model::factory(Pie::class)->findOne($id); + + $cant = $pie->cuotas - count($pie->cuotas()); + for ($i = 0; $i < $cant; $i ++) { + if (trim(post('valor' . $i)) == '') { + continue; + } + $banco = \Model::factory(Banco::class)->where('nombre', post('banco' . $i))->findOne(); + $f = Carbon::createFromDate(post('year' . $i), post('month' . $i), post('day' . $i), config('app.timezone')); + $uf = uf($f); + $valor = correctNumber(post('valor' . $i)); + + $pago = \Model::factory(Pago::class)->create(); + $pago->banco = $banco->id; + $pago->fecha = $f->format('Y-m-d'); + if ($uf and $uf->total > 0) { + $pago->uf = $uf->uf->value; + } else { + $pago->uf = 0; + } + $pago->tipo = 1; + $pago->valor = $valor; + $pago->identificador = post('identificador' . $i); + + $cuota = \Model::factory(Cuota::class)->create(); + $cuota->pie = $pie->id; + $cuota->fecha = $pago->fecha; + $cuota->{'valor_$'} = $pago->valor; + $cuota->estado = 0; + $cuota->banco = $pago->banco; + $cuota->uf = $pago->uf; + $cuota->numero = post('numero' . $i); + + $pago->new(); + + $cuota->pago = $pago->id; + $cuota->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $pie->venta()->id])); + } + } +} +?> diff --git a/app/Controller/Devoluciones.php b/app/Controller/Devoluciones.php new file mode 100644 index 0000000..8d9c41c --- /dev/null +++ b/app/Controller/Devoluciones.php @@ -0,0 +1,19 @@ +findOne($id); + + return view('print.devolucion', compact('venta')); + } +} +?> diff --git a/app/Controller/Escrituras.php b/app/Controller/Escrituras.php new file mode 100644 index 0000000..f2cb056 --- /dev/null +++ b/app/Controller/Escrituras.php @@ -0,0 +1,212 @@ +findOne($id); + return view('ventas.escrituras.add', compact('venta')); + } + public static function agregar() + { + $id = get('venta'); + $venta = \Model::factory(Venta::class)->findOne($id); + + $f = Carbon::createFromDate(post('escritura_year'), post('escritura_month'), post('escritura_day'), config('app.timezone')); + $venta->escriturado = $f->format('Y-m-d'); + + if (post('valor_reajuste')) { + $reajuste = \Model::factory(Pago::class)->create(); + $reajuste->valor = correctNumber(post('valor_reajuste')); + $fp = Carbon::createFromDate(post('reajuste_year'), post('reajuste_month'), post('reajuste_day'), config('app.timezone')); + $reajuste->fecha = $fp->format('Y-m-d'); + $reajuste->uf = (float) uf($fp)->uf->value; + $reajuste->newPagado(); + + $pie = $venta->pie(); + $pie->reajuste = $reajuste->id; + $pie->save(); + } + if (post('escritura_valor') or post('escritura_valor_uf')) { + $pago = \Model::factory(Pago::class)->create(); + $fp = Carbon::createFromDate(post('pago_escritura_year'), post('pago_escritura_month'), post('pago_escritura_day'), config('app.timezone')); + $pago->fecha = $fp->format('Y-m-d'); + $pago->uf = (float) uf($fp)->uf->value; + if (post('escritura_valor')) { + $pago->valor = correctNumber(post('escritura_valor')); + $pago->newPagado(); + } else { + $pago->valor = correctNumber(post('escritura_valor_uf')) * $pago->uf; + $pago->new(); + } + + $escritura = \Model::factory(Escritura::class)->create(); + $escritura->pago = $pago->id; + $escritura->valor = $pago->valor('uf'); + $escritura->fecha = $pago->fecha; + $escritura->save(); + + $venta->escritura = $escritura->id; + } + if (post('subsidio_ahorrado') or post('subsidio_valor')) { + $total = post('subsidio_ahorrado') + post('subsidio_valor'); + $subsidio = \Model::factory(Subsidio::class)->create(); + $pago = \Model::factory(Pago::class)->create(); + $pago->fecha = $f->format('Y-m-d'); + $pago->uf = (float) uf($f)->uf->value; + $pago->valor = correctNumber(post('subsidio_ahorrado')) * $pago->uf; + $pago->new(); + $subsidio->pago = $pago->id; + $pago = \Model::factory(Pago::class)->create(); + $pago->fecha = $f->format('Y-m-d'); + $pago->uf = (float) uf($f)->uf->value; + $pago->valor = correctNumber(post('subsidio_valor')) * $pago->uf; + $pago->new(); + $subsidio->subsidio = $pago->id; + $subsidio->save(); + + $venta->subsidio = $subsidio->id; + } + if (post('credito_valor')) { + $pago = \Model::factory(Pago::class)->create(); + $pago->fecha = $f->format('Y-m-d'); + $pago->uf = (float) uf($f)->uf->value; + $valor = post('credito_valor'); + if (strpos($valor, ',') !== false) { + $valor = correctNumber($valor); + } + $pago->valor = $valor * $pago->uf; + $banco = \Model::factory(Banco::class)->where('nombre', post('credito_banco'))->findOne(); + $pago->banco = $banco->id; + $pago->new(); + + $credito = \Model::factory(Credito::class)->create(); + $credito->pago = $pago->id; + $credito->save(); + + $venta->credito = $credito->id; + } elseif (post('credito_banco')) { + $pago = $venta->credito()->pago(); + $banco = \Model::factory(Banco::class)->where('nombre', post('credito_banco'))->findOne(); + $pago->banco = $banco->id; + $pago->save(); + } + + $tipo = \Model::factory(TipoEstadoVenta::class)->where('descripcion', 'escriturando')->findOne(); + $data = [ + 'venta' => $venta->id, + 'estado' => $tipo->id, + 'fecha' => $venta->escriturado + ]; + $estado = \Model::factory(EstadoVenta::class)->create($data); + $estado->save(); + $venta->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function edit() + { + $id = get('venta'); + $venta = \Model::factory(Venta::class)->findOne($id); + echo view('ventas.escrituras.edit', compact('venta')); + } + public static function editar() + { + $id = get('venta'); + $venta = \Model::factory(Venta::class)->findOne($id); + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $uf = uf($f); + + $valor = correctNumber(post('valor')); + if ($valor == '') { + $valor_uf = correctNumber(post('valor_uf')); + $valor = $valor_uf * $uf->uf->value; + } + $pago = $venta->escritura()->pago(); + if ($pago->valor != $valor) { + $pago->valor = $valor; + } + if ($pago->fecha != $f->format('Y-m-d')) { + $pago->fecha = $f->format('Y-m-d'); + $pago->uf = $uf->uf->value; + } + + $pago->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function informe() + { + $id = get('venta'); + $venta = \Model::factory(Venta::class)->findOne($id); + return view('ventas.escrituras.informe', compact('venta')); + } + public static function pagar() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + return view('ventas.escrituras.pagar', compact('venta')); + } + public static function pagado() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + + $data = [ + 'pago' => $venta->escritura()->pago()->id, + 'fecha' => $f->format('Y-m-d'), + 'estado' => 1 + ]; + $estado = model(EstadoPago::class)->create($data); + $estado->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function abonar() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + return view('ventas.escrituras.abonar', compact('venta')); + } + public static function abonado() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + + $data = [ + 'pago' => $venta->escritura()->pago()->id, + 'fecha' => $f->format('Y-m-d'), + 'estado' => 2 + ]; + $estado = model(EstadoPago::class)->create($data); + $estado->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } +} +?> diff --git a/app/Controller/FormaPago.php b/app/Controller/FormaPago.php new file mode 100644 index 0000000..6ccc7b3 --- /dev/null +++ b/app/Controller/FormaPago.php @@ -0,0 +1,98 @@ +findOne($id); + + return view('ventas.forma_pago.edit', compact('venta')); + } + public static function editar() + { + d(post()); + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + $valor = correctNumber(post('valor_pie')); + $cuotas = post('cuotas_pie'); + if ($venta->pie != 0) { + $pie = $venta->pie(); + $changed = false; + if ($pie->valor != $valor) { + $pie->valor = $valor; + $changed = true; + } + if ($pie->cuotas != $cuotas) { + $pie->cuotas = $cuotas; + $changed = true; + } + if ($changed) { + d($pie); + } + + $valor = correctNumber(post('valor_reajuste')); + $f = Carbon::createFromDate(post('year_reajuste'), post('month_reajuste'), post('day_reajuste'), config('app.timezone')); + $uf = uf($f); + $reajuste = $pie->reajuste(); + $changed = false; + if ($reajuste->valor != $valor) { + $reajuste->valor = $valor; + $changed = true; + } + if ($reajuste->fecha != $f->format('Y-m-d')) { + $reajuste->fecha = $f->format('Y-m-d'); + $reajuste->uf = $uf->uf->value; + $changed = true; + } + if ($changed) { + d($reajuste); + } + } elseif ($valor != '') { + $f = Carbon::parse($venta->fecha, config('app.timezone')); + $uf = uf($f); + $data = [ + 'valor' => $valor, + 'cuotas' => $cuotas, + 'uf' => $uf->uf->value, + 'fecha' => $f->format('Y-m-d') + ]; + $pie = model(Pie::class)->create($data); + d($pie); + } + + $valor = correctNumber(post('valor_escritura')); + $f = Carbon::createFromDate(post('year_escritura'), post('month_escritura'), post('day_escritura'), config('app.timezone')); + if ($venta->escritura != 0) { + $escritura = $venta->escritura(); + d($escritura); + } elseif ($valor != '') { + $data = [ + 'valor' => $valor, + 'fecha' => $f->format('Y-m-d'), + 'uf' => $uf->uf->value, + 'tipo' => 7 + ]; + $pago = model(Pago::class)->create($data); + $pago->newPagado(); + $data['pago'] = $pago->id; + unset($data['tipo']); + $escritura = model(Escritura::class)->create($data); + $escritura->save(); + $venta->escritura = $escritura->id; + $venta->save(); + } + } +} +?> diff --git a/app/Controller/Informes.php b/app/Controller/Informes.php new file mode 100644 index 0000000..6a65fe9 --- /dev/null +++ b/app/Controller/Informes.php @@ -0,0 +1,950 @@ +find_one($id_proyecto); + $ini = \Carbon\Carbon::parse($proyecto->estado()->fecha, config('app.timezone')); + #$informe = new Informador('Carta Gantt Proyecto - ' . $proyecto->descripcion); + $name = 'Carta Gantt Proyecto - ' . $proyecto->descripcion; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $name . ' - ' . $hoy->format('Y-m-d') . '.xls'); + $informe = new PHPExcel($name, $filename); + + $columnas = ['Departamento', 'Propietario', 'Entrega', 'Estado']; + $today = \Carbon\Carbon::today(config('app.timezone')); + $end = $today->copy()->addDays(30); + $dif = $end->diffInDays($ini); + for ($i = 0; $i <= $dif; $i ++) { + $f = $ini->copy()->addDays($i); + if ($f->isWeekend()) { + continue; + } + $columnas []= $f->format('Y-m-d'); + } + $informe->addColumns($columnas); + + $data = []; + foreach ($proyecto->entregas() as $venta) { + $info = []; + $info []= $venta->unidad()->descripcion; + $info []= $venta->propietario()->findOne()->nombreCompleto(); + $fe = Carbon::parse($venta->entrega()->find_one()->fecha, config('app.timezone')); + $info []= $fe->format('Y-m-d'); + $info []= ''; + + for ($i = 0; $i <= $dif; $i ++) { + $f = $ini->copy()->addDays($i); + if ($f->isWeekend()) { + continue; + } + if ($f >= $fe and $f <= $fe->copy()->addDays(14)) { + $info []= 'X'; + } else { + $info []= ''; + } + } + + $data []= $info; + } + $informe->addDatas($data); + + return $informe->informe(); + } else { + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many(); + return view('informes.gantt_entregas', compact('proyectos')); + } + } + public static function escrituras() + { + if (get('proyecto')) { + set_time_limit(60); + $id_proyecto = get('proyecto'); + $proyecto = model(Proyecto::class)->find_one($id_proyecto); + + #$informe = new Informador('Escrituras - ' . $proyecto->descripcion); + $name = 'Escrituras'; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls'); + $informe = new PHPExcel($name, $filename); + + $columnas = [ + 'Departamento', + 'Estacionamientos', + 'Bodegas', + 'Propietario', + (object) ['name' => 'Promesa', 'style' => 'number'], + ['name' => 'Bono Pie', 'style' => 'amount'], + ['name' => 'Pie Pagado', 'style' => 'amount'], + ['name' => 'Reajuste', 'style' => 'amount'], + ['name' => 'Abono Contado', 'style' => 'amount'], + ['name' => 'Subsidio', 'style' => 'amount'], + 'Estado Subsidio', + ['name' => 'Credito', 'style' => 'amount'], + 'Banco', + 'Estado Credito', + ['name' => 'Saldo', 'style' => 'amount'], + ['name' => 'Escritura', 'style' => 'amount'], + ['name' => 'Entrega', 'style' => 'date'] + ]; + $informe->addColumns($columnas); + + //$ventas = $proyecto->escrituras(); + $ventas = $proyecto->ventas(); + + $data = []; + foreach ($ventas as $venta) { + $info = []; + $info['Departamento'] = $venta->unidad()->descripcion; + $ests = []; + foreach ($venta->propiedad()->estacionamientos() as $e) { + $ests []= $e->descripcion; + } + $bods = []; + foreach ($venta->propiedad()->bodegas() as $b) { + $bods []= $b->descripcion; + } + $info['Estacionamientos'] = implode(' - ', $ests); + $info['Bodegas'] = implode(' - ', $bods); + $info['Propietario'] = $venta->propietario()->nombreCompleto(); + $info['Promesa'] = $venta->valor_uf; + $saldo = $venta->valor_uf; + $info['Bono Pie'] = ''; + if ($venta->bono_pie != 0) { + $info['Bono Pie'] = $venta->bonoPie()->pago()->valor('ufs'); + $saldo -= $venta->bonoPie()->pago()->valor('ufs'); + } + $info['Pie'] = ''; + $info['Reajuste'] = ''; + if ($venta->pie != 0) { + $info['Pie'] = $venta->pie()->valorPagado(); + $saldo -= $venta->pie()->valorPagado(); + if ($venta->pie()->reajuste != 0) { + $info['Reajuste'] = $venta->pie()->reajuste()->valor('ufs'); + $saldo -= $venta->pie()->reajuste()->valor('ufs'); + } + } + $info['Abono Contado'] = ''; + if ($venta->escritura != 0) { + $info['Abono Contado'] = $venta->escritura()->pago()->valor('ufs'); + $saldo -= $venta->escritura()->pago()->valor('ufs'); + } + $info['Subsidio'] = ''; + $info['Estado Subsidio'] = ''; + if ($venta->subsidio != 0) { + $info['Subsidio'] = $venta->subsidio()->total('ufs'); + $info['Estado Subsidio'] = implode(' - ', [ + $venta->subsidio()->subsidio()->estado()->tipo()->descripcion, + $venta->subsidio()->pago()->estado()->tipo()->descripcion + ]); + $saldo -= $venta->subsidio()->total('ufs'); + } + $info['Credito'] = ''; + $info['Banco'] = ''; + $info['Estado Credito'] = ''; + if ($venta->credito != 0) { + $info['Credito'] = $venta->credito()->pago()->valor('ufs'); + $saldo -= $venta->credito()->pago()->valor('ufs'); + if ($venta->credito()->pago()->banco != 0) { + $info['Banco'] = $venta->credito()->pago()->banco()->nombre; + } + $info['Estado Credito'] = $venta->credito()->pago()->estado()->tipo()->descripcion; + } + $info['Saldo'] = -$saldo; + $info['Escritura'] = ''; + if ($venta->escriturado != 0) { + $info['Escritura'] = $venta->escriturado; + } + $info['Entrega'] = ''; + if ($venta->entregado != 0) { + $info['Entrega'] = $venta->entregado; + } + + $data []= $info; + } + $informe->addData($data); + + return $informe->informe(); + } else { + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many(); + return view('informes.escrituras', compact('proyectos')); + } + } + public static function consolidacion() + { + $id_proyecto = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id_proyecto); + + $ventas = $proyecto->ventas(); + set_time_limit(count($ventas)); + + $f = Carbon::today(config('app.timezone')); + setlocale(LC_TIME, 'es'); + + $data = [ + [$proyecto->descripcion], + [strftime('%d de %B de %Y', $f->timestamp)], + [''], + [''] + ]; + $columns = [ + ['name' => 'Fecha', 'style' => 'date'], + 'Glosa', + ['name' => 'Debe', 'style' => 'number'], + ['name' => 'Haber', 'style' => 'number'], + ['name' => 'Saldo', 'style' => 'number'], + 'Comentario' + ]; + $bold_rows = []; + + foreach ($ventas as $venta) { + $data []= ['Departamento ' . $venta->unidad()->descripcion . ' (' . format('ufs', $venta->valor_uf) . ' UF)']; + $data []= $columns; + $bold_rows []= count($data) - 1; + $ufs = 0; + $debe = 0; + $haber = 0; + $sum = 0; + if ($venta->pie != 0) { + $cuotas = $venta->pie()->cuotas(); + foreach ($cuotas as $cuota) { + $sum += $cuota->pago()->valor(); + $ufs += $cuota->pago()->valor('ufs'); + $haber += $cuota->pago()->valor(); + $info = [ + $cuota->pago()->estado()->fecha, + 'Pie - Cuota ' . $cuota->numero() . ' - ' . $venta->pie()->cuotas . ' (' . format('ufs', $cuota->pago()->valor('ufs')) . ' UF)', + '', + $cuota->pago()->valor(), + $sum + ]; + if ($cuota->pago()->estado()->estado < 2) { + $info []= 'No ha sido abonada.'; + } + $data []= $info; + } + if ($venta->pie()->reajuste != 0) { + $sum += $venta->pie()->reajuste()->valor(); + $ufs += $venta->pie()->reajuste()->valor('ufs'); + $haber += $venta->pie()->reajuste()->valor(); + $info = [ + $venta->pie()->reajuste()->estado()->fecha, + 'Reajuste (' . format('ufs', $venta->pie()->reajuste()->valor('ufs')) . ' UF)', + '', + $venta->pie()->reajuste()->valor(), + $sum + ]; + if ($venta->pie()->reajuste()->estado()->estado < 2) { + $info []= 'No ha sido abonado.'; + } + $data []= $info; + } + } + if ($venta->escritura != 0) { + $sum += $venta->escritura()->pago()->valor(); + $ufs += $venta->escritura()->pago()->valor('ufs'); + $haber += $venta->escritura()->pago()->valor(); + $info = [ + $venta->escritura()->pago()->estado()->fecha, + 'Abono Escritura (' . format('ufs', $venta->escritura()->pago()->valor('ufs')) . ' UF)', + '', + $venta->escritura()->pago()->valor(), + $sum + ]; + if ($venta->escritura()->pago()->estado()->estado < 2) { + $info []= 'No ha sido abonado.'; + } + $data []= $info; + } + if ($venta->credito != 0) { + $sum += $venta->credito()->pago()->valor(); + $ufs += $venta->credito()->pago()->valor('ufs'); + $haber += $venta->credito()->pago()->valor(); + $info = [ + $venta->credito()->pago()->estado()->fecha, + 'Crédito (' . format('ufs', $venta->credito()->pago()->valor('ufs')) . ' UF)', + '', + $venta->credito()->pago()->valor(), + $sum + ]; + if ($venta->credito()->pago()->estado()->estado < 2) { + $info []= 'No ha sido pagado.'; + } + $data []= $info; + } + if ($venta->bono_pie != 0) { + try { + $sum -= $venta->bonoPie()->pago()->valor(); + $debe += $venta->bonoPie()->pago()->valor(); + $info = [ + $venta->bonoPie()->pago()->estado()->fecha, + 'Bono Pie (' . format('ufs', $venta->bonoPie()->pago()->valor('ufs')) . ' UF)'. + $venta->bonoPie()->pago()->valor(), + '', + $sum + ]; + $data []= $info; + $sum += $venta->bonoPie()->pago()->valor(); + $haber += $venta->bonoPie()->pago()->valor(); + $info = [ + $venta->bonoPie()->pago()->estado()->fecha, + 'Bono Pie (' . format('ufs', $venta->bonoPie()->pago()->valor('ufs')) . ' UF)'. + '', + $venta->bonoPie()->pago()->valor(), + $sum + ]; + $data []= $info; + } catch (\Exception $e) { + + } + } + $info = [ + '', + 'TOTAL (' . format('ufs', $ufs) . ' UF)', + $debe, + $haber, + $sum + ]; + $data []= $info; + $bold_rows []= count($data) - 1; + + $data []= ['']; + } + /** + * Departamento # + * Fecha |Glosa |Debe |Haber |Saldo + * |Pie - Cuota 1 - n (# UF) |- |$# | + * |Reajuste (# UF) |- |$# | + * |Abono Escritura (# UF) |- |$# | + * |Crédito (# UF) |- |$# | + * |Bono Pie (# UF) |$# |- | + * |Bono Pie (# UF) |- |$# | + * |Devolución (# UF) |$# |- | + * - |TOTAL (# UF) | | | + */ + + array_walk($data, function(&$e, $i) use ($columns) { + if (count($e) < count($columns)) { + $n = count($columns) - count($e); + for ($j = 0; $j < $n; $j ++) { + $e []= ''; + } + } + }); + + #$informe = new Informador('Consolidación - ' . $proyecto->descripcion); + $name = 'Consolidación'; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls'); + $informe = new PHPExcel($name, $filename); + $informe->addColumns($columns); + $informe->addData($data); + + return $informe->informe(); + } + public static function creditos_pendientes() + { + function creditos() { + $creditos = model(Credito::class) + ->select('credito.*') + ->join('venta', ['venta.credito', '=', 'credito.id']) + ->join('pago', ['pago.id', '=', 'credito.pago']) + ->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') + ->whereLt('estado_pago.estado', 2) + ->where('venta.estado', 1) + ->orderByAsc('estado_pago.fecha') + ->findMany(); + foreach ($creditos as $credito) { + yield $credito; + } + } + $informe = new Informador('Créditos Pendientes'); + + $columnas = ['Proyecto', 'Departamento', 'Valor', 'Fecha Escritura', 'Estado']; + $informe->addColumns($columnas); + + $row = 0; + foreach (creditos() as $credito) { + $informe->addData($row, $credito->venta()->proyecto()->descripcion, 'Proyecto'); + $informe->addData($row, $credito->venta()->unidad()->descripcion, 'Departamento'); + $informe->addData($row, $credito->pago()->valor('ufs'), 'Valor'); + $informe->addData($row, (($credito->venta()->escriturado) ? $credito->venta()->escriturado : $credito->pago()->estado()->fecha), 'Fecha Escritura'); + $informe->addData($row, ucwords($credito->pago()->estado()->tipo()->descripcion), 'Estado'); + + $row ++; + } + + $date = [ + 'numberFormat' => ['short-date'] + ]; + $ufs = [ + 'numberFormat' => ['thousands'] + ]; + $formats = ['Valor' => $ufs, 'Fecha Escritura' => $date]; + $informe->addFormats($formats); + + return $informe->informe(); + } + public static function ventas() + { + if (get('proyecto')) { + $id = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + $ventas = $proyecto->ventas(); + + /*usort($ventas, function($a, $b) { + return $a->fecha()->timestamp - $b->fecha()->timestamp; + });*/ + + $procasa = model(Agente::class)->findOne(1); + $pa = model(ProyectoAgente::class)->where('agente', $procasa->id)->where('proyecto', $proyecto->id)->findOne(); + if ($pa) { + $comision = $pa->comision / 100; + } else { + $comision = 0.03; + } + + #$informe = new Informador('Ventas - ' . $proyecto->descripcion); + $name = 'Informe de Ventas'; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xlsx'); + //$informe = new PHPExcel($name, $filename); + + $columnas = [ + 'Propietario', + ['name' => 'Departamento', 'style' => 'number'], + ['name' => 'Estacionamientos', 'style' => 'number'], + ['name' => 'Bodegas', 'style' => 'number'], + 'Fecha Venta', + ['name' => 'Mes', 'style' => 'mes'], + 'Tipo', + ['name' => 'm² Ponderados', 'style' => 'amount'], + ['name' => 'Valor Promesa', 'style' => 'amount'], + ['name' => 'Pie', 'style' => 'amount'], + ['name' => 'Pie Pagado', 'style' => 'amount'], + ['name' => '% Pie Pagado', 'style' => 'percent'], + ['name' => 'Bono Pie', 'style' => 'amount'], + 'Operador', + ['name' => 'Valor Operador', 'style' => 'amount'], + ['name' => 'Premios', 'style' => 'amount'], + ['name' => 'Subsidio', 'style' => 'amount'], + ['name' => 'Ahorro', 'style' => 'amount'], + ['name' => 'Credito', 'style' => 'amount'], + 'Banco', + ['name' => 'Valor Ests & Bods', 'style' => 'amount'], + ['name' => 'Valor Neto', 'style' => 'amount'], + ['name' => 'UF/m²*', 'style' => 'amount'], + ['name' => 'Comision', 'style' => 'amount'], + ['name' => 'Venta s/Comision', 'style' => 'amount'] + ]; + //$informe->addColumns($columnas); + + $data = []; + foreach ($ventas as $venta) { + $info = []; + $info['Propietario'] = mb_strtoupper($venta->propietario()->nombreCompleto()); + $info['Departamento'] = trim(array_reduce($venta->propiedad()->departamentos(), function($carry, $item) { + return implode(' - ', [$carry, $item->descripcion]); + }), ' -'); + //$ests = []; + $es = $venta->propiedad()->estacionamientos(); + /*if (count($es) > 0) { + foreach ($es as $e) { + $ests []= $e->descripcion; + } + } + $info['Estacionamientos'] = implode(', ', $ests);*/ + $info['Estacionamientos'] = implode(', ', array_map(function($item) { + return $item->descripcion; + }, $es)); + //$bods = []; + $bs = $venta->propiedad()->bodegas(); + /*if (count($bs) > 0) { + foreach ($bs as $b) { + $bods []= $b->descripcion; + } + } + $info['Bodegas'] = implode(', ', $bods);*/ + $info['Bodegas'] = implode(', ', array_map(function($item) { + return $item->descripcion; + }, $bs)); + $info['Fecha Venta'] = $venta->fecha()->format('Y-m-d'); + $info['Mes'] = $venta->fecha()->format('M-y'); + $info['Tipo'] = $venta->unidad()->abreviacion; + $info['m² Ponderados'] = $venta->unidad()->m2('vendible'); + $info['Valor Promesa'] = $venta->valor_uf; + $info['Pie'] = $venta->pie()->valor; + $info['Pie Pagado'] = 0; + $info['% Pie Pagado'] = 0; + if ($venta->pie()) { + $info['Pie Pagado'] = $venta->pie()->valorPagado('uf'); + $info['% Pie Pagado'] = $venta->pie()->valorPagado('uf') / $venta->valor_uf; + } + + $info['Bono Pie'] = ($venta->bono_pie == 0 or $venta->bonoPie() === false) ? '' : $venta->bonoPie()->pago()->valor('ufs'); + $info['Operador'] = ($venta->agente and $venta->agente()->agente()->tipo == 19) ? $venta->agente()->agente()->descripcion : ''; + $info['Valor Operador'] = $venta->valorComision(); + //$promos = 0; + $ps = $venta->promociones(); + /*if (count($ps) > 0) { + foreach ($ps as $promo) { + $promos += $promo->valor; + } + } + $info['Premios'] = $promos;*/ + $info['Premios'] = array_reduce($ps, function($sum, $item) { + return $sum + $item->valor; + }); + $info['Subsidio'] = 0; + $info['Ahorro'] = 0; + if ($venta->subsidio != 0) { + $info['Subsidio'] = $venta->subsidio()->subsidio()->valor('ufs'); + $info['Ahorro'] = $venta->subsidio()->pago()->valor('ufs'); + } + $info['Credito'] = 0; + $info['Banco'] = ''; + if ($venta->credito != 0) { + $info['Credito'] = $venta->credito()->pago()->valor('ufs'); + if ($venta->credito()->pago()->banco != 0) { + $info['Banco'] = $venta->credito()->pago()->banco()->nombre; + } + } + $info['Valor Ests & Bods'] = $venta->valorEstacionamientosYBodegas(); + $info['Valor Neto'] = $venta->valorFinal(); + $info['UF/m²*'] = $venta->uf_m2(); + $info['Comision'] = $venta->valorFinal() * $comision; + $info['Venta s/Comision'] = $venta->valorFinal() - $info['Comision']; + + $data []= $info; + } + /*$informe->addData($data); + + $totals = [ + 'Propietario' => 'TOTAL', + 'Departamento' => 'count', + 'Estacionamientos' => 'count', + 'Bodegas' => 'count', + 'm² Ponderados' => 'sum', + 'Valor Promesa' => 'sum', + 'Bono Pie' => 'sum', + 'Subsidio' => 'sum', + 'Ahorro' => 'sum', + 'Credito' => 'sum', + 'Valor Operador' => 'sum', + 'Premios' => 'sum', + 'Valor Ests & Bods' => 'sum', + 'Valor Neto' => 'sum', + 'Comision' => 'sum' + ]; + $informe->addTotals($totals); + + return $informe->informe();*/ + + $body = [ + "Proyecto" => $proyecto->descripcion, + "Compañía" => $proyecto->inmobiliaria()->abreviacion, + "data" => $data + ]; + $client = new Client(['base_uri' => 'localhost:8011']); + $response = $client->post('/ventas', ['json' => $body]); + + header("Content-Type: application/octet-stream; charset=utf-8"); + header('Content-Transfer-Encoding: binary'); + header('Content-Disposition: attachment; filename="' . $filename . '"'); + header('Cache-Control: max-age=0'); + return $response->getBody(); + //file_put_contents('php://output', $output); + + } else { + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many(); + return view('informes.ventas', compact('proyectos')); + } + } + public static function resumen_contabilidad() + { + if (get('proyecto')) { + $id = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + $fecha = get('fecha'); + $mes = null; + if ($fecha != null) { + $mes = Carbon::parse($fecha)->addMonths(1)->subDays(1); + } + + $ventas = $proyecto->ventas(); + + usort($ventas, function($a, $b) { + return $a->fecha()->timestamp - $b->fecha()->timestamp; + }); + + $name = 'Contabilidad'; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls'); + $informe = new PHPExcel($name, $filename); + + $columnas = [ + 'Propietario', + ['name' => 'Departamento', 'style' => 'general_number'], + ['name' => 'Estacionamientos', 'style' => 'number'], + ['name' => 'Bodegas', 'style' => 'number'], + 'Fecha Venta', + ['name' => 'Mes', 'style' => 'mes'], + 'Tipo', + ['name' => 'm² Ponderados', 'style' => 'amount'], + ['name' => 'Valor Promesa', 'style' => 'amount'], + ['name' => 'Pie [UF]', 'style' => 'amount'], + ['name' => 'Pie [$]', 'style' => 'amount'], + ['name' => 'Abono Escritura', 'style' => 'amount'], + ['name' => 'Crédito', 'style' => 'amount'], + ['name' => 'Cuotas', 'style' => 'number'], + ['name' => 'Cuotas Pagadas', 'style' => 'number'], + ['name' => 'Pie Pagado [UF]', 'style' => 'amount'], + ['name' => 'Pie Pagado [$]', 'style' => 'amount'] + ]; + $informe->addColumns($columnas); + + $data = []; + foreach ($ventas as $venta) { + $info = []; + $info['Propietario'] = mb_strtoupper($venta->propietario()->nombreCompleto()); + $info['Departamento'] = $venta->unidad()->descripcion; + $ests = []; + if ($venta->propiedad()->estacionamientos != '') { + $es = $venta->propiedad()->estacionamientos(); + foreach ($es as $e) { + $ests []= $e->descripcion; + } + } + $info['Estacionamientos'] = implode(', ', $ests); + $bods = []; + if ($venta->propiedad()->bodegas != '') { + $bs = $venta->propiedad()->bodegas(); + foreach ($bs as $b) { + $bods []= $b->descripcion; + } + } + $info['Bodegas'] = implode(', ', $bods); + $info['Fecha Venta'] = $venta->fecha()->format('d.m.Y'); + $info['Mes'] = $venta->fecha()->format('M-y'); + $info['Tipo'] = $venta->unidad()->abreviacion; + $info['m² Ponderados'] = $venta->unidad()->m2('vendible'); + $info['Valor Promesa'] = $venta->valor_uf; + $info['Pie [UF]'] = 0; + $info['Pie [$]'] = 0; + $info['Abono Escritura'] = 0; + $info['Crédito'] = 0; + $info['Cuotas'] = 0; + $info['Cuotas Pagadas'] = 0; + $info['Pie Pagado [UF]'] = 0; + $info['Pie Pagado [$]'] = 0; + if ($venta->pie()) { + $info['Pie [UF]'] = $venta->pie()->valor; + $info['Pie [$]'] = $venta->pie()->valorPesos(); + $info['Abono Escritura'] = ($venta->escritura != 0) ? $venta->escritura()->valor('ufs') : ($venta->valor_uf - $venta->pie()->valor - (($venta->credito != 0) ? $venta->credito()->pago()->valor('ufs') : 0)); + $info['Crédito'] = ($venta->credito != 0) ? $venta->credito()->pago()->valor('ufs') : 0; + $info['Cuotas'] = $venta->pie()->cuotas; + $info['Cuotas Pagadas'] = count($venta->pie()->pagadas($mes)); + $info['Pie Pagado [UF]'] = $venta->pie()->valorPagado('uf', $mes); + $info['Pie Pagado [$]'] = $venta->pie()->valorPagado('pesos', $mes); + } + + $data []= $info; + } + $informe->addData($data); + + $totals = [ + 'Departamento' => 'count', + 'Estacionamientos' => 'count', + 'Bodegas' => 'count', + 'm² Ponderados' => 'sum', + 'Valor Promesa' => 'sum', + 'Pie' => 'sum', + 'Pie Pagado' => 'sum' + ]; + $informe->addTotals($totals); + + return $informe->informe(); + } else { + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many(); + return view('informes.resumen_contabilidad', compact('proyectos')); + } + } + public static function contabilidad() + { + if (get('proyecto')) { + $id = get('proyecto'); + $fecha = get('fecha'); + $mes = null; + if ($fecha != null) { + $mes = Carbon::parse($fecha); + } + $proyecto = model(Proyecto::class)->findOne($id); + $q = "SELECT pago.*, venta.id AS vid, venta.tipo AS ctipo, venta.pie AS pie + FROM ( + SELECT pago.id, banco.nombre AS banco, pago.fecha, pago.valor, pago.uf, ep.estado, ep.fecha AS efecha + FROM pago JOIN banco ON banco.id = pago.banco JOIN (( + SELECT pago, MAX(id) AS id FROM estado_pago GROUP BY pago) e0 JOIN estado_pago ep ON ep.id = e0.id) ON ep.pago = pago.id + WHERE ep.estado > 0 "; + if ($mes != null) { + $q .= "AND (pago.fecha BETWEEN '" . $mes->format('Y-m-01') . "' AND '" . $mes->format('Y-m-t') . "' + OR ep.fecha BETWEEN '" . $mes->format('Y-m-01') . "' AND '" . $mes->format('Y-m-t') . "')"; + } + $q .= ") pago JOIN (SELECT venta.* + FROM (( + SELECT venta.id, venta.pie, venta.propiedad, credito.pago, 'credito' AS tipo + FROM venta JOIN credito ON credito.id = venta.credito) + UNION ALL ( + SELECT venta.id, venta.pie, venta.propiedad, escritura.pago, 'escritura' AS tipo + FROM venta JOIN escritura ON escritura.id = venta.escritura) + UNION ALL ( + SELECT venta.id, venta.pie, venta.propiedad, cuota.pago, 'cuota' AS tipo + FROM venta JOIN cuota ON cuota.pie = venta.pie)) venta + JOIN propiedad ON propiedad.id = venta.propiedad + JOIN unidad ON unidad.id = propiedad.unidad_principal + WHERE unidad.proyecto = ?) venta + ON venta.pago = pago.id"; + $st = \ORM::getDB()->prepare($q); + $st->execute([$id]); + if ($st->rowCount() > 0) { + $R = $st->fetchAll(\PDO::FETCH_OBJ); + + //$informe = new Informador('Contabilidad - ' . (($mes != null) ? $mes->format('Y-m') . ' - ' : '') . $proyecto->descripcion); + $name = 'Contabilidad'; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', 'Contabilidad - ' . (($mes != null) ? $mes->format('Y-m') . ' - ' : '') . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls'); + + $informe = new PHPExcel($name, $filename); + + $columnas = ['Proyecto', 'Fecha', 'Banco', 'Departamento', 'RUT', 'Propietario', 'Glosa', 'Glosa2', (object) ['name' => 'Valor', 'style' => 'integer'], (object) ['name' => 'Valor UF', 'style' => 'currency']]; + $informe->addColumns($columnas); + $data = []; + foreach ($R as $r) { + $info = []; + $info['Proyecto'] = $proyecto->descripcion; + $f1 = \Carbon\Carbon::parse($r->fecha, config('app.timezone')); + $f2 = \Carbon\Carbon::parse($r->efecha, config('app.timezone')); + $info['Fecha'] = ($f1->max($f2))->format('Y-m-d'); + $info['Banco'] = $r->banco; + $venta = model(Venta::class)->findOne($r->vid); + $info['Departamento'] = $venta->unidad()->descripcion; + $info['RUT'] = $venta->propietario()->rut(); + $info['Propietario'] = $venta->propietario()->nombreCompleto(); + $info['Glosa'] = ucwords($r->ctipo); + $info['Glosa2'] = ''; + if ($r->ctipo == 'cuota') { + $cuota = model(Cuota::class)->where('pago', $r->id)->findOne(); + + $info['Glosa'] = 'Pie - ' . format('ufs', $cuota->pie()->valor('ufs'), null, true); + + $info['Glosa2'] = $cuota->numero() . ' - ' . $cuota->pie()->cuotas; + } + $info['Valor'] = $r->valor; + $info['Valor UF'] = '0'; + if ($r->uf > 0) { + $info['Valor UF'] = $r->valor / $r->uf; + } + $data []= $info; + } + + $informe->addData($data); + + return $informe->informe(); + } + } else { + setlocale(LC_TIME, 'es_ES'); + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many(); + return view('informes.contabilidad', compact('proyectos')); + } + } + public static function para_comision() + { + $proyectos = model(Proyecto::class)->orderByAsc('descripcion')->findMany(); + return view('informes.para_comision', compact('proyectos')); + } + public static function comisiones() + { + $id = post('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + $unidades = explode('-', str_replace([';', '.', ':', ' ', PHP_EOL, '|', '+', ','], '-', post('unidades'))); + $ventas = model(Venta::class) + ->select('venta.*') + ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad']) + ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal']) + ->where('unidad.proyecto', $proyecto->id) + ->where('venta.estado', 1) + ->whereIn('unidad.descripcion', $unidades) + ->orderByExpr('FIELD(unidad.descripcion, ' . implode(', ', $unidades) . ')') + ->findMany(); + $ids = []; + $totales = (object) ['precio' => 0, 'neto' => 0, 'comision' => 0]; + foreach ($ventas as $venta) { + $ids []= $venta->id; + $totales->precio += $venta->valor_uf; + $totales->neto += $venta->valorCorredora(); + $totales->comision += $venta->valorCorredora() * 1.5 / 100; + } + return view('informes.comisiones', compact('ventas', 'proyecto', 'totales', 'ids')); + } + public static function comisiones_xlsx() + { + $id_ventas = explode(',', get('ventas')); + $ventas = model(Venta::class) + ->whereIn('id', $id_ventas) + ->orderByExpr('FIELD(id, ' . implode(', ', $id_ventas) . ')') + ->findMany(); + + $informe = new Informador('Comisiones - ' . $ventas[0]->proyecto()->descripcion); + $columnas = ['Departamento', 'Estacionamientos', 'Bodegas', 'Propietario', 'Precio', '% Com', 'Com UF']; + $informe->addColumns($columnas); + $data = []; + foreach ($ventas as $venta) { + $info = []; + $info['Departamento'] = $venta->unidad()->descripcion; + $info['Estacionamientos'] = implode(' - ', $venta->propiedad()->estacionamientos('array')); + $info['Bodegas'] = implode(' - ', $venta->propiedad()->bodegas('array')); + $info['Propietario'] = $venta->propietario()->nombreCompleto(); + $info['Precio'] = "'" . format('ufs', $venta->valorCorredora()); + $info['% Com'] = '1,5 %'; + $info['Com UF'] = "'" . format('ufs', $venta->valorCorredora() * 1.5 / 100); + $data []= $info; + } + + $informe->addDatas($data); + + return $informe->informe(); + } + public static function cuotas() + { + $id_venta = get('venta'); + $venta = model(Venta::class)->findOne($id_venta); + + $name = 'Cuotas - ' . $venta->unidad()->descripcion; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $name . ' - ' . $venta->proyecto()->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls'); + $informe = new PHPExcel($name, $filename); + $columnas = [ + ['name' => 'Cuota', 'style' => 'number'], + ['name' => 'Fecha Cuota', 'style' => 'date'], + 'Banco', + 'Identificador', + ['name' => 'Valor $', 'style' => 'number'], + ['name' => 'Valor UF', 'style' => 'currency'], + ['name' => 'Fecha Pago', 'style' => 'date'] + ]; + $informe->addColumns($columnas); + $data = []; + foreach ($venta->pie()->cuotas() as $cuota) { + $info = []; + $info['Cuota'] = $cuota->numero(); + $info['Fecha Cuota'] = $cuota->pago()->fecha()->format('Y-m-d'); + $info['Banco'] = $cuota->pago()->banco()->descripcion; + $info['Identificador'] = $cuota->pago()->identificador; + $info['Valor $'] = $cuota->pago()->valor(); + $info['Valor UF'] = $cuota->pago()->valor('ufs'); + $info['Fecha Pago'] = $cuota->pago()->estado()->fecha()->format('Y-m-d'); + $data []= $info; + } + $informe->addData($data); + + return $informe->informe(); + } + public static function resciliaciones() + { + if (get('proyecto')) { + $id = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + $ventas = $proyecto->resciliaciones(); + + usort($ventas, function($a, $b) { + return $a->fecha()->timestamp - $b->fecha()->timestamp; + }); + + $name = 'Resciliaciones'; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls'); + $informe = new PHPExcel($name, $filename); + + $columnas = [ + 'Propietario', + ['name' => 'Departamento', 'style' => 'number'], + ['name' => 'Estacionamientos', 'style' => 'number'], + ['name' => 'Bodegas', 'style' => 'number'], + 'Fecha Venta', + 'Fecha Resciliación', + ['name' => 'Mes', 'style' => 'mes'], + 'Tipo', + ['name' => 'm² Ponderados', 'style' => 'amount'], + ['name' => 'Valor Promesa', 'style' => 'amount'], + ]; + $informe->addColumns($columnas); + + $data = []; + foreach ($ventas as $venta) { + $info = []; + $info['Propietario'] = mb_strtoupper($venta->propietario()->nombreCompleto()); + $info['Departamento'] = $venta->unidad()->descripcion; + $ests = []; + if ($venta->propiedad()->estacionamientos != '') { + $es = $venta->propiedad()->estacionamientos(); + foreach ($es as $e) { + $ests []= $e->descripcion; + } + } + $info['Estacionamientos'] = implode(', ', $ests); + $bods = []; + if ($venta->propiedad()->bodegas != '') { + $bs = $venta->propiedad()->bodegas(); + foreach ($bs as $b) { + $bods []= $b->descripcion; + } + } + $info['Bodegas'] = implode(', ', $bods); + $info['Fecha Venta'] = $venta->fecha()->format('d.m.Y'); + $info['Fecha Resciliación'] = $venta->estado()->fecha()->format('d.m.Y'); + $info['Mes'] = $venta->estado()->fecha()->format('M-y'); + $info['Tipo'] = $venta->unidad()->abreviacion; + $info['m² Ponderados'] = $venta->unidad()->m2('vendible'); + $info['Valor Promesa'] = $venta->valor_uf; + + $data []= $info; + } + $informe->addData($data); + + $totals = [ + 'Departamento' => 'count', + 'Estacionamientos' => 'count', + 'Bodegas' => 'count', + 'm² Ponderados' => 'sum', + 'Valor Promesa' => 'sum' + ]; + $informe->addTotals($totals); + + return $informe->informe(); + } else { + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many(); + return view('informes.resciliaciones', compact('proyectos')); + } + } +} diff --git a/app/Controller/Informes.php.save b/app/Controller/Informes.php.save new file mode 100644 index 0000000..efd5035 --- /dev/null +++ b/app/Controller/Informes.php.save @@ -0,0 +1,901 @@ +find_one($id_proyecto); + $ini = \Carbon\Carbon::parse($proyecto->estado()->fecha, config('app.timezone')); + #$informe = new Informador('Carta Gantt Proyecto - ' . $proyecto->descripcion); + $name = 'Carta Gantt Proyecto - ' . $proyecto->descripcion; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $name . ' - ' . $hoy->format('Y-m-d') . '.xls'); + $informe = new PHPExcel($name, $filename); + + $columnas = ['Departamento', 'Propietario', 'Entrega', 'Estado']; + $today = \Carbon\Carbon::today(config('app.timezone')); + $end = $today->copy()->addDays(30); + $dif = $end->diffInDays($ini); + for ($i = 0; $i <= $dif; $i ++) { + $f = $ini->copy()->addDays($i); + if ($f->isWeekend()) { + continue; + } + $columnas []= $f->format('Y-m-d'); + } + $informe->addColumns($columnas); + + $data = []; + foreach ($proyecto->entregas() as $venta) { + $info = []; + $info []= $venta->unidad()->descripcion; + $info []= $venta->propietario()->findOne()->nombreCompleto(); + $fe = Carbon::parse($venta->entrega()->find_one()->fecha, config('app.timezone')); + $info []= $fe->format('Y-m-d'); + $info []= ''; + + for ($i = 0; $i <= $dif; $i ++) { + $f = $ini->copy()->addDays($i); + if ($f->isWeekend()) { + continue; + } + if ($f >= $fe and $f <= $fe->copy()->addDays(14)) { + $info []= 'X'; + } else { + $info []= ''; + } + } + + $data []= $info; + } + $informe->addDatas($data); + + return $informe->informe(); + } else { + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many(); + return view('informes.gantt_entregas', compact('proyectos')); + } + } + public static function escrituras() + { + if (get('proyecto')) { + set_time_limit(60); + $id_proyecto = get('proyecto'); + $proyecto = model(Proyecto::class)->find_one($id_proyecto); + + #$informe = new Informador('Escrituras - ' . $proyecto->descripcion); + $name = 'Escrituras'; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls'); + $informe = new PHPExcel($name, $filename); + + $columnas = [ + 'Departamento', + 'Estacionamientos', + 'Bodegas', + 'Propietario', + (object) ['name' => 'Promesa', 'style' => 'number'], + ['name' => 'Bono Pie', 'style' => 'amount'], + ['name' => 'Pie Pagado', 'style' => 'amount'], + ['name' => 'Reajuste', 'style' => 'amount'], + ['name' => 'Abono Contado', 'style' => 'amount'], + ['name' => 'Subsidio', 'style' => 'amount'], + 'Estado Subsidio', + ['name' => 'Credito', 'style' => 'amount'], + 'Banco', + 'Estado Credito', + ['name' => 'Saldo', 'style' => 'amount'], + ['name' => 'Escritura', 'style' => 'amount'], + ['name' => 'Entrega', 'style' => 'date'] + ]; + $informe->addColumns($columnas); + + //$ventas = $proyecto->escrituras(); + $ventas = $proyecto->ventas(); + + $data = []; + foreach ($ventas as $venta) { + $info = []; + $info['Departamento'] = $venta->unidad()->descripcion; + $ests = []; + foreach ($venta->propiedad()->estacionamientos() as $e) { + $ests []= $e->descripcion; + } + $bods = []; + foreach ($venta->propiedad()->bodegas() as $b) { + $bods []= $b->descripcion; + } + $info['Estacionamientos'] = implode(' - ', $ests); + $info['Bodegas'] = implode(' - ', $bods); + $info['Propietario'] = $venta->propietario()->nombreCompleto(); + $info['Promesa'] = $venta->valor_uf; + $saldo = $venta->valor_uf; + $info['Bono Pie'] = ''; + if ($venta->bono_pie != 0) { + $info['Bono Pie'] = $venta->bonoPie()->pago()->valor('ufs'); + $saldo -= $venta->bonoPie()->pago()->valor('ufs'); + } + $info['Pie'] = ''; + $info['Reajuste'] = ''; + if ($venta->pie != 0) { + $info['Pie'] = $venta->pie()->valorPagado(); + $saldo -= $venta->pie()->valorPagado(); + if ($venta->pie()->reajuste != 0) { + $info['Reajuste'] = $venta->pie()->reajuste()->valor('ufs'); + $saldo -= $venta->pie()->reajuste()->valor('ufs'); + } + } + $info['Abono Contado'] = ''; + if ($venta->escritura != 0) { + $info['Abono Contado'] = $venta->escritura()->pago()->valor('ufs'); + $saldo -= $venta->escritura()->pago()->valor('ufs'); + } + $info['Subsidio'] = ''; + $info['Estado Subsidio'] = ''; + if ($venta->subsidio != 0) { + $info['Subsidio'] = $venta->subsidio()->total('ufs'); + $info['Estado Subsidio'] = implode(' - ', [ + $venta->subsidio()->subsidio()->estado()->tipo()->descripcion, + $venta->subsidio()->pago()->estado()->tipo()->descripcion + ]); + $saldo -= $venta->subsidio()->total('ufs'); + } + $info['Credito'] = ''; + $info['Banco'] = ''; + $info['Estado Credito'] = ''; + if ($venta->credito != 0) { + $info['Credito'] = $venta->credito()->pago()->valor('ufs'); + $saldo -= $venta->credito()->pago()->valor('ufs'); + if ($venta->credito()->pago()->banco != 0) { + $info['Banco'] = $venta->credito()->pago()->banco()->nombre; + } + $info['Estado Credito'] = $venta->credito()->pago()->estado()->tipo()->descripcion; + } + $info['Saldo'] = -$saldo; + $info['Escritura'] = ''; + if ($venta->escriturado != 0) { + $info['Escritura'] = $venta->escriturado; + } + $info['Entrega'] = ''; + if ($venta->entregado != 0) { + $info['Entrega'] = $venta->entregado; + } + + $data []= $info; + } + $informe->addData($data); + + return $informe->informe(); + } else { + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many(); + return view('informes.escrituras', compact('proyectos')); + } + } + public static function consolidacion() + { + $id_proyecto = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id_proyecto); + + $ventas = $proyecto->ventas(); + set_time_limit(count($ventas)); + + $f = Carbon::today(config('app.timezone')); + setlocale(LC_TIME, 'es'); + + $data = [ + [$proyecto->descripcion], + [strftime('%d de %B de %Y', $f->timestamp)], + [''], + [''] + ]; + $columns = [ + ['name' => 'Fecha', 'style' => 'date'], + 'Glosa', + ['name' => 'Debe', 'style' => 'number'], + ['name' => 'Haber', 'style' => 'number'], + ['name' => 'Saldo', 'style' => 'number'], + 'Comentario' + ]; + $bold_rows = []; + + foreach ($ventas as $venta) { + $data []= ['Departamento ' . $venta->unidad()->descripcion . ' (' . format('ufs', $venta->valor_uf) . ' UF)']; + $data []= $columns; + $bold_rows []= count($data) - 1; + $ufs = 0; + $debe = 0; + $haber = 0; + $sum = 0; + if ($venta->pie != 0) { + $cuotas = $venta->pie()->cuotas(); + foreach ($cuotas as $cuota) { + $sum += $cuota->pago()->valor(); + $ufs += $cuota->pago()->valor('ufs'); + $haber += $cuota->pago()->valor(); + $info = [ + $cuota->pago()->estado()->fecha, + 'Pie - Cuota ' . $cuota->numero() . ' - ' . $venta->pie()->cuotas . ' (' . format('ufs', $cuota->pago()->valor('ufs')) . ' UF)', + '', + $cuota->pago()->valor(), + $sum + ]; + if ($cuota->pago()->estado()->estado < 2) { + $info []= 'No ha sido abonada.'; + } + $data []= $info; + } + if ($venta->pie()->reajuste != 0) { + $sum += $venta->pie()->reajuste()->valor(); + $ufs += $venta->pie()->reajuste()->valor('ufs'); + $haber += $venta->pie()->reajuste()->valor(); + $info = [ + $venta->pie()->reajuste()->estado()->fecha, + 'Reajuste (' . format('ufs', $venta->pie()->reajuste()->valor('ufs')) . ' UF)', + '', + $venta->pie()->reajuste()->valor(), + $sum + ]; + if ($venta->pie()->reajuste()->estado()->estado < 2) { + $info []= 'No ha sido abonado.'; + } + $data []= $info; + } + } + if ($venta->escritura != 0) { + $sum += $venta->escritura()->pago()->valor(); + $ufs += $venta->escritura()->pago()->valor('ufs'); + $haber += $venta->escritura()->pago()->valor(); + $info = [ + $venta->escritura()->pago()->estado()->fecha, + 'Abono Escritura (' . format('ufs', $venta->escritura()->pago()->valor('ufs')) . ' UF)', + '', + $venta->escritura()->pago()->valor(), + $sum + ]; + if ($venta->escritura()->pago()->estado()->estado < 2) { + $info []= 'No ha sido abonado.'; + } + $data []= $info; + } + if ($venta->credito != 0) { + $sum += $venta->credito()->pago()->valor(); + $ufs += $venta->credito()->pago()->valor('ufs'); + $haber += $venta->credito()->pago()->valor(); + $info = [ + $venta->credito()->pago()->estado()->fecha, + 'Crédito (' . format('ufs', $venta->credito()->pago()->valor('ufs')) . ' UF)', + '', + $venta->credito()->pago()->valor(), + $sum + ]; + if ($venta->credito()->pago()->estado()->estado < 2) { + $info []= 'No ha sido pagado.'; + } + $data []= $info; + } + if ($venta->bono_pie != 0) { + try { + $sum -= $venta->bonoPie()->pago()->valor(); + $debe += $venta->bonoPie()->pago()->valor(); + $info = [ + $venta->bonoPie()->pago()->estado()->fecha, + 'Bono Pie (' . format('ufs', $venta->bonoPie()->pago()->valor('ufs')) . ' UF)'. + $venta->bonoPie()->pago()->valor(), + '', + $sum + ]; + $data []= $info; + $sum += $venta->bonoPie()->pago()->valor(); + $haber += $venta->bonoPie()->pago()->valor(); + $info = [ + $venta->bonoPie()->pago()->estado()->fecha, + 'Bono Pie (' . format('ufs', $venta->bonoPie()->pago()->valor('ufs')) . ' UF)'. + '', + $venta->bonoPie()->pago()->valor(), + $sum + ]; + $data []= $info; + } catch (\Exception $e) { + + } + } + $info = [ + '', + 'TOTAL (' . format('ufs', $ufs) . ' UF)', + $debe, + $haber, + $sum + ]; + $data []= $info; + $bold_rows []= count($data) - 1; + + $data []= ['']; + } + /** + * Departamento # + * Fecha |Glosa |Debe |Haber |Saldo + * |Pie - Cuota 1 - n (# UF) |- |$# | + * |Reajuste (# UF) |- |$# | + * |Abono Escritura (# UF) |- |$# | + * |Crédito (# UF) |- |$# | + * |Bono Pie (# UF) |$# |- | + * |Bono Pie (# UF) |- |$# | + * |Devolución (# UF) |$# |- | + * - |TOTAL (# UF) | | | + */ + + array_walk($data, function(&$e, $i) use ($columns) { + if (count($e) < count($columns)) { + $n = count($columns) - count($e); + for ($j = 0; $j < $n; $j ++) { + $e []= ''; + } + } + }); + + #$informe = new Informador('Consolidación - ' . $proyecto->descripcion); + $name = 'Consolidación'; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls'); + $informe = new PHPExcel($name, $filename); + $informe->addColumns($columns); + $informe->addData($data); + + return $informe->informe(); + } + public static function creditos_pendientes() + { + function creditos() { + $creditos = model(Credito::class) + ->select('credito.*') + ->join('venta', ['venta.credito', '=', 'credito.id']) + ->join('pago', ['pago.id', '=', 'credito.pago']) + ->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') + ->whereLt('estado_pago.estado', 2) + ->where('venta.estado', 1) + ->orderByAsc('estado_pago.fecha') + ->findMany(); + foreach ($creditos as $credito) { + yield $credito; + } + } + $informe = new Informador('Créditos Pendientes'); + + $columnas = ['Proyecto', 'Departamento', 'Valor', 'Fecha Escritura', 'Estado']; + $informe->addColumns($columnas); + + $row = 0; + foreach (creditos() as $credito) { + $informe->addData($row, $credito->venta()->proyecto()->descripcion, 'Proyecto'); + $informe->addData($row, $credito->venta()->unidad()->descripcion, 'Departamento'); + $informe->addData($row, $credito->pago()->valor('ufs'), 'Valor'); + $informe->addData($row, (($credito->venta()->escriturado) ? $credito->venta()->escriturado : $credito->pago()->estado()->fecha), 'Fecha Escritura'); + $informe->addData($row, ucwords($credito->pago()->estado()->tipo()->descripcion), 'Estado'); + + $row ++; + } + + $date = [ + 'numberFormat' => ['short-date'] + ]; + $ufs = [ + 'numberFormat' => ['thousands'] + ]; + $formats = ['Valor' => $ufs, 'Fecha Escritura' => $date]; + $informe->addFormats($formats); + + return $informe->informe(); + } + public static function ventas() + { + if (get('proyecto')) { + $id = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + $ventas = $proyecto->ventas(); + + usort($ventas, function($a, $b) { + return $a->fecha()->timestamp - $b->fecha()->timestamp; + }); + + $procasa = model(Agente::class)->findOne(1); + $pa = model(ProyectoAgente::class)->where('agente', $procasa->id)->where('proyecto', $proyecto->id)->findOne(); + if ($pa) { + $comision = $pa->comision / 100; + } else { + $comision = 0.03; + } + + #$informe = new Informador('Ventas - ' . $proyecto->descripcion); + $name = 'Ventas'; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls'); + $informe = new PHPExcel($name, $filename); + + $columnas = [ + 'Propietario', + ['name' => 'Departamento', 'style' => 'number'], + ['name' => 'Estacionamientos', 'style' => 'number'], + ['name' => 'Bodegas', 'style' => 'number'], + 'Fecha Venta', + ['name' => 'Mes', 'style' => 'mes'], + 'Tipo', + ['name' => 'm² Ponderados', 'style' => 'amount'], + ['name' => 'Valor Promesa', 'style' => 'amount'], + ['name' => 'Bono Pie', 'style' => 'amount'], + 'Operador', + ['name' => 'Valor Operador', 'style' => 'amount'], + ['name' => 'Premios', 'style' => 'amount'], + ['name' => 'Subsidio', 'style' => 'amount'], + ['name' => 'Ahorro', 'style' => 'amount'], + ['name' => 'Credito', 'style' => 'amount'], + 'Banco', + ['name' => 'Valor Ests & Bods', 'style' => 'amount'], + ['name' => 'Valor Neto', 'style' => 'amount'], + ['name' => 'UF/m²*', 'style' => 'amount'], + ['name' => 'Comision', 'style' => 'amount'], + ['name' => 'Venta s/Comision', 'style' => 'amount'] + ]; + $informe->addColumns($columnas); + + $data = []; + foreach ($ventas as $venta) { + $info = []; + $info['Propietario'] = mb_strtoupper($venta->propietario()->nombreCompleto()); + $info['Departamento'] = $venta->unidad()->descripcion; + $ests = []; + if ($venta->propiedad()->estacionamientos != '') { + $es = $venta->propiedad()->estacionamientos(); + foreach ($es as $e) { + $ests []= $e->descripcion; + } + } + $info['Estacionamientos'] = implode(', ', $ests); + $bods = []; + if ($venta->propiedad()->bodegas != '') { + $bs = $venta->propiedad()->bodegas(); + foreach ($bs as $b) { + $bods []= $b->descripcion; + } + } + $info['Bodegas'] = implode(', ', $bods); + $info['Fecha Venta'] = $venta->fecha()->format('d.m.Y'); + $info['Mes'] = $venta->fecha()->format('M-y'); + $info['Tipo'] = $venta->unidad()->abreviacion; + $info['m² Ponderados'] = $venta->unidad()->m2('vendible'); + $info['Valor Promesa'] = $venta->valor_uf; + $info['Bono Pie'] = ($venta->bono_pie == 0 or $venta->bonoPie() === false) ? '' : $venta->bonoPie()->pago()->valor('ufs'); + $info['Operador'] = ($venta->agente and $venta->agente()->agente()->tipo == 19) ? $venta->agente()->agente()->descripcion : ''; + $info['Valor Operador'] = $venta->valorComision(); + $promos = 0; + $ps = $venta->promociones(); + if (count($ps) > 0) { + foreach ($ps as $promo) { + $promos += $promo->valor; + } + } + $info['Premios'] = $promos; + $info['Subsidio'] = 0; + $info['Ahorro'] = 0; + if ($venta->subsidio != 0) { + $info['Subsidio'] = $venta->subsidio()->subsidio()->valor('ufs'); + $info['Ahorro'] = $venta->subsidio()->pago()->valor('ufs'); + } + $info['Credito'] = 0; + $info['Banco'] = ''; + if ($venta->credito != 0) { + $info['Credito'] = $venta->credito()->pago()->valor('ufs'); + if ($venta->credito()->pago()->banco != 0) { + $info['Banco'] = $venta->credito()->pago()->banco()->nombre; + } + } + $info['Valor Ests & Bods'] = $venta->valorEstacionamientosYBodegas(); + $info['Valor Neto'] = $venta->valorFinal(); + $info['UF/m²*'] = $venta->uf_m2(); + $info['Comision'] = $venta->valorFinal() * $comision; + $info['Venta s/Comision'] = $venta->valorFinal() - $info['Comision']; + + $data []= $info; + } + $informe->addData($data); + + $totals = [ + 'Propietario' => 'TOTAL', + 'Departamento' => 'count', + 'Estacionamientos' => 'count', + 'Bodegas' => 'count', + 'm² Ponderados' => 'sum', + 'Valor Promesa' => 'sum', + 'Bono Pie' => 'sum', + 'Subsidio' => 'sum', + 'Ahorro' => 'sum', + 'Credito' => 'sum', + 'Valor Operador' => 'sum', + 'Premios' => 'sum', + 'Valor Ests & Bods' => 'sum', + 'Valor Neto' => 'sum', + 'Comision' => 'sum' + ]; + $informe->addTotals($totals); + + return $informe->informe(); + } else { + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many(); + return view('informes.ventas', compact('proyectos')); + } + } + public static function resumen_contabilidad() + { + if (get('proyecto')) { + $id = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + $ventas = $proyecto->ventas(); + + usort($ventas, function($a, $b) { + return $a->fecha()->timestamp - $b->fecha()->timestamp; + }); + + $name = 'Ventas'; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls'); + $informe = new PHPExcel($name, $filename); + + $columnas = [ + 'Propietario', + ['name' => 'Departamento', 'style' => 'general_number'], + ['name' => 'Estacionamientos', 'style' => 'number'], + ['name' => 'Bodegas', 'style' => 'number'], + 'Fecha Venta', + ['name' => 'Mes', 'style' => 'mes'], + 'Tipo', + ['name' => 'm² Ponderados', 'style' => 'amount'], + ['name' => 'Valor Promesa', 'style' => 'amount'], + ['name' => 'Pie [UF]', 'style' => 'amount'], + ['name' => 'Pie [$]', 'style' => 'amount'], + ['name' => 'Abono Escritura', 'style' => 'amount'], + ['name' => 'Crédito', 'style' => 'amount'], + ['name' => 'Cuotas', 'style' => 'number'], + ['name' => 'Cuotas Pagadas', 'style' => 'number'], + ['name' => 'Pie Pagado [UF]', 'style' => 'amount'], + ['name' => 'Pie Pagado [$]', 'style' => 'amount'] + ]; + $informe->addColumns($columnas); + + $data = []; + foreach ($ventas as $venta) { + $info = []; + $info['Propietario'] = mb_strtoupper($venta->propietario()->nombreCompleto()); + $info['Departamento'] = $venta->unidad()->descripcion; + $ests = []; + if ($venta->propiedad()->estacionamientos != '') { + $es = $venta->propiedad()->estacionamientos(); + foreach ($es as $e) { + $ests []= $e->descripcion; + } + } + $info['Estacionamientos'] = implode(', ', $ests); + $bods = []; + if ($venta->propiedad()->bodegas != '') { + $bs = $venta->propiedad()->bodegas(); + foreach ($bs as $b) { + $bods []= $b->descripcion; + } + } + $info['Bodegas'] = implode(', ', $bods); + $info['Fecha Venta'] = $venta->fecha()->format('d.m.Y'); + $info['Mes'] = $venta->fecha()->format('M-y'); + $info['Tipo'] = $venta->unidad()->abreviacion; + $info['m² Ponderados'] = $venta->unidad()->m2('vendible'); + $info['Valor Promesa'] = $venta->valor_uf; + $info['Pie [UF]'] = 0; + $info['Pie [$]'] = 0; + if ($venta->pie()) { + $info['Pie [UF]'] = $venta->pie()->valor; + $info['Pie [$]'] = $venta->pie()->valorPesos(); + } + $info['Abono Escritura'] = ($venta->escritura != 0) ? $venta->escritura()->valor('ufs') : ($venta->valor_uf - $venta->pie()->valor - (($venta->credito != 0) ? $venta->credito()->pago()->valor('ufs') : 0)); + $info['Crédito'] = ($venta->credito != 0) ? $venta->credito()->pago()->valor('ufs') : 0; + + $info['Cuotas'] = $venta->pie()->cuotas; + $info['Cuotas Pagadas'] = count($venta->pie()->pagadas()); + $info['Pie Pagado [UF]'] = $venta->pie()->valorPagado('uf'); + $info['Pie Pagado [$]'] = $venta->pie()->valorPagado('pesos'); + + $data []= $info; + } + $informe->addData($data); + + $totals = [ + 'Departamento' => 'count', + 'Estacionamientos' => 'count', + 'Bodegas' => 'count', + 'm² Ponderados' => 'sum', + 'Valor Promesa' => 'sum', + 'Pie' => 'sum', + 'Pie Pagado' => 'sum' + ]; + $informe->addTotals($totals); + + return $informe->informe(); + } else { + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many(); + return view('informes.resumen_contabilidad', compact('proyectos')); + } + } + public static function contabilidad() + { + if (get('proyecto')) { + $id = get('proyecto'); + $fecha = get('fecha'); + $mes = null; + if ($fecha != null) { + $mes = Carbon::parse($fecha); + } + $proyecto = model(Proyecto::class)->findOne($id); + $q = "SELECT pago.*, venta.id AS vid, venta.tipo AS ctipo, venta.pie AS pie + FROM ( + SELECT pago.id, banco.nombre AS banco, pago.fecha, pago.valor, pago.uf, ep.estado, ep.fecha AS efecha + FROM pago JOIN banco ON banco.id = pago.banco JOIN (( + SELECT pago, MAX(id) AS id FROM estado_pago GROUP BY pago) e0 JOIN estado_pago ep ON ep.id = e0.id) ON ep.pago = pago.id + WHERE ep.estado > 0 "; + if ($mes != null) { + $q .= "AND (pago.fecha BETWEEN '" . $mes->format('Y-m-01') . "' AND '" . $mes->format('Y-m-t') . "' + OR ep.fecha BETWEEN '" . $mes->format('Y-m-01') . "' AND '" . $mes->format('Y-m-t') . "')"; + } + $q .= ") pago JOIN (SELECT venta.* + FROM (( + SELECT venta.id, venta.pie, venta.propiedad, credito.pago, 'credito' AS tipo + FROM venta JOIN credito ON credito.id = venta.credito) + UNION ALL ( + SELECT venta.id, venta.pie, venta.propiedad, escritura.pago, 'escritura' AS tipo + FROM venta JOIN escritura ON escritura.id = venta.escritura) + UNION ALL ( + SELECT venta.id, venta.pie, venta.propiedad, cuota.pago, 'cuota' AS tipo + FROM venta JOIN cuota ON cuota.pie = venta.pie)) venta + JOIN propiedad ON propiedad.id = venta.propiedad + JOIN unidad ON unidad.id = propiedad.unidad_principal + WHERE unidad.proyecto = ?) venta + ON venta.pago = pago.id"; + $st = \ORM::getDB()->prepare($q); + $st->execute([$id]); + if ($st->rowCount() > 0) { + $R = $st->fetchAll(\PDO::FETCH_OBJ); + + #$informe = new Informador('Contabilidad - ' . (($mes != null) ? $mes->format('Y-m') . ' - ' : '') . $proyecto->descripcion); + $name = 'Contabilidad'; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', 'Contabilidad - ' . (($mes != null) ? $mes->format('Y-m') . ' - ' : '') . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls'); + + $informe = new PHPExcel($name, $filename); + + $columnas = ['Proyecto', 'Fecha', 'Banco', 'Departamento', 'RUT', 'Propietario', 'Glosa', 'Glosa2', (object) ['name' => 'Valor', 'style' => 'integer'], (object) ['name' => 'Valor UF', 'style' => 'currency']]; + $informe->addColumns($columnas); + $data = []; + foreach ($R as $r) { + $info = []; + $info['Proyecto'] = $proyecto->descripcion; + $f1 = \Carbon\Carbon::parse($r->fecha, config('app.timezone')); + $f2 = \Carbon\Carbon::parse($r->efecha, config('app.timezone')); + $info['Fecha'] = ($f1->max($f2))->format('Y-m-d'); + $info['Banco'] = $r->banco; + $venta = model(Venta::class)->findOne($r->vid); + $info['Departamento'] = $venta->unidad()->descripcion; + $info['RUT'] = $venta->propietario()->rut(); + $info['Propietario'] = $venta->propietario()->nombreCompleto(); + $info['Glosa'] = ucwords($r->ctipo); + $info['Glosa2'] = ''; + if ($r->ctipo == 'cuota') { + $cuota = model(Cuota::class)->where('pago', $r->id)->findOne(); + + $info['Glosa'] = 'Pie - ' . format('ufs', $cuota->pie()->valor('ufs'), null, true); + + $info['Glosa2'] = $cuota->numero() . ' - ' . $cuota->pie()->cuotas; + } + $info['Valor'] = $r->valor; + $info['Valor UF'] = '0'; + if ($r->uf > 0) { + $info['Valor UF'] = $r->valor / $r->uf; + } + $data []= $info; + } + + $informe->addData($data); + + return $informe->informe(); + } + } else { + setlocale(LC_TIME, 'es'); + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many(); + return view('informes.contabilidad', compact('proyectos')); + } + } + public static function para_comision() + { + $proyectos = model(Proyecto::class)->orderByAsc('descripcion')->findMany(); + return view('informes.para_comision', compact('proyectos')); + } + public static function comisiones() + { + $id = post('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + $unidades = explode('-', str_replace([';', '.', ':', ' ', PHP_EOL, '|', '+', ','], '-', post('unidades'))); + $ventas = model(Venta::class) + ->select('venta.*') + ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad']) + ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal']) + ->where('unidad.proyecto', $proyecto->id) + ->where('venta.estado', 1) + ->whereIn('unidad.descripcion', $unidades) + ->orderByExpr('FIELD(unidad.descripcion, ' . implode(', ', $unidades) . ')') + ->findMany(); + $ids = []; + $totales = (object) ['precio' => 0, 'neto' => 0, 'comision' => 0]; + foreach ($ventas as $venta) { + $ids []= $venta->id; + $totales->precio += $venta->valor_uf; + $totales->neto += $venta->valorCorredora(); + $totales->comision += $venta->valorCorredora() * 1.5 / 100; + } + return view('informes.comisiones', compact('ventas', 'proyecto', 'totales', 'ids')); + } + public static function comisiones_xlsx() + { + $id_ventas = explode(',', get('ventas')); + $ventas = model(Venta::class) + ->whereIn('id', $id_ventas) + ->orderByExpr('FIELD(id, ' . implode(', ', $id_ventas) . ')') + ->findMany(); + + $informe = new Informador('Comisiones - ' . $ventas[0]->proyecto()->descripcion); + $columnas = ['Departamento', 'Estacionamientos', 'Bodegas', 'Propietario', 'Precio', '% Com', 'Com UF']; + $informe->addColumns($columnas); + $data = []; + foreach ($ventas as $venta) { + $info = []; + $info['Departamento'] = $venta->unidad()->descripcion; + $info['Estacionamientos'] = implode(' - ', $venta->propiedad()->estacionamientos('array')); + $info['Bodegas'] = implode(' - ', $venta->propiedad()->bodegas('array')); + $info['Propietario'] = $venta->propietario()->nombreCompleto(); + $info['Precio'] = "'" . format('ufs', $venta->valorCorredora()); + $info['% Com'] = '1,5 %'; + $info['Com UF'] = "'" . format('ufs', $venta->valorCorredora() * 1.5 / 100); + $data []= $info; + } + + $informe->addDatas($data); + + return $informe->informe(); + } + public static function cuotas() + { + $id_venta = get('venta'); + $venta = model(Venta::class)->findOne($id_venta); + + $name = 'Cuotas - ' . $venta->unidad()->descripcion; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $name . ' - ' . $venta->proyecto()->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls'); + $informe = new PHPExcel($name, $filename); + $columnas = [ + ['name' => 'Cuota', 'style' => 'number'], + ['name' => 'Fecha Cuota', 'style' => 'date'], + 'Banco', + 'Identificador', + ['name' => 'Valor $', 'style' => 'number'], + ['name' => 'Valor UF', 'style' => 'currency'], + ['name' => 'Fecha Pago', 'style' => 'date'] + ]; + $informe->addColumns($columnas); + $data = []; + foreach ($venta->pie()->cuotas() as $cuota) { + $info = []; + $info['Cuota'] = $cuota->numero(); + $info['Fecha Cuota'] = $cuota->pago()->fecha()->format('Y-m-d'); + $info['Banco'] = $cuota->pago()->banco()->descripcion; + $info['Identificador'] = $cuota->pago()->identificador; + $info['Valor $'] = $cuota->pago()->valor(); + $info['Valor UF'] = $cuota->pago()->valor('ufs'); + $info['Fecha Pago'] = $cuota->pago()->estado()->fecha()->format('Y-m-d'); + $data []= $info; + } + $informe->addData($data); + + return $informe->informe(); + } + public static function resciliaciones() + { + if (get('proyecto')) { + $id = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + $ventas = $proyecto->resciliaciones(); + + usort($ventas, function($a, $b) { + return $a->fecha()->timestamp - $b->fecha()->timestamp; + }); + + $name = 'Resciliaciones'; + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls'); + $informe = new PHPExcel($name, $filename); + + $columnas = [ + 'Propietario', + ['name' => 'Departamento', 'style' => 'number'], + ['name' => 'Estacionamientos', 'style' => 'number'], + ['name' => 'Bodegas', 'style' => 'number'], + 'Fecha Venta', + 'Fecha Resciliación', + ['name' => 'Mes', 'style' => 'mes'], + 'Tipo', + ['name' => 'm² Ponderados', 'style' => 'amount'], + ['name' => 'Valor Promesa', 'style' => 'amount'], + ]; + $informe->addColumns($columnas); + + $data = []; + foreach ($ventas as $venta) { + $info = []; + $info['Propietario'] = mb_strtoupper($venta->propietario()->nombreCompleto()); + $info['Departamento'] = $venta->unidad()->descripcion; + $ests = []; + if ($venta->propiedad()->estacionamientos != '') { + $es = $venta->propiedad()->estacionamientos(); + foreach ($es as $e) { + $ests []= $e->descripcion; + } + } + $info['Estacionamientos'] = implode(', ', $ests); + $bods = []; + if ($venta->propiedad()->bodegas != '') { + $bs = $venta->propiedad()->bodegas(); + foreach ($bs as $b) { + $bods []= $b->descripcion; + } + } + $info['Bodegas'] = implode(', ', $bods); + $info['Fecha Venta'] = $venta->fecha()->format('d.m.Y'); + $info['Fecha Resciliación'] = $venta->estado()->fecha()->format('d.m.Y'); + $info['Mes'] = $venta->estado()->fecha()->format('M-y'); + $info['Tipo'] = $venta->unidad()->abreviacion; + $info['m² Ponderados'] = $venta->unidad()->m2('vendible'); + $info['Valor Promesa'] = $venta->valor_uf; + + $data []= $info; + } + $informe->addData($data); + + $totals = [ + 'Departamento' => 'count', + 'Estacionamientos' => 'count', + 'Bodegas' => 'count', + 'm² Ponderados' => 'sum', + 'Valor Promesa' => 'sum' + ]; + $informe->addTotals($totals); + + return $informe->informe(); + } else { + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many(); + return view('informes.resciliaciones', compact('proyectos')); + } + } +} diff --git a/app/Controller/Inmobiliarias.php b/app/Controller/Inmobiliarias.php new file mode 100644 index 0000000..f0b8910 --- /dev/null +++ b/app/Controller/Inmobiliarias.php @@ -0,0 +1,74 @@ +orderByAsc('abreviacion')->findMany(); + return view('inmobiliarias.list', compact('inmobiliarias')); + } + public static function show() + { + $rut = get('rut'); + $inmobiliaria = model(Inmobiliaria::class)->findOne($rut); + return view('inmobiliarias.show', compact('inmobiliaria')); + } + public static function add() + { + $sociedades = model(TipoSociedad::class)->findMany(); + return view('inmobiliarias.add', compact('sociedades')); + } + public static function agregar() + { + list($rut, $dv) = explode('-', str_replace('.', '', post('rut'))); + + $inmobiliaria = model(Inmobiliaria::class)->findOne($rut); + if ($inmobiliaria) { + header('Location: ' . url('', ['p' => 'inmobiliarias', 'a' => 'show', 'rut' => $inmobiliaria->rut])); + die(); + } + + $inmobiliaria = model(Inmobiliaria::class)->create(); + $inmobiliaria->rut = $rut; + $inmobiliaria->dv = $dv; + $inmobiliaria->razon = post('razon'); + $inmobiliaria->abreviacion = post('abrev'); + $inmobiliaria->sociedad = post('sociedad'); + + $inmobiliaria->save(); + header('Location: ' . url('', ['p' => 'inmobiliarias', 'a' => 'show', 'rut' => $inmobiliaria->rut])); + } + public static function edit() + { + $sociedades = model(TipoSociedad::class)->findMany(); + $rut = get('rut'); + $inmobiliaria = model(Inmobiliaria::class)->findOne($rut); + $bancos = model(Banco::class)->findMany(); + usort($bancos, function($a, $b) { + return strcmp($a->nombre, $b->nombre); + }); + return view('inmobiliarias.edit', compact('inmobiliaria', 'bancos', 'sociedades')); + } + public static function do_edit() + { + $rut = get('rut'); + $inmobiliaria = model(Inmobiliaria::class)->findOne($rut); + foreach (post() as $field => $value) { + if ($value != '' and $inmobiliaria->{$field} != $value) { + $inmobiliaria->{$field} = $value; + } + } + + $inmobiliaria->save(); + header('Location: ' . nUrl('inmobiliarias', 'show', ['rut' => $inmobiliaria->rut])); + } +} +?> diff --git a/app/Controller/Operadores.php b/app/Controller/Operadores.php new file mode 100644 index 0000000..765ba2a --- /dev/null +++ b/app/Controller/Operadores.php @@ -0,0 +1,47 @@ +findOne(get('proyecto')); + $operadores = model(Agente::class) + ->select('agente.*') + ->join('agente_tipo', ['agente_tipo.agente', '=', 'agente.id']) + ->join('tipo_agente', ['tipo_agente.id', '=', 'agente_tipo.tipo']) + ->where('tipo_agente.descripcion', 'operador') + ->orderByAsc('agente.abreviacion') + ->findMany(); + $vigentes = array_map(function($item) { + return $item->agente()->agente(); + }, $proyecto->operadoresVigentes()); + echo view('proyectos.operadores.add', compact('proyecto', 'operadores', 'vigentes')); + } + public static function add() + { + $proyecto = model(Proyecto::class)->findOne(get('proyecto')); + $fecha = Carbon::today(config('app.timezone')); + foreach (post('operadores') as $op) { + $operador = model(Agente::class)->findOne($op); + $at = $operador->tipos(19); + $data = [ + 'proyecto' => $proyecto->id, + 'agente' => $at->id, + 'fecha' => $fecha->format('Y-m-d'), + 'comision' => 2 + ]; + $pa = model(ProyectoAgente::class)->create($data); + $pa->new(); + } + header('Location: ' . nUrl('proyectos', 'show', ['proyecto' => $proyecto->id])); + } +} diff --git a/app/Controller/Other.php b/app/Controller/Other.php new file mode 100644 index 0000000..eb90f31 --- /dev/null +++ b/app/Controller/Other.php @@ -0,0 +1,71 @@ +create(); + $unidad = \Model::factory(Unidad::class)->where('descripcion', $info[0])->where('proyecto', post('proyecto'))->find_one(); + if (!$unidad->venta()->find_one()) { + echo 'x'; + continue; + } + $venta = $unidad->venta()->find_one(); + $entrega->fecha = \Carbon\Carbon::parse($info[1])->format('Y-m-d'); + if ($venta->entrega == '0') { + $entrega->save(); + $venta->entrega = $entrega->id; + $venta->save(); + echo '.'; + } else { + echo 'x'; + } + } + } else { + $proyectos = \Model::factory(Proyecto::class)->order_by_asc('descripcion')->find_many(); + return view('other.entregar_multiple', compact('proyectos')); + } + } + public static function capacidades() + { + $capacidades = []; + $controllers = glob(config('locations.app') . '/Controller/*.php'); + foreach ($controllers as $controller) { + if (basename($controller) == 'Admin.php' or basename($controller) == 'Other.php') { + continue; + } + $class = Stringy::create($controller)->replace(config('locations.app'), '/App')->replace('.php', '')->replace('/', '\\')->__toString(); + $ref = new \ReflectionClass($class); + $static = $ref->getMethods(\ReflectionMethod::IS_STATIC && \ReflectionMethod::IS_PUBLIC); + foreach ($static as $method) { + if ($method->name == 'setDefault' or $method->name == 'index') { + continue; + } + $capacidades []= $method; + } + } + return view('other.capacidades', compact('capacidades')); + } +} +?> \ No newline at end of file diff --git a/app/Controller/Pagares.php b/app/Controller/Pagares.php new file mode 100644 index 0000000..f05b24e --- /dev/null +++ b/app/Controller/Pagares.php @@ -0,0 +1,271 @@ +findOne(get('pagare')); + return view('proyectos.pagares.show', compact('pagare')); + } + public static function add() + { + $proyecto = model(Proyecto::class)->findOne(get('proyecto')); + return view('proyectos.pagares.add', compact('proyecto')); + } + public static function do_add() + { + $proyecto = model(Proyecto::class)->findOne(get('proyecto')); + $data = post(); + + $data['id'] = $data['numero']; + unset($data['numero']); + $data['proyecto'] = $proyecto->id; + $moneda = model(TipoMonedaPagare::class)->where('descripcion', $data['moneda'])->findOne(); + $data['moneda'] = $moneda->id; + + $fecha = ['year', 'month', 'day']; + $fecha_arr = array_filter($data, function($item) use ($fecha) { + return (array_search($item, $fecha) !== false); + }, \ARRAY_FILTER_USE_KEY); + uksort($fecha_arr, function($a, $b) use ($fecha) { + return array_search($a, $fecha) - array_search($b, $fecha); + }); + foreach ($fecha as $f) { + unset($data[$f]); + } + array_walk($fecha_arr, function(&$item) { + if (strlen($item) < 4) { + $item = str_pad($item, 2, '0', \STR_PAD_LEFT); + } + }); + $data['fecha'] = implode('-', $fecha_arr); + + foreach ($fecha as &$key) { + $key .= '_banco'; + } + $fecha_arr = array_filter($data, function($item) use ($fecha) { + return (array_search($item, $fecha) !== false); + }, \ARRAY_FILTER_USE_KEY); + uksort($fecha_arr, function($a, $b) use ($fecha) { + return array_search($a, $fecha) - array_search($b, $fecha); + }); + foreach ($fecha as $f) { + unset($data[$f]); + } + array_walk($fecha_arr, function(&$item) { + if (strlen($item) < 4) { + $item = str_pad($item, 2, '0', \STR_PAD_LEFT); + } + }); + $data['fecha_banco'] = implode('-', $fecha_arr); + + $data['abonado'] = (int) $data['abonado']; + if ($data['abonado'] == 0) { + $data['fecha'] = '0000-00-00'; + } + + $pagare = model(Pagare::class)->create($data); + $pagare->save(); + header('Location: ' . nUrl('pagares', 'show', ['pagare' => $pagare->id])); + } + public static function edit() + { + $pagare = model(Pagare::class)->findOne(get('pagare')); + return view('proyectos.pagares.edit', compact('pagare')); + } + public static function do_edit() + { + $pagare = model(Pagare::class)->findOne(get('pagare')); + + $data = post(); + if ($pagare->id != $data['numero']) { + foreach ($pagare->renovaciones() as $renovacion) { + $renovacion->pagare = $data['numero']; + $renovacion->save(); + } + $pagare->id = $data['numero']; + $changed = true; + } + unset($data['numero']); + $moneda = model(TipoMonedaPagare::class)->where('descripcion', $data['moneda'])->findOne(); + $data['moneda'] = $moneda->id; + $fecha = ['year', 'month', 'day']; + $fecha_arr = array_filter($data, function($item) use ($fecha) { + return (array_search($item, $fecha) !== false); + }, \ARRAY_FILTER_USE_KEY); + uksort($fecha_arr, function($a, $b) use ($fecha) { + return array_search($a, $fecha) - array_search($b, $fecha); + }); + foreach ($fecha as $f) { + unset($data[$f]); + } + array_walk($fecha_arr, function(&$item) { + if (strlen($item) < 4) { + $item = str_pad($item, 2, '0', \STR_PAD_LEFT); + } + }); + $data['fecha'] = implode('-', $fecha_arr); + + foreach ($fecha as &$key) { + $key .= '_banco'; + } + $fecha_arr = array_filter($data, function($item) use ($fecha) { + return (array_search($item, $fecha) !== false); + }, \ARRAY_FILTER_USE_KEY); + uksort($fecha_arr, function($a, $b) use ($fecha) { + return array_search($a, $fecha) - array_search($b, $fecha); + }); + foreach ($fecha as $f) { + unset($data[$f]); + } + array_walk($fecha_arr, function(&$item) { + if (strlen($item) < 4) { + $item = str_pad($item, 2, '0', \STR_PAD_LEFT); + } + }); + $data['fecha_banco'] = implode('-', $fecha_arr); + + $data['abonado'] = (int) $data['abonado']; + if ($data['abonado'] == 0) { + $data['fecha'] = '0000-00-00'; + } + + $changed = false; + foreach ($data as $k => $v) { + if ($pagare->$k != $v) { + $pagare->$k = $v; + $changed = true; + if (strpos($k, 'fecha') !== false) { + $pagare->uf = 0; + } + } + } + + if ($changed) { + $pagare->save(); + } + header('Location: ' . nUrl('pagares', 'show', ['pagare' => $pagare->id])); + } + public static function edit_renovacion() + { + $renovacion = model(RenovacionPagare::class)->findOne(get('renovacion')); + return view('proyectos.pagares.edit_renovacion', compact('renovacion')); + } + public static function do_edit_renovacion() + { + $renovacion = model(RenovacionPagare::class)->findOne(get('renovacion')); + + $data = post(); + $fecha = ['year', 'month', 'day']; + $fecha_arr = array_filter($data, function($item) use ($fecha) { + return (array_search($item, $fecha) !== false); + }, \ARRAY_FILTER_USE_KEY); + uksort($fecha_arr, function($a, $b) use ($fecha) { + return array_search($a, $fecha) - array_search($b, $fecha); + }); + foreach ($fecha as $f) { + unset($data[$f]); + } + array_walk($fecha_arr, function(&$item) { + if (strlen($item) < 4) { + $item = str_pad($item, 2, '0', \STR_PAD_LEFT); + } + }); + $data['fecha'] = implode('-', $fecha_arr); + + foreach ($fecha as &$key) { + $key .= '_banco'; + } + $fecha_arr = array_filter($data, function($item) use ($fecha) { + return (array_search($item, $fecha) !== false); + }, \ARRAY_FILTER_USE_KEY); + uksort($fecha_arr, function($a, $b) use ($fecha) { + return array_search($a, $fecha) - array_search($b, $fecha); + }); + foreach ($fecha as $f) { + unset($data[$f]); + } + array_walk($fecha_arr, function(&$item) { + if (strlen($item) < 4) { + $item = str_pad($item, 2, '0', \STR_PAD_LEFT); + } + }); + $data['fecha_banco'] = implode('-', $fecha_arr); + + $changed = false; + foreach ($data as $k => $v) { + if ($renovacion->$k != $v) { + $renovacion->$k = $v; + $changed = true; + if (strpos($k, 'fecha') !== false) { + $renovacion->uf = 0; + } + } + } + if ($changed) { + $renovacion->save(); + } + header('Location: ' . nUrl('pagares', 'show', ['pagare' => $renovacion->pagare])); + } + public static function add_renovacion() + { + $pagare = model(Pagare::class)->findOne(get('pagare')); + return view('proyectos.pagares.add_renovacion', compact('pagare')); + } + public static function do_add_renovacion() + { + $pagare = model(Pagare::class)->findOne(get('pagare')); + $data = post(); + + $data['pagare'] = $pagare->id; + $fecha = ['year', 'month', 'day']; + $fecha_arr = array_filter($data, function($item) use ($fecha) { + return (array_search($item, $fecha) !== false); + }, \ARRAY_FILTER_USE_KEY); + uksort($fecha_arr, function($a, $b) use ($fecha) { + return array_search($a, $fecha) - array_search($b, $fecha); + }); + foreach ($fecha as $f) { + unset($data[$f]); + } + array_walk($fecha_arr, function(&$item) { + if (strlen($item) < 4) { + $item = str_pad($item, 2, '0', \STR_PAD_LEFT); + } + }); + $data['fecha'] = implode('-', $fecha_arr); + + foreach ($fecha as &$key) { + $key .= '_banco'; + } + $fecha_arr = array_filter($data, function($item) use ($fecha) { + return (array_search($item, $fecha) !== false); + }, \ARRAY_FILTER_USE_KEY); + uksort($fecha_arr, function($a, $b) use ($fecha) { + return array_search($a, $fecha) - array_search($b, $fecha); + }); + foreach ($fecha as $f) { + unset($data[$f]); + } + array_walk($fecha_arr, function(&$item) { + if (strlen($item) < 4) { + $item = str_pad($item, 2, '0', \STR_PAD_LEFT); + } + }); + $data['fecha_banco'] = implode('-', $fecha_arr); + + $renovacion = model(RenovacionPagare::class)->create($data); + $renovacion->save(); + + header('Location: ' . nUrl('pagares', 'show', ['pagare' => $renovacion->pagare])); + } +} diff --git a/app/Controller/Pagos.php b/app/Controller/Pagos.php new file mode 100644 index 0000000..f279b9e --- /dev/null +++ b/app/Controller/Pagos.php @@ -0,0 +1,358 @@ +findOne($id); + $tipos = model(TipoPago::class)->orderByAsc('descripcion')->findMany(); + $estados = model(TipoEstadoPago::class)->orderByAsc('descripcion')->findMany(); + + return view('ventas.pagos.edit', compact('pago', 'asociado', 'id_asociado', 'tipos', 'estados')); + } + public static function editar() + { + $id = get('pago'); + $pago = model(Pago::class)->findOne($id); + + $fp = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $tipo = model(TipoPago::class)->findOne(post('tipo')); + $valor = correctNumber(post('valor')); + $banco = model(Banco::class)->where('nombre', post('banco'))->findOne(); + + $fe = Carbon::createFromDate(post('yearestado'), post('monthestado'), post('dayestado'), config('app.timezone')); + $estado = model(TipoEstadoPago::class)->findOne(post('estado')); + $uf = uf($fe); + + $est = $pago->estado(); + if ($est->fecha != $fe->format('Y-m-d')) { + $est->fecha = $fe->format('Y-m-d'); + $pago->uf = $uf->uf->value; + } + if ($est->estado != $estado->id) { + $est->estado = $estado->id; + } + + if ($pago->fecha != $fp->format('Y-m-d')) { + $pago->fecha = $fp->format('Y-m-d'); + } + if ($pago->tipo != $tipo->id) { + $pago->tipo = $tipo->id; + } + if ($pago->valor != $valor) { + $pago->valor = $valor; + } + if ($pago->identificador != post('identificador')) { + $pago->identificador = post('identificador'); + } + if ($pago->pagador != post('pagador')) { + $pago->pagador = post('pagador'); + } + if ($pago->banco != $banco->id) { + $pago->banco = $banco->id; + } + + $est->save(); + $pago->save(); + header('Location: ' . url('', ['p' => get('asociado') . 's', 'a' => 'show', get('asociado') => get(get('asociado'))])); + } + public static function pendientes() + { + $ventas = model(Venta::class) + ->select('venta.*') + ->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', ['te.id', '=', 'ev.estado'], 'te') + ->join('propiedad', ['propiedad.id', '=', 'venta.propiedad']) + ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal']) + ->join('proyecto', ['proyecto.id', '=', 'unidad.proyecto']) + ->where('te.activa', 1) + ->orderByAsc('proyecto.descripcion') + ->orderByExpr('LPAD(unidad.descripcion, 4, "0")') + ->findMany(); + $n = 30; + $mod = floor(count($ventas) / $n); + $i_rest = count($ventas) - count($ventas) % $mod + 1; + $rest = count($ventas) - $i_rest; + $lots = (object) ['size' => $mod, 'N' => $n, 'rest' => (object) [ + 'size' => $rest, + 'start' => $i_rest + ] + ]; + return view('ventas.pagos.pendientes', compact('ventas', 'lots')); + } + public static function para_pendientes() + { + $timezone = config('app.timezone'); + $today = Carbon::today($timezone); + $days = []; + $fechas = []; + for ($i = $today->copy()->subDays(15); $i <= $today->copy()->addDays(15); $i = $i->copy()->addDay()) { + $days []= $i->format('Y-m-d'); + $fechas []= $i->format('d-m-Y'); + } + $pagos_pendientes = model(Pago::class) + ->select('estado_pago.fecha') + ->selectExpr('COUNT(pago.id)', 'cantidad') + ->join('cuota', ['cuota.pago', '=', 'pago.id']) + ->join('venta', ['venta.pie', '=', 'cuota.pie']) + ->filter('filterEstado') + ->where('estado_pago.estado', 0) + ->where('venta.estado', 1) + ->whereGte('estado_pago.fecha', $today->copy()->subDays(15)->format('Y-m-d')) + ->whereLte('estado_pago.fecha', $today->copy()->addDays(15)->format('Y-m-d')) + ->orderByAsc('estado_pago.fecha') + ->groupBy('estado_pago.fecha') + ->findMany(); + $valores = array_fill(0, count($days), 0); + $anteriores = model(Pago::class) + ->join('cuota', ['cuota.pago', '=', 'pago.id']) + ->join('venta', ['venta.pie', '=', 'cuota.pie']) + ->filter('filterEstado') + ->where('estado_pago.estado', 0) + ->where('venta.estado', 1) + ->whereLt('estado_pago.fecha', $today->copy()->subDays(15)->format('Y-m-d')) + ->count(); + foreach ($pagos_pendientes as $pago) { + $valores[array_search($pago->fecha()->format('Y-m-d'), $days)] = $pago->cantidad; + } + $acum = []; + $sum = 0; + foreach ($valores as $valor) { + $sum += $valor; + $acum []= $sum; + } + $t = array_search($today->format('Y-m-d'), $days); + $color = array_merge( + array_fill(0, $t, 'red'), + ['blue'], + array_fill(0, count($days) - $t, 'green') + ); + $pagos = ['data' => $acum, 'historico' => $anteriores, 'backgroundColor' => $color]; + $abonos_pendientes = model(Pago::class) + ->select('estado_pago.fecha') + ->selectExpr('COUNT(pago.id)', 'cantidad') + ->filter('filterEstado') + ->where('estado_pago.estado', 1) + ->whereGte('estado_pago.fecha', $today->copy()->subDays(15)->format('Y-m-d')) + ->whereLt('estado_pago.fecha', $today->copy()->format('Y-m-d')) + ->orderByAsc('estado_pago.fecha') + ->groupBy('estado_pago.fecha') + ->findMany(); + $anteriores = model(Pago::class) + ->join('cuota', ['cuota.pago', '=', 'pago.id']) + ->join('venta', ['venta.pie', '=', 'cuota.pie']) + ->filter('filterEstado') + ->where('estado_pago.estado', 1) + ->where('venta.estado', 1) + ->whereLt('estado_pago.fecha', $today->copy()->subDays(15)->format('Y-m-d')) + ->count(); + $valores = array_fill(0, count($days), 0); + foreach ($abonos_pendientes as $pago) { + $valores[array_search($pago->fecha()->format('Y-m-d'), $days)] = $pago->cantidad; + } + $acum = []; + $sum = 0; + foreach ($valores as $valor) { + $sum += $valor; + $acum []= $sum; + } + $color = array_fill(0, count($pagos), 'rgb(200, 0, 0)'); + $abonos = ['data' => $acum, 'historico' => $anteriores, 'backgroundColor' => $color]; + $output = ['count' => count($days), 'fechas' => $fechas, 'pagos' => $pagos, 'abonos' => $abonos]; + echo json_encode($output); + } + public static function para_abonar() + { + $ids = json_decode(post('ids')); + //$id = get('id'); + function checkPago(&$pagos, $tipo, $pago) { + if (!$pago) { + return; + } + if (!$pago->estado()) { + $pagos []= [ + 'tipo' => $tipo, + 'pago' => $pago->asArray(), + 'estado' => -1 + ]; + return; + } + if ($pago->estado()->tipo()->descripcion == 'depositado') { + $pagos []= [ + 'tipo' => $tipo, + 'pago' => $pago->asArray(), + 'fecha' => format('shortDate', $pago->estado()->fecha), + 'valor' => format('pesos', $pago->valor, true), + 'estado' => 1 + ]; + } + } + $output = []; + foreach ($ids as $id) { + $venta = model(Venta::class)->findOne($id); + if ($venta->estado()->tipo()->activa == 0) { + $output []= ['status' => -1, 'venta' => $venta->id]; + continue; + } + $pagos = []; + if ($venta->pie()) { + foreach ($venta->pie()->cuotas() as $cuota) { + checkPago($pagos, 'Pie', $cuota->pago()); + } + if ($venta->pie()->reajuste()) { + checkPago($pagos, 'Reajuste', $venta->pie()->reajuste()); + } + } + if ($venta->credito()) { + checkPago($pagos, 'Credito', $venta->credito()->pago()); + } + if ($venta->escritura()) { + checkPago($pagos, 'Abono Escritura', $venta->escritura()->pago()); + } + if ($venta->subsidio()) { + checkPago($pagos, 'Subsidio', $venta->subsidio()->subsidio()); + checkPago($pagos, 'Ahorro', $venta->subsidio()->pago()); + } + if (count($pagos) <= 0) { + $output []= ['status' => -1, 'venta' => $venta->id]; + continue; + } + $output []= [ + 'status' => 1, + 'proyecto' => $venta->proyecto()->descripcion, + 'venta' => $venta->id, + 'propietario' => $venta->propietario()->nombreCompleto(), + 'departamento' => $venta->unidad()->descripcion, + 'pagos' => $pagos + ]; + } + return json_encode($output); + } + public static function rebotes() + { + $ids = json_decode(post('ids')); + $response = []; + foreach ($ids as $id) { + //$id = get('id'); + $venta = model(Venta::class)->findOne($id); + $rebotes = $venta->pagos(-1); + if (count($rebotes) < 1) { + $response []= ['status' => -1, 'venta' => $venta->id]; + continue; + } + usort($rebotes, function($a, $b) { + return $b->estado()->fecha()->diffInDays($a->estado()->fecha(), false); + }); + + $output = []; + $textos = []; + foreach ($rebotes as $rebote) { + $fuente = $rebote->fuente()[0]; + $text = '' . ucwords(str_replace('_', ' ', $fuente->tipo)) . ''; + $info = ['tipo' => ucwords(str_replace('_', ' ', $fuente->tipo))]; + switch ($fuente->tipo) { + case('cuota'): + $text .= '' . $fuente->obj->pie()->venta()->proyecto()->descripcion + . '' . $fuente->obj->pie()->venta()->unidad()->descripcion . '' + . $fuente->obj->pie()->venta()->propietario()->nombreCompleto() + . '' . format('shortDate', $rebote->estado()->fecha) . ''; + $info['proyecto'] = $fuente->obj->pie()->venta()->proyecto()->descripcion; + $info['venta'] = $fuente->obj->pie()->venta()->id; + $info['departamento'] = $fuente->obj->pie()->venta()->unidad()->descripcion; + $info['propietario'] = $fuente->obj->pie()->venta()->propietario()->nombreCompleto(); + $info['fecha'] = format('shortDate', $rebote->estado()->fecha); + break; + } + $text .= '' . format('pesos', $rebote->valor('pesos'), true) . ''; + $info['valor'] = format('pesos', $rebote->valor('pesos'), true); + $output []= array_merge(['id' => $rebote->id], $info); + $textos []= ['id' => $rebote->id, 'text' => $text]; + } + $response []= ['status' => 1, 'venta' => $venta->id, 'textos' => $textos, 'rebotes' => $output]; + } + + return json_encode($response); + } + public static function show() + { + $id = get('pago'); + $asociado = get('asociado'); + $id_asociado = get($asociado); + + $pago = model(Pago::class)->findOne($id); + + return view('ventas.pagos.show', compact('pago', 'asociado', 'id_asociado')); + } + public static function pagar() + { + $id = get('pago'); + $pago = model(Pago::class)->findOne($id); + $asociado = get('asociado'); + $id_asociado = get($asociado); + + return view('ventas.pagos.pagar', compact('pago', 'asociado', 'id_asociado')); + } + public static function pagando() + { + $id = get('pago'); + $pago = model(Pago::class)->findOne($id); + $asociado = get('asociado'); + $id_asociado = get($asociado); + + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $data = [ + 'fecha' => $f->format('Y-m-d'), + 'pago' => $pago->id, + 'estado' => 1 + ]; + $estado = model(EstadoPago::class)->create($data); + + $estado->save(); + header('Location: ' . url('', ['p' => $asociado . 's', 'a' => 'show', $asociado => $id_asociado])); + } + public static function abonar() + { + $id = get('pago'); + $pago = model(Pago::class)->findOne($id); + $asociado = get('asociado'); + $id_asociado = get($asociado); + + return view('ventas.pagos.abonar', compact('pago', 'asociado', 'id_asociado')); + } + public static function abonando() + { + $id = get('pago'); + $pago = model(Pago::class)->findOne($id); + $asociado = get('asociado'); + $id_asociado = get($asociado); + + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $data = [ + 'fecha' => $f->format('Y-m-d'), + 'pago' => $pago->id, + 'estado' => 2 + ]; + $estado = model(EstadoPago::class)->create($data); + + $estado->save(); + header('Location: ' . url('', ['p' => $asociado . 's', 'a' => 'show', $asociado => $id_asociado])); + } +} +?> diff --git a/app/Controller/Pies.php b/app/Controller/Pies.php new file mode 100644 index 0000000..38c2fcb --- /dev/null +++ b/app/Controller/Pies.php @@ -0,0 +1,104 @@ +findOne($proyecto); + $ventas = $proyecto->ventas(); + self::sort($ventas); + return view('ventas.list', compact('proyecto', 'ventas')); + } + public static function listProyectos() + { + $proyectos = \Model::factory(Proyecto::class) + ->select('proyecto.*') + ->join('estado_proyecto', ['estado.proyecto', '=', 'proyecto.id'], 'estado') + ->join('tipo_estado_proyecto', ['tipo.id', '=', 'estado.estado'], 'tipo') + ->join('etapa_proyecto', ['etapa.id', '=', 'tipo.etapa'], 'etapa') + ->whereGte('etapa.orden', 4) + ->groupBy('proyecto.id') + ->findMany(); + echo view('ventas.proyectos', compact('proyectos')); + } + public static function resumen() + { + $id = get('pie'); + $pie = \Model::factory(\Incoviba\old\Venta\Pie::class)->findOne($id); + $venta = $pie->venta(); + return view('ventas.pies.resumen', compact('venta')); + } + public static function reajustar() + { + $id = get('venta'); + $venta = \Model::factory(Venta::class)->findOne($id); + return view('ventas.pies.reajustar', compact('venta')); + } + public static function reajuste() + { + $id = get('venta'); + $venta = \Model::factory(Venta::class)->findOne($id); + + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $pago = \Model::factory(Pago::class)->create(); + $pago->fecha = $f->format('Y-m-d'); + $pago->uf = (float) uf($f)->uf->value; + $pago->valor = str_replace('.', '', post('valor')); + + $pago->new(); + + $pie = $venta->pie(); + $pie->reajuste = $pago->id; + $pie->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function edit() + { + $id = get('venta'); + $venta = \Model::factory(Venta::class)->findOne($id); + return view('ventas.pies.edit', compact('venta')); + } + public static function editar() + { + $id = get('venta'); + $venta = \Model::factory(Venta::class)->findOne($id); + $pie = $venta->pie(); + $valor = correctNumber(post('valor')); + if ($pie->valor != $valor) { + $pie->valor = $valor; + } + if ($pie->cuotas != post('cuotas')) { + $pie->cuotas = post('cuotas'); + } + + $pie->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function asociar() + { + $id = get('pie'); + $pie = \Model::factory(Pie::class)->findOne($id); + $pie->asociado = post('asociado'); + + $pie->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $pie->venta()->id])); + } +} +?> diff --git a/app/Controller/Postventas.php b/app/Controller/Postventas.php new file mode 100644 index 0000000..7b38cb6 --- /dev/null +++ b/app/Controller/Postventas.php @@ -0,0 +1,69 @@ +findOne($id); + + return view('ventas.postventas.add', compact('venta')); + } + public static function agregar() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $observaciones = json_decode(post('observaciones')); + $postventa = model(Postventa::class)->create(); + $postventa->venta_id = $venta->id; + $postventa->save(); + + $estado = model(EstadoPostventa::class)->create(); + $estado->postventa_id = $postventa->id; + $estado->tipo_estado_postventa_id = 1; + $estado->fecha = $f->format('Y-m-d'); + $estado->save(); + + foreach ($observaciones as $o) { + $observacion = model(Observacion::class)->create(); + $observacion->texto = post('observacion' . $o); + + $observacion->save(); + + $estado = model(EstadoObservacion::class)->create(); + $estado->observacion_id = $observacion->id; + $estado->tipo_estado_observacion_id = 1; + $estado->fecha = $f->format('Y-m-d'); + $estado->save(); + + $po = model(PostventaObservacion::class)->create(); + $po->postventa_id = $postventa->id; + $po->observacion_id = $observacion->id; + $po->save(); + } + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function show() + { + $id = get('postventa'); + $postventa = model(Postventa::class)->findOne($id); + $venta = model(Venta::class)->findOne($postventa->venta_id); + + return view('ventas.postventas.show', compact('postventa', 'venta')); + } +} +?> diff --git a/app/Controller/Precios.php b/app/Controller/Precios.php new file mode 100644 index 0000000..20db97b --- /dev/null +++ b/app/Controller/Precios.php @@ -0,0 +1,177 @@ +orderByAsc('descripcion')->findMany(); + return view('ventas.precios.proyectos', compact('proyectos')); + } + public static function list() + { + $proyecto = \model(Proyecto::class)->findOne(get('proyecto')); + return view('ventas.precios.list', compact('proyecto')); + } + public static function import() + { + $proyectos = \model(Proyecto::class)->orderByAsc('descripcion')->findMany(); + return view('ventas.precios.import', compact('proyectos')); + } + public static function importar() + { + $proyecto = \model(Proyecto::class)->findOne(post('proyecto')); + $fecha = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $file = explode(PHP_EOL, trim(file_get_contents($_FILES['archivo']['tmp_name']))); + $columnas = explode(';', array_shift($file)); + $tr = model(TipoEstadoPrecio::class)->where('descripcion', 'reemplazado')->findOne()->id; + $tv = model(TipoEstadoPrecio::class)->where('descripcion', 'vigente')->findOne()->id; + foreach ($file as $line) { + if (trim($line) == '') { + continue; + } + $info = explode(';', $line); + $tipo = \model(TipoUnidad::class)->where('descripcion', $info[0])->findOne(); + $unidad = \model(Unidad::class)->where('tipo', $tipo->id)->where('descripcion', $info[1])->where('proyecto', $proyecto->id)->findOne(); + if (!$unidad) { + continue; + } + + try { + self::reemplazar($unidad->id, $info[2], $fecha, $tr, $tv); + } catch (\Exception $e) { + continue; + } + } + header('Location: ' . nUrl('precios', 'list', ['proyecto' => $proyecto->id])); + } + public static function add() + { + $proyecto = \model(Proyecto::class)->findOne(get('proyecto')); + return view('ventas.precios.add', compact('proyecto')); + } + public static function agregar() + { + $proyecto = get('proyecto'); + $fecha = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $precios = []; + foreach (post() as $name => $valor) { + if ($valor == '' or strpos($name, 'precio') === false) { + continue; + } + list($tipo, $id) = explode(':', $name); + $tipo = trim(str_replace('precio', '', $tipo), '_'); + $id = explode('-', $id); + switch (count($id)) { + case 1: + $precios []= ['tipo' => 'pt', 'id' => $id[0], 'valor' => $valor]; + break; + case 2: + $exists = false; + foreach ($precios as $precio) { + if ($precio['tipo'] == 'pt' and $precio['id'] == $id[0]) { + $exists = true; + break; + } + } + if (!$exists) { + $precios []= ['tipo' => 'subtipo', 'id' => $id[1], 'pt' => $id[0], 'valor' => $valor]; + } + break; + case 3: + $exists = false; + foreach ($precios as $precio) { + if ($precio['tipo'] == 'pt' and $precio['id'] == $id[0]) { + $exists = true; + break; + } + if ($precio['tipo'] == 'subtipo' and 'id' == $id[1] and 'pt' == $id[0]) { + $exists = true; + break; + } + } + if (!$exists) { + $precios []= ['tipo' => 'unidad', 'id' => $id[2], 'valor' => $valor]; + } + break; + } + } + foreach ($precios as $precio) { + $precio = (object) $precio; + try { + switch ($precio->tipo) { + case 'pt': + $pt = model(ProyectoTipoUnidad::class)->findOne($precio->id); + $pt->setPrecios($fecha, $precio->valor); + break; + case 'subtipo': + $pt = model(ProyectoTipoUnidad::class)->findOne($precio->pt); + $pt->setPreciosSubtipo($precios->id, $fecha, $precio->valor); + break; + case 'unidad': + $unidad = model(Unidad::class)->findOne($precio->id); + $unidad->setPrecio($fecha, $precio->valor); + break; + } + } catch(\Exception $e) { + continue; + } + } + header('Location: ' . nUrl('precios', 'list', ['proyecto' => $proyecto])); + } + protected static function reemplazar(int $unidad_id, float $valor, \DateTime $fecha, int $tr = 0, int $tv = 0) + { + if ($tr == 0) { + $tr = model(TipoEstadoPrecio::class)->where('descripcion', 'reemplazado')->findOne()->id; + } + if ($tv == 0) { + $tv = model(TipoEstadoPrecio::class)->where('descripcion', 'vigente')->findOne()->id; + } + $olds = \model(Precio::class)->where('unidad', $unidad_id)->findMany(); + if ($olds !== false) { + foreach ($olds as $old) { + if (!$old->vigente()) { + continue; + } + $data = [ + 'precio' => $old->id, + 'fecha' => $fecha->format('Y-m-d'), + 'estado' => $tr + ]; + $estado = \model(EstadoPrecio::class)->create($data); + $estado->save(); + } + } + $data = [ + 'unidad' => $unidad_id, + 'valor' => $valor + ]; + $precio = (new Factory(Precio::class))->where($data)->find(); + if (!$precio) { + $precio = \model(Precio::class)->create($data); + $precio->save(); + } + $data = [ + 'precio' => $precio->id, + 'fecha' => $fecha->format('Y-m-d'), + 'estado' => $tv + ]; + $estado = \model(EstadoPrecio::class)->create($data); + $estado->save(); + } +} diff --git a/app/Controller/Propietarios.php b/app/Controller/Propietarios.php new file mode 100644 index 0000000..5d38ee7 --- /dev/null +++ b/app/Controller/Propietarios.php @@ -0,0 +1,129 @@ +findOne($id); + $propietario = $venta->propietario(); + $regiones = model(Region::class)->orderByAsc('numeracion')->findMany(); + + return view('ventas.propietarios.edit', compact('venta', 'propietario', 'regiones')); + } + public static function editar() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + $info = post(); + list($info['rut'], $info['dv']) = explode('-', str_replace('.', '', $info['rut'])); + $propietario = model(Propietario::class)->findOne($info['rut']); + if (!$propietario) { + $propietario = model(Propietario::class)->create(); + } + if ($propietario->direccion != 0) { + $direccion = $propietario->direccion(); + } else { + $direccion = model(Direccion::class) + ->where('calle', post('calle')) + ->where('numero', post('numero')) + ->where('extra', post('extra')) + ->where('comuna', post('comuna')) + ->findOne(); + if (!$direccion) { + $data = [ + 'calle' => post('calle'), + 'numero' => post('numero'), + 'extra' => post('extra'), + 'comuna' => post('comuna') + ]; + $direccion = model(Direccion::class)->create($data); + } + } + + if (isset($info['empresa'])) { + $info['apellido_paterno'] = ''; + $info['apellido_materno'] = ''; + } + + if ($propietario->representante != 0) { + list($info['rep_rut'], $info['rep_dv']) = explode('-', str_replace('.', '', $info['rep_rut'])); + $representante = $propietario->representante(); + } elseif (isset($info['rep_rut'])) { + list($info['rep_rut'], $info['rep_dv']) = explode('-', str_replace('.', '', $info['rep_rut'])); + $representante= model(Propietario::class)->findOne($info['rep_rut']); + if (!$representante) { + $representante= model(Propietario::class)->create(); + } + } + + $fields = ['rut', 'dv', 'nombres', 'apellido_paterno', 'apellido_materno']; + $change = false; + foreach ($fields as $key) { + if ($propietario->$key != $info[$key]) { + $propietario->$key = $info[$key]; + $change = true; + } + } + if ($direccion->isNew()) { + $direccion->save(); + } + if ($propietario->direccion != $direccion->id) { + $propietario->direccion = $direccion->id; + $change = true; + } + if ($change) { + d($propietario); + $propietario->save(); + } + + if (isset($info['rep_rut'])) { + $change = false; + if ($representante->rut != $info['rep_rut']) { + $representante->rut = $info['rep_rut']; + $representante->dv = $info['rep_dv']; + $change = true; + } + if ($representante->nombres != $info['rep_nombres']) { + $representante->nombres = $info['rep_nombres']; + $change = true; + } + if ($representante->apellido_paterno != $info['rep_apaterno']) { + $representante->apellido_paterno = $info['rep_apaterno']; + $change = true; + } + if ($representante->apellido_materno != $info['rep_amaterno']) { + $representante->apellido_materno = $info['rep_amaterno']; + $change = true; + } + if ($representante->direccion != $direccion->id) { + $representante->direccion = $direccion->id; + $change = true; + } + if ($change) { + $representante->save(); + } + if ($propietario->representante != $representante->rut) { + $propietario->representante = $representante->rut; + $propietario->save(); + } + } + + if ($venta->propietario != $propietario->rut) { + $venta->propietario = $propietario->rut; + $venta->save(); + } + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } +} +?> diff --git a/app/Controller/ProyectoTipoUnidades.php b/app/Controller/ProyectoTipoUnidades.php new file mode 100644 index 0000000..32c0c1d --- /dev/null +++ b/app/Controller/ProyectoTipoUnidades.php @@ -0,0 +1,77 @@ +findOne($id); + $tipos = model(TipoUnidad::class)->findMany(); + + return view('proyectos.tipo_unidades.edit', compact('tipo', 'tipos')); + } + public static function editar() + { + $id = get('tipo_unidad'); + $tipo = model(ProyectoTipoUnidad::class)->findOne($id); + + $changed = false; + foreach (post() as $field => $value) { + if ($tipo->{$field} != $value) { + $tipo->{$field} = $value; + $changed = true; + } + } + if ($changed) { + $tipo->save(); + } + header('Location: ' . nUrl('proyectos', 'list_unidades', ['proyecto' => $tipo->proyecto()->id])); + } + public static function add_unidad() + { + $id = get('tipo_unidad'); + $tipo = model(ProyectoTipoUnidad::class)->findOne($id); + if ($tipo->tipo()->descripcion == 'departamento') { + return view('proyectos.unidades.add', compact('tipo')); + } + return view('proyectos.unidades.add2', compact('tipo')); + } + public static function assign() + { + $id = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + $tipos = model(ProyectoTipoUnidad::class)->where('proyecto', $proyecto->id)->findMany(); + $libres = model(Unidad::class)->where('proyecto', $proyecto->id)->where('pt', 0)->findMany(); + + return view('proyectos.unidades.assign', compact('proyecto', 'tipos', 'libres')); + } + public static function asignar() + { + $id = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + + $libres = model(Unidad::class)->where('proyecto', $proyecto->id)->where('pt', 0)->findMany(); + foreach ($libres as $unidad) { + $unidad->pt = post('tipo' . $unidad->id); + $unidad->save(); + } + header('Location: ' . nUrl('proyectos', 'list_unidades', ['proyecto' => $proyecto->id])); + } +} diff --git a/app/Controller/Proyectos.php b/app/Controller/Proyectos.php new file mode 100644 index 0000000..f6a4e45 --- /dev/null +++ b/app/Controller/Proyectos.php @@ -0,0 +1,327 @@ +where('inmobiliaria', $id_inmobiliaria); + } else { + $proyectos = model(Proyecto::class); + } + $proyectos = $proyectos->order_by_asc('descripcion')->findMany(); + return view('proyectos.list', compact('proyectos')); + } + public static function show() + { + $id_proyecto = get('proyecto'); + if ($id_proyecto == null) { + header('Location: ' . url('', ['p' => 'proyectos', 'a' => 'list'])); + } + $proyecto = model(Proyecto::class)->findOne($id_proyecto); + $estados = model(TipoEstadoProyecto::class)->findMany(); + foreach ($estados as &$estado) { + $estado = $estado->asArray()['orden'] + 1; + } + $colors = []; + + $ventas_pt = (object) ['fields' => [], 'data' => [], 'totales' => [], 'vendidas' => []]; + $ventas = $proyecto->ventas('fecha'); + $months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + if (count($ventas) > 0) { + $inicio = $ventas[0]->fecha()->format('Y'); + $fin = $ventas[count($ventas) - 1]->fecha()->format('Y'); + $end = $ventas[count($ventas) - 1]->fecha()->format('M'); + for ($y = $inicio; $y <= $fin; $y ++) { + foreach ($months as $month) { + $ventas_pt->fields []= $y . ' ' . $month; + if ($y == $fin and $month == $end) { + break; + } + } + } + } + + foreach ($proyecto->tipologias() as $tipo) { + if (!isset($ventas_pt->data[$tipo->tipologia->descripcion])) { + $ventas_pt->data[$tipo->tipologia->descripcion] = []; + $ventas_pt->data[$tipo->tipologia->descripcion] = array_fill(0, count($ventas_pt->fields), 0); + $ventas_pt->totales[$tipo->tipologia->descripcion] = 0; + $ventas_pt->vendidas[$tipo->tipologia->descripcion] = 0; + } + foreach ($tipo->tipos as $pt) { + foreach ($pt->ventas('fecha') as $venta) { + $ventas_pt->data[$tipo->tipologia->descripcion][array_search($venta->fecha()->format('Y M'), $ventas_pt->fields)] ++; + $ventas_pt->vendidas[$tipo->tipologia->descripcion] ++; + } + $ventas_pt->totales[$tipo->tipologia->descripcion] += count($pt->unidades()); + } + } + foreach ($ventas_pt->data as $tipo => $data) { + $acum = 0; + foreach ($data as $i => $cantidad) { + $acum += $cantidad; + $ventas_pt->data[$tipo][$i] = round($acum / $ventas_pt->totales[$tipo] * 100, 2); + } + } + $meses = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic']; + array_walk($ventas_pt->fields, function(&$item) use ($meses, $months) { + $item = str_replace($months, $meses, $item); + }); + + for ($i = 0; $i < 10; $i ++) { + $colors[$i] = 'rgb(' . mt_rand(0, 255) . ', ' . mt_rand(0, 255) . ', ' . mt_rand(0, 255) . ')'; + } + return view('proyectos.show', compact('proyecto', 'estados', 'colors', 'ventas_pt')); + } + public static function historial() + { + $proyecto = model(Proyecto::class)->findOne(get('proyecto')); + return view('proyectos.historia', compact('proyecto')); + } + public static function advance() + { + $id_proyecto = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id_proyecto); + $estados = model(TipoEstadoProyecto::class)->whereGt('orden', $proyecto->estado()->tipo()->orden)->orderByAsc('orden')->findMany(); + + return view('proyectos.advance', compact('proyecto', 'estados')); + } + public static function avanzar() + { + $id_proyecto = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id_proyecto); + $id_tipo = post('estado'); + $tipo = model(TipoEstadoProyecto::class)->findOne($id_tipo); + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + + $tipos = model(TipoEstadoProyecto::class) + ->whereGt('orden', $proyecto->estado()->tipo()->orden) + ->whereLte('orden', $tipo->orden) + ->orderByAsc('orden') + ->findMany(); + + foreach ($tipos as $t) { + $estado = model(EstadoProyecto::class)->create(); + $estado->proyecto = $proyecto->id; + $estado->estado = $t->id; + $estado->fecha = $f->format('Y-m-d'); + $estado->save(); + } + header('Location: ' . url('', ['p' => 'proyectos', 'a' => 'show', 'proyecto' => $proyecto->id])); + } + public static function avance() + { + $id = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $av = post('avance') / 100; + $ep = (double) post('estado_pago'); + $avance = model(AvanceConstruccion::class) + ->where('proyecto', $proyecto->id) + ->where('fecha', $f->format('Y-m-d')) + ->findOne(); + if (!$avance) { + $data = [ + 'proyecto' => $proyecto->id, + 'fecha' => $f->format('Y-m-d'), + 'numero' => post('numero'), + 'avance' => $av, + 'estado_pago' => $ep + ]; + $avance = model(AvanceConstruccion::class)->create($data); + } + $avance->save(); + header('Location: ' . url('', ['p' => 'proyectos', 'a' => 'historial', 'proyecto' => $proyecto->id])); + } + public static function add() + { + $rut = get('inmobiliaria'); + + $inmobiliarias = model(Inmobiliaria::class)->orderByAsc('abreviacion')->findMany(); + $regiones = model(Region::class)->orderByAsc('numeracion')->findMany(); + + return view('proyectos.add', compact('inmobiliarias', 'rut', 'regiones')); + } + public static function agregar() + { + $proyecto = model(Proyecto::class)->where('descripcion', post('descripcion'))->where('inmobiliaria', post('inmobiliaria'))->find_one(); + if ($proyecto) { + header('Location: ' . url('', ['p' => 'proyectos', 'a' => 'show', 'proyecto' => $proyecto->id])); + die(); + } + $proyecto = model(Proyecto::class)->create(); + $proyecto->descripcion = post('descripcion'); + $proyecto->inmobiliaria = post('inmobiliaria'); + + $direccion = model(Direccion::class) + ->where('calle', post('calle')) + ->where('numero', post('numero')) + ->where('extra', post('extra')) + ->where('comuna', post('comuna')) + ->findOne(); + if (!$direccion) { + $direccion = model(Direccion::class)->create(); + $direccion->calle = post('calle'); + $direccion->numero = post('numero'); + $direccion->extra = post('extra'); + $direccion->comuna = post('comuna'); + $direccion->save(); + } + + $proyecto->direccion = $direccion->id; + $proyecto->save(); + + $fecha = Carbon::parse(post('year'), post('month'), post('day'), config('app.timezone')); + $estado = model(EstadoProyecto::class)->create(); + $estado->proyecto = $proyecto->id; + $estado->estado = 1; + $estado->fecha = $fecha->format('Y-m-d'); + $estado->save(); + header('Location: ' . url('', ['p' => 'proyectos', 'a' => 'show', 'proyecto' => $proyecto->id])); + } + public static function disponibles() + { + $id = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + + return view('proyectos.disponibles', compact('proyecto')); + } + public static function list_unidades() + { + $id = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + $libres = model(Unidad::class)->where('proyecto', $proyecto->id)->where('pt', 0)->findMany(); + + return view('proyectos.unidades.list', compact('proyecto', 'libres')); + } + public static function add_tipo_unidad() + { + $id = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + $tipos = model(TipoUnidad::class)->findMany(); + + return view('proyectos.tipo_unidades.add', compact('proyecto', 'tipos')); + } + public static function agregar_tipo_unidad() + { + $id = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + $data = post(); + $data['proyecto'] = $proyecto->id; + $tipo = model(ProyectoTipoUnidad::class)->where('proyecto', $data['proyecto']) + ->where('tipo', $data['tipo'])->where('nombre', $data['nombre'])->findOne(); + if ($tipo === false) { + $tipo = model(ProyectoTipoUnidad::class)->create($data); + $tipo->save(); + } + header('Location: ' . nUrl('proyectos', 'list_unidades', ['proyecto' => $proyecto->id])); + } + public static function construccion() + { + $id = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id); + return view('proyectos.construccion', compact('proyecto')); + } + public static function editar_avance() + { + $avance = model(AvanceConstruccion::class)->findOne(get('avance')); + return view('proyectos.avances.edit', compact('avance')); + } + public static function edit_avance() + { + $avance = model(AvanceConstruccion::class)->findOne(get('avance')); + $cols = [ + 'day', + 'month', + 'year', + 'avance', + 'estado_pago', + 'pagado', + 'day_pago', + 'month_pago', + 'year_pago' + ]; + $data = array_filter(post(), function($key) use ($cols) { + return (array_search($key, $cols) !== false); + }, \ARRAY_FILTER_USE_KEY); + $data['fecha'] = implode('-', [$data['year'], $data['month'], $data['day']]); + unset($data['year']); + unset($data['month']); + unset($data['day']); + $data['fecha_pagado'] = implode('-', [$data['year_pago'], $data['month_pago'], $data['day_pago']]); + unset($data['year_pago']); + unset($data['month_pago']); + unset($data['day_pago']); + $data['avance'] /= 100; + $avance->edit($data); + + header('Location: ' . nUrl('proyectos', 'construccion', ['proyecto' => $avance->proyecto])); + } + public static function reservas() + { + $proyecto = model(Proyecto::class)->findOne(get('proyecto')); + $pisos = []; + $totales = []; + foreach ($proyecto->unidades('departamento') as $unidad) { + if (!isset($pisos[$unidad->piso - 1])) { + $piso = (object) ['descripcion' => $unidad->piso, 'unidades' => []]; + $pisos[$unidad->piso - 1] = $piso; + } + if (!isset($totales[$unidad->linea()])) { + $totales[$unidad->linea()] = (object) ['ventas' => 0, 'reservas' => 0]; + } + $pisos[$unidad->piso - 1]->unidades[$unidad->linea()] = $unidad; + if ($unidad->isVendida()) { + $totales[$unidad->linea()]->ventas ++; + } + if ($unidad->isReservada()) { + $totales[$unidad->linea()]->reservas ++; + } + } + ksort($pisos); + $max_unidades = 0; + foreach ($pisos as $piso) { + if (count($piso->unidades) > $max_unidades) { + $max_unidades = count($piso->unidades); + } + } + return view('proyectos.reservas.base', compact('proyecto', 'pisos', 'max_unidades', 'totales')); + } + public function unidades() + { + if (get('proyecto')) { + $proyecto = model(Proyecto::class)->findOne(get('proyecto')); + $libres = model(Unidad::class)->where('proyecto', $proyecto->id)->where('pt', 0)->findMany(); + + return view('proyectos.unidades.list', compact('proyecto', 'libres')); + } + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->findMany(); + return view('proyectos.unidades.proyectos', compact('proyectos')); + } +} +?> diff --git a/app/Controller/Reajustes.php b/app/Controller/Reajustes.php new file mode 100644 index 0000000..4c6c938 --- /dev/null +++ b/app/Controller/Reajustes.php @@ -0,0 +1,90 @@ +findOne($id); + return view('ventas.pies.reajustes.edit', compact('venta')); + } + public static function editar() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $uf = uf($f); + + $valor = correctNumber(post('valor')); + if ($valor == '') { + $valor_uf = correctNumber(post('valor_uf')); + $valor = $valor_uf * $uf->uf->value; + } + $pago = $venta->pie()->reajuste(); + if ($pago->valor != $valor) { + $pago->valor = $valor; + } + if ($pago->fecha != $f->format('Y-m-d')) { + $pago->fecha = $f->format('Y-m-d'); + $pago->uf = $uf->uf->value; + } + + $pago->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function pagar() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + return view('ventas.pies.reajustes.pagar', compact('venta')); + } + public static function pagado() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + + $data = [ + 'pago' => $venta->pie()->reajuste()->id, + 'fecha' => $f->format('Y-m-d'), + 'estado' => 1 + ]; + $estado = model(EstadoPago::class)->create($data); + $estado->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function abonar() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + return view('ventas.pies.reajustes.abonar', compact('venta')); + } + public static function abonado() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + + $data = [ + 'pago' => $venta->pie()->reajuste()->id, + 'fecha' => $f->format('Y-m-d'), + 'estado' => 2 + ]; + $estado = model(EstadoPago::class)->create($data); + $estado->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } +} +?> diff --git a/app/Controller/Registros.php b/app/Controller/Registros.php new file mode 100644 index 0000000..546fece --- /dev/null +++ b/app/Controller/Registros.php @@ -0,0 +1,39 @@ +orderByDesc('time')->findMany(); + $ini = new Color(0, 100, 0); + $end = new Color(255, 255, 255); + $colores = self::colores($end, $ini, 100); + return view('admin.registros.list', compact('registros', 'colores')); + } + public static function show() + { + $registro = model(RModel::class)->findOne(get('registro')); + $ini = new Color(0, 100, 0); + $end = new Color(255, 255, 255); + $colores = self::colores($end, $ini, 100); + return view('admin.registros.show', compact('registro', 'colores')); + } + protected static function colores($ini, $end, $max) + { + $current = $ini->toVector(); + $colores = []; + $line = new Line($ini->toVector(), $end->toVector()); + for ($i = 0; $i < $max; $i ++) { + $colores[$i] = new Color($current); + $current = $line->move($current, $line->length() / $max); + } + return $colores; + } +} diff --git a/app/Controller/Subsidios.php b/app/Controller/Subsidios.php new file mode 100644 index 0000000..5107fc3 --- /dev/null +++ b/app/Controller/Subsidios.php @@ -0,0 +1,184 @@ +findOne($id); + echo view('ventas.subsidios.add', compact('venta')); + } + public static function do_add() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $uf = uf($f); + + $pago1 = model(Pago::class)->create(); + $valor = post('ahorro_uf') * $uf->uf->value; + if (post('ahorro') != null) { + $valor = post('ahorro'); + } + $pago1->valor = $valor; + $pago1->fecha = $f->format('Y-m-d'); + $pago1->uf = $uf->uf->value; + + $pago2 = model(Pago::class)->create(); + $valor = post('subsidio_uf') * $uf->uf->value; + if (post('subsidio') != null) { + $valor = post('subsidio'); + } + $pago2->valor = $valor; + $pago2->fecha = $f->format('Y-m-d'); + $pago2->uf = $uf->uf->value; + + $pago1->new(); + $pago2->new(); + + $subsidio = model(Subsidio::class)->create(); + $subsidio->pago = $pago1->id; + $subsidio->subsidio = $pago2->id; + + $subsidio->save(); + $venta->subsidio = $subsidio->id(); + $venta->save(); + header('Location: ' . nUrl('ventas', 'show', ['venta' => $venta->id])); + } + public static function edit() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + echo view('ventas.subsidios.edit', compact('venta')); + } + public static function do_edit() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $uf = uf($f); + + $pago1 = $venta->subsidio()->pago(); + $valor = post('ahorro_uf') * $uf->uf->value; + if (post('ahorro') != null) { + $valor = post('ahorro'); + } + $pago1->valor = $valor; + $pago1->fecha = $f->format('Y-m-d'); + $pago1->uf = $uf->uf->value; + + $pago2 = $venta->subsidio()->subsidio(); + $valor = post('subsidio_uf') * $uf->uf->value; + if (post('subsidio') != null) { + $valor = post('subsidio'); + } + $pago2->valor = $valor; + $pago2->fecha = $f->format('Y-m-d'); + $pago2->uf = $uf->uf->value; + + $pago1->save(); + $pago2->save(); + header('Location: ' . nUrl('ventas', 'show', ['venta' => $venta->id])); + } + public static function pagar() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + $tipo = get('tipo'); + switch($tipo) { + case 'subsidio': + $pago = $venta->subsidio()->subsidio(); + break; + case 'pago': + $pago = $venta->subsidio()->pago(); + break; + default: + $pago = null; + } + echo view('ventas.subsidios.pagar', compact('venta', 'pago')); + } + public static function do_pagar() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $tipo = post('tipo'); + switch($tipo) { + case 'subsidio': + $pago = $venta->subsidio()->subsidio(); + break; + case 'pago': + $pago = $venta->subsidio()->pago(); + break; + default: + $pago = null; + } + $pago->valor = post('valor'); + $tipo = model(TipoEstadoPago::class)->where('descripcion', 'depositado')->findOne(); + $data = [ + 'pago' => $pago->id, + 'fecha' => $f->format('Y-m-d'), + 'estado' => $tipo->id + ]; + $estado = model(EstadoPago::class)->create($data); + $pago->save(); + $estado->save(); + header('Location: ' . nUrl('ventas', 'show', ['venta' => $venta->id])); + } + public static function abonar() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + $tipo = get('tipo'); + switch($tipo) { + case 'subsidio': + $pago = $venta->subsidio()->subsidio(); + break; + case 'pago': + $pago = $venta->subsidio()->pago(); + break; + default: + $pago = null; + } + echo view('ventas.subsidios.abonar', compact('venta', 'pago')); + } + public static function do_abonar() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $tipo = post('tipo'); + switch($tipo) { + case 'subsidio': + $pago = $venta->subsidio()->subsidio(); + break; + case 'pago': + $pago = $venta->subsidio()->pago(); + break; + default: + $pago = null; + } + $pago->valor = post('valor'); + $tipo = model(TipoEstadoPago::class)->where('descripcion', 'abonado')->findOne(); + $data = [ + 'pago' => $pago->id, + 'fecha' => $f->format('Y-m-d'), + 'estado' => $tipo->id + ]; + $estado = model(EstadoPago::class)->create($data); + $pago->save(); + $estado->save(); + header('Location: ' . nUrl('ventas', 'show', ['venta' => $venta->id])); + } +} diff --git a/app/Controller/Temas.php b/app/Controller/Temas.php new file mode 100644 index 0000000..24b121a --- /dev/null +++ b/app/Controller/Temas.php @@ -0,0 +1,111 @@ +orderByAsc('descripcion')->findMany(); + return view('temas.add', compact('proyectos')); + } + public static function agregar() + { + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $data = [ + "proyecto_id" => post('proyecto'), + "inicio" => $f->format('Y-m-d'), + "texto" => post('texto') + ]; + $tema = model(Tema::class)->create($data); + + $tema->save(); + header('Location: ' . url('', ['p' => 'temas', 'a' => 'list'])); + } + public static function list() + { + $temas = model(Tema::class)->findMany(); + $t = Carbon::today(config('app.timezone')); + foreach ($temas as $i => $tema) { + if ($tema->cierre()->year != -1 and $t->diff($tema->cierre())->days > 10) { + unset($temas[$i]); + } + } + $temas = array_values($temas); + usort($temas, function($a, $b) { + $p = strcmp($a->proyecto()->descripcion, $b->proyecto()->descripcion); + if ($p == 0) { + $f = $b->inicio()->diff($a->inicio())->format('%r%a'); + if ($f == 0) { + return $a->id - $b->id; + } + return $f; + } + return $p; + }); + + return view('temas.list', compact('temas')); + } + public static function edit() + { + $id = get('tema'); + $tema = model(Tema::class)->findOne($id); + $proyectos = model(Proyecto::class)->orderByAsc('descripcion')->findMany(); + return view('temas.edit', compact('tema', 'proyectos')); + } + public static function editar() + { + $id = get('tema'); + $tema = model(Tema::class)->findOne($id); + + $proyecto = post('proyecto'); + $changed = false; + if ($tema->proyecto_id != $proyecto) { + $tema->proyecto_id = $proyecto; + $changed = true; + } + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + if ($tema->inicio() != $f) { + $tema->inicio = $f->format('Y-m-d'); + $changed = true; + } + $texto = post('texto'); + if ($tema->texto != $texto) { + $tema->texto = $texto; + $changed = true; + } + + if ($changed) { + $tema->save(); + } + header('Location: ' . url('', ['p' => 'temas', 'a' => 'list'])); + } + public static function cerrar() + { + $id = get('tema'); + $tema = model(Tema::class)->findOne($id); + $f = Carbon::today(config('app.timezone')); + $tema->cierre = $f->format('Y-m-d'); + + $tema->save(); + header('Location: ' . url('', ['p' => 'temas', 'a' => 'list'])); + } + public static function abrir() + { + $id = get('tema'); + $tema = model(Tema::class)->findOne($id)->as_array(); + unset($tema['id'], $tema['cierre'], $tema['created_at'], $tema['updated_at']); + + $tema = model(Tema::class)->create($tema); + + $tema->save(); + header('Location: ' . url('', ['p' => 'temas', 'a' => 'list'])); + } +} +?> diff --git a/app/Controller/Unidades.php b/app/Controller/Unidades.php new file mode 100644 index 0000000..9f0da01 --- /dev/null +++ b/app/Controller/Unidades.php @@ -0,0 +1,126 @@ +findOne($id); + $len = strlen(post('total')); + + $unis = json_decode(post('unidades')); + $data = []; + foreach ($unis as $n_unidad) { + if ($tipo->tipo()->descripcion == 'departamento') { + $ini = post('piso_ini' . $n_unidad); + $end = post('piso_end' . $n_unidad); + $subtipo = post('linea' . $n_unidad); + $orientacion = post('orientacion' . $n_unidad); + for ($piso = $ini; $piso <= $end; $piso ++) { + $descripcion = $piso . str_pad(post('linea' . $n_unidad), $len, '0', \STR_PAD_LEFT); + + $data []= [ + 'proyecto' => $tipo->proyecto()->id, + 'tipo' => $tipo->tipo()->id, + 'subtipo' => $subtipo, + 'piso' => $piso, + 'descripcion' => $descripcion, + 'abreviacion' => $tipo->abreviacion, + 'm2' => $tipo->m2, + 'terraza' => $tipo->terraza, + 'logia' => $tipo->logia, + 'orientacion' => $orientacion, + 'pt' => $tipo->id + ]; + } + } else { + $descripcion = post('descripcion' . $n_unidad); + $piso = post('piso' . $n_unidad); + $data []= [ + 'proyecto' => $tipo->proyecto()->id, + 'tipo' => $tipo->tipo()->id, + 'piso' => $piso, + 'descripcion' => $descripcion, + 'abreviacion' => $tipo->abreviacion, + 'm2' => $tipo->m2, + 'terraza' => $tipo->terraza, + 'logia' => $tipo->logia, + 'pt' => $tipo->id + ]; + } + } + + foreach ($data as $uni) { + $unidad = model(Unidad::class) + ->where('descripcion', $uni['descripcion']) + ->where('proyecto', $uni['proyecto']) + ->where('tipo', $uni['tipo']) + ->findOne(); + if ($unidad) { + continue; + } + $unidad = model(Unidad::class)->create($uni); + $unidad->save(); + } + header('Location: ' . url('', ['p' => 'proyectos', 'a' => 'list_unidades', 'proyecto' => $tipo->proyecto()->id])); + } + public static function edit() + { + $id = get('unidad'); + $unidad = model(Unidad::class)->findOne($id); + $tipos = model(ProyectoTipoUnidad::class)->where('proyecto', $unidad->proyecto()->id)->findMany(); + $abreviaciones = ['N', 'NE', 'E', 'SE', 'S', 'SO', 'O', 'NO']; + $descripciones = ['Norte', 'Noreste', 'Este', 'Sureste', 'Sur', 'Suroeste', 'Oeste', 'Noroeste']; + $orientaciones = []; + foreach ($abreviaciones as $i => $ab) { + $orientaciones []= (object) ['abreviacion' => $ab, 'descripcion' => $descripciones[$i]]; + } + + return view('proyectos.unidades.edit', compact('unidad', 'tipos', 'orientaciones')); + } + public static function editar() + { + $id = get('unidad'); + $unidad = model(Unidad::class)->findOne($id); + + $change = false; + $fields = ['descripcion', 'tipo', 'piso', 'linea', 'orientacion']; + foreach ($fields as $field) { + $f = $field; + if ($f == 'tipo') { + $f = 'pt'; + } + if ($f == 'linea') { + $f = 'subtipo'; + } + if ($unidad->{$f} != post($field)) { + $unidad->{$f} = post($field); + $change = true; + } + } + + if ($change) { + $unidad->save(); + } + header('Location: ' . nUrl('proyectos', 'list_unidades', ['proyecto' => $unidad->proyecto()->id])); + } + public static function remove() + { + $id = get('unidad'); + $unidad = model(Unidad::class)->findOne($id); + $unidad->delete(); + + $id = get('proyecto'); + header('Location: ' . nUrl('proyectos', 'list_unidades', ['proyecto' => $id])); + } +} +?> diff --git a/app/Controller/UnidadesBloqueadas.php b/app/Controller/UnidadesBloqueadas.php new file mode 100644 index 0000000..9bd4107 --- /dev/null +++ b/app/Controller/UnidadesBloqueadas.php @@ -0,0 +1,83 @@ +findMany(); + echo view('ventas.operadores.unidades.list', compact('proyectos')); + } + public static function add() + { + $proyectos = model(Proyecto::class)->findMany(); + echo view('ventas.operadores.unidades.add', compact('proyectos')); + } + public static function bloquear() + { + $operador = model(ProyectoAgente::class)->findOne(get('operador')); + echo view('ventas.operadores.unidades.bloquear', compact('operador')); + } + public static function do_bloquear() + { + $operador = model(ProyectoAgente::class)->findOne(get('operador')); + $fecha = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $unidades = self::getUnidades([], 'departamentos', 1); + $unidades = self::getUnidades($unidades, 'estacionamientos', 2); + $unidades = self::getUnidades($unidades, 'bodegas', 3); + if (post('unidad') != null) { + foreach (post('unidad') as $u) { + $unidad = model(Unidad::class)->findOne($u); + if (array_search($unidad, $unidades) === false) { + $unidades []= $unidad; + } + } + } + + foreach ($unidades as $unidad) { + $data = [ + 'agente' => $operador->id, + 'unidad' => $unidad->id + ]; + $ub = model(UnidadBloqueada::class)->create($data); + $ub->new($fecha); + } + header('Location: ' . nUrl('unidades_bloqueadas', 'list')); + } + protected static function getUnidades(array $unidades, string $name, int $tipo): array + { + if (trim(post($name)) == '') { + return $unidades; + } + $unis = []; + $separators = [PHP_EOL, ';', ',', '-']; + foreach ($separators as $separator) { + if (strpos(post($name), $separator) !== false) { + $unis = explode($separator, post($name)); + break; + } + } + if (count($unis) == 0) { + return $unidades; + } + array_walk($unis, function(&$item) { + $item = trim($item); + $item = model(Unidad::class)->where('descripcion', $item)->where('tipo', 1)->findOne(); + }); + foreach ($unis as $uni) { + if (array_search($uni, $unidades) === false) { + $unidades []= $uni; + } + } + return $unidades; + } +} diff --git a/app/Controller/Ventas.php b/app/Controller/Ventas.php new file mode 100644 index 0000000..e66faf2 --- /dev/null +++ b/app/Controller/Ventas.php @@ -0,0 +1,623 @@ +findOne($proyecto); + $ventas = $proyecto->ventas(); + self::sort($ventas); + return view('ventas.list', compact('proyecto', 'ventas')); + } + protected static function sort(&$ventas) + { + $sort = get('sort'); + if ($sort == null) { + $sort = 'departamento'; + } + $direction = get('sort_dir'); + if ($direction == null) { + $direction = 1; + } + switch ($sort) { + case 'departamento': + usort($ventas, function($a, $b) use ($direction) { + return ($a->propiedad()->unidad()->descripcion - $b->propiedad()->unidad()->descripcion) * $direction; + }); + break; + case 'propietario': + usort($ventas, function($a, $b) use ($direction) { + $pa = trim($a->propietario()->nombreCompleto(true), ', '); + $pb = trim($b->propietario()->nombreCompleto(true), ', '); + return $direction * strcasecmp($pa, $pb); + }); + break; + case 'valor_uf': + usort($ventas, function($a, $b) use ($direction) { + return $direction * ($a->valor_uf - $b->valor_uf); + }); + break; + case 'uf_m2': + usort($ventas, function($a, $b) use ($direction) { + return $direction * ($a->uf_m2() - $b->uf_m2()); + }); + break; + case 'fecha_venta': + usort($ventas, function($a, $b) use ($direction) { + return ($a->fecha()->timestamp - $b->fecha()->timestamp) * $direction; + }); + break; + } + if ($direction == 'desc') { + $ventas = array_reverse($ventas); + } + } + public static function listProyectos() + { + $proyectos = model(Proyecto::class) + ->select('proyecto.*') + ->join('estado_proyecto', ['estado.proyecto', '=', 'proyecto.id'], 'estado') + ->join('tipo_estado_proyecto', ['tipo.id', '=', 'estado.estado'], 'tipo') + ->join('etapa_proyecto', ['etapa.id', '=', 'tipo.etapa'], 'etapa') + ->whereGte('etapa.orden', 4) + ->orderByAsc('proyecto.descripcion') + ->groupBy('proyecto.id') + ->findMany(); + echo view('ventas.proyectos', compact('proyectos')); + } + public static function show() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + return view('ventas.show', compact('venta')); + } + public static function new() + { + $proyectos = model(Proyecto::class) + ->select('proyecto.*') + ->join('estado_proyecto', ['estado.proyecto', '=', 'proyecto.id'], 'estado') + ->join('tipo_estado_proyecto', ['tipo.id', '=', 'estado.estado'], 'tipo') + ->join('etapa_proyecto', ['etapa.id', '=', 'tipo.etapa'], 'etapa') + ->whereGte('etapa.orden', 3) + ->orderByAsc('proyecto.descripcion') + ->groupBy('proyecto.id') + ->findMany(); + $regiones = model(Region::class)->order_by_asc('numeracion')->findMany(); + return view('ventas.add', compact('proyectos', 'regiones')); + } + public static function agregar() + { + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $t = Carbon::today(config('app.timezone')); + $uf = uf($f); + + $calle = trim(post('calle')); + $numero = post('numero'); + $extra = trim(post('extra')); + $comuna = post('comuna'); + $direccion = model(Direccion::class) + ->where('calle', $calle) + ->where('numero', $numero) + ->where('extra', $extra) + ->where('comuna', $comuna) + ->findOne(); + if (!$direccion) { + $direccion = model(Direccion::class)->create(); + $direccion->calle = $calle; + $direccion->numero = $numero; + $direccion->extra = $extra; + $direccion->comuna = $comuna; + $direccion->save(); + } + + list($rut, $dv) = explode('-', str_replace('.', '', post('rut'))); + $propietario = model(Propietario::class)->where('rut', $rut)->findOne(); + if (!$propietario) { + $propietario = model(Propietario::class)->create(); + $propietario->rut = $rut; + $propietario->dv = $dv; + $propietario->nombres = trim(post('nombres')); + $propietario->apellido_paterno = trim(post('paterno')); + $propietario->apellido_materno = trim(post('materno')); + $propietario->direccion = $direccion->id; + if (post('otro') != null) { + $propietario->otro = 1; + } + + $propietario->save(); + } + + $unis = json_decode(post('unidades')); + $id_principal = array_shift($unis); + $principal = model(Unidad::class)->findOne(post('unidad' . $id_principal)); + $propiedad = model(Propiedad::class) + ->select('propiedad.*') + ->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal']) + ->where('propiedad.unidad_principal', $principal->id) + ->where('unidad.proyecto', post('proyecto')) + ->orderByDesc('propiedad.id') + ->findOne(); + // Revisar si existe la propiedad y si está vigente. + if (!$propiedad or ($propiedad->venta() and $propiedad->venta()->estado() and $propiedad->venta()->estado()->tipo()->descripcion != 'vigente')) { + if (!$propiedad) { + $propiedad = model(Propiedad::class)->create(); + } + $propiedad->unidad_principal = $principal->id; + $propiedad->save(); + $data = [ + 'propiedad' => $propiedad->id, + 'unidad' => $principal->id, + 'principal' => 1 + ]; + $pu = model(PropiedadUnidad::class)->create($data); + $pu->save(); + foreach ($unis as $id_unidad) { + $data = [ + 'propiedad' => $propiedad->id, + 'unidad' => post('unidad' . $id_unidad), + 'principal' => 0 + ]; + $pu = model(PropiedadUnidad::class)->create($data); + $pu->save(); + } + /*$ests = []; + $bods = []; + foreach ($unis as $id_unidad) { + $unidad = model(Unidad::class)->findOne(post('unidad' . $id_unidad)); + if ($unidad->tipo == 2) { + $ests []= $unidad->id; + } + if ($unidad->tipo == 3) { + $bods []= $unidad->id; + } + } + $propiedad->estacionamientos = implode(';', $ests); + $propiedad->bodegas = implode(';', $bods); + $propiedad->save();*/ + } elseif ($propiedad->venta() and $propiedad->venta()->estado()->tipo()->descripcion == 'vigente') { + // Existe la propiedad en este proyecto y está vigente. Error, no se debiese vender si está vigente. + throw new \Exception('Existe la propiedad en este proyecto y está vigente. Error, no se debiese vender si está vigente.'); + } + + $venta = model(Venta::class)->create(); + $venta->propietario = $propietario->rut; + $venta->propiedad = $propiedad->id; + if (post('pie')) { + $pie = model(Pie::class)->create(); + $pie->valor = post('pie'); + $pie->fecha = $f->format('Y-m-d'); + $pie->cuotas = post('cuotas'); + $pie->uf = $uf->uf->value; + $pie->save(); + + $venta->pie = $pie->id; + } + if (post('bono_pie')) { + $bono = model(BonoPie::class)->create(); + $bono->valor = post('bono_pie'); + + $pago = model(Pago::class)->create(); + $pago->fecha = $f->format('Y-m-d'); + $pago->uf = $uf->uf->value; + $pago->valor = $bono->valor * $uf->uf->value; + $pago->tipo = 8; + $pago->new(); + + $bono->pago = $pago->id; + $bono->save(); + + $venta->bono_pie = $bono->id; + } + if (post('credito')) { + $pago = model(Pago::class)->create(); + $pago->fecha = $f->format('Y-m-d'); + $pago->uf = $uf->uf->value; + $pago->valor = post('credito') * $uf->uf->value; + $pago->tipo = 2; + $pago->new(); + + $credito = model(Credito::class)->create(); + $credito->pago = $pago->id; + $credito->save(); + + $venta->credito = $credito->id; + } + + $venta->fecha = $f->format('Y-m-d'); + $venta->valor_uf = post('valor'); + $venta->fecha_ingreso = $t->format('Y-m-d'); + if (post('operador') != 0) { + $venta->agente = post('operador'); + } + $venta->uf = $uf->uf->value; + $venta->new(); + + if (post('promociones') != 0) { + $promos = json_decode(post('promociones')); + foreach ($promos as $id_promo) { + $promocion = model(Promocion::class)->findOne(post('promocion' . $id_promo)); + $promo = model(PromocionVenta::class)->create(); + $promo->promocion = $promocion->id; + $promo->venta = $venta->id; + $promo->valor = post('promo' . $id_promo); + $promo->save(); + } + } + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function edit() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->findMany(); + $regiones = model(Region::class)->order_by_asc('numeracion')->findMany(); + return view('ventas.edit', compact('venta', 'proyectos', 'regiones')); + } + public static function editar() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $uf = uf($f); + + $valor = correctNumber(post('valor')); + $change = false; + if ($venta->fecha != $f->format('Y-m-d')) { + $venta->fecha = $f->format('Y-m-d'); + $venta->uf = $uf->uf->value; + $change = true; + } + if ($venta->valor_uf != $valor) { + $venta->valor_uf = $valor; + $change = true; + } + if ($change) { + $venta->save(); + } + + $direccion = $venta->propietario()->direccion(); + $calle = post('calle'); + $numero = post('numero'); + $extra = post('extra'); + $comuna = post('comuna'); + $change = false; + if ($direccion->calle != $calle) { + $direccion->calle = $calle; + $change = true; + } + if ($direccion->numero != $numero) { + $direccion->numero = $numero; + $change = true; + } + if ($direccion->extra != $extra) { + $direccion->extra = $extra; + $change = true; + } + if ($direccion->comuna != $comuna) { + $direccion->comuna = $comuna; + $change = true; + } + if ($change) { + $direccion->save(); + } + + $propietario = $venta->propietario(); + list($rut, $dv) = explode('-', str_replace('.', '', post('rut'))); + $nombres = post('nombres'); + $paterno = post('paterno'); + $materno = post('materno'); + $change = false; + if ($propietario->rut != $rut) { + $propietario->rut = $rut; + $propietario->dv = $dv; + $venta->propietario = $rut; + $venta->save(); + $change = true; + } + if ($propietario->nombres != $nombres) { + $propietario->nombres = $nombres; + $change = true; + } + if ($propietario->apellido_paterno != $paterno) { + $propietario->apellido_paterno = $paterno; + $change = true; + } + if ($propietario->apellido_materno != $materno) { + $propietario->apellido_materno = $materno; + $change = true; + } + if ($change) { + $propietario->save(); + } + + $unidades = json_decode(post('unidades')); + if (count($unidades) > 0) { + $propiedad = $venta->propiedad(); + $ests = explode(';', $propiedad->estacionamientos); + $bods = explode(';', $propiedad->bodegas); + $change = false; + foreach ($unidades as $n) { + $id = post('unidad' . $n); + $unidad = model(Unidad::class)->findOne($id); + if ($unidad->tipo == 1 and $propiedad->unidad_principal != $unidad->id) { + $propiedad->unidad_principal = $unidad->id; + $change = true; + } + if ($unidad->tipo == 2 and array_search($unidad->id, $ests) === false) { + $ests []= $unidad->id; + } + if ($unidad->tipo == 3 and array_search($unidad->id, $bods) === false) { + $bods []= $unidad->id; + } + } + $ests = implode(';', $ests); + $bods = implode(';', $bods); + if ($propiedad->estacionamientos != $ests) { + $propiedad->estacionamientos = $ests; + $change = true; + } + if ($propiedad->bodegas != $bods) { + $propiedad->bodegas = $bods; + $change = true; + } + if ($change) { + $propiedad->save(); + } + } + + if (post('pie')) { + $pie = $venta->pie(); + $valor = correctNumber(post('pie')); + $cuotas = post('cuotas'); + $change = false; + if ($pie->valor != $valor) { + $pie->valor = $valor; + $change = true; + } + if ($pie->cuotas != $cuotas) { + $pie->cuotas = $cuotas; + $change = true; + } + if ($change) { + $pie->save(); + } + } + + $credito = $venta->credito(); + $valor = post('credito'); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function desistir() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + return view('ventas.desist', compact('venta')); + } + public static function desistiendo() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $valor = correctNumber(post('pago')); + $uf = uf($f); + + $venta->estado = 0; + $tipo = model(TipoEstadoVenta::class)->where('descripcion', 'desistida')->findOne(); + $data = [ + 'venta' => $venta->id, + 'estado' => $tipo->id, + 'fecha' => $f->format('Y-m-d') + ]; + $estado = model(EstadoVenta::class)->create($data); + $propiedad = $venta->propiedad(); + $propiedad->estado = 0; + $pago = model(Pago::class)->create(); + $pago->fecha = $f->format('Y-m-d'); + $pago->valor = (double) $valor; + $pago->uf = $uf->uf->value; + $pago->tipo = 1; + + $pago->new(); + $propiedad->save(); + $estado->save(); + $venta->resciliacion = $pago->id; + $venta->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function ceder() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + return view('ventas.ceder', compact('venta')); + } + public static function cediendo() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + $nueva_venta = model(Venta::class)->create(); + + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + + list($rut, $dv) = explode('-', str_replace('.', '', post('rut'))); + $propietario = model(Propietario::class)->where('rut', $rut)->findOne(); + if (!$propietario) { + $propietario = model(Propietario::class)->create(); + $propietario->rut = $rut; + $propietario->dv = $dv; + $propietario->nombres = trim(post('nombres')); + $propietario->apellido_paterno = trim(post('paterno')); + $propietario->apellido_materno = trim(post('materno')); + $propietario->direccion = $direccion->id; + if (post('otro') != null) { + $propietario->otro = 1; + } + + $propietario->save(); + } + + $nueva_venta->fecha_ingreso = $f->format(); + $nueva_venta->estado = 1; + $cols = [ + 'propiedad', + 'pie', + 'bono_pie', + 'credito', + 'escritura', + 'subsidio', + 'fecha', + 'valor_uf', + 'agente', + 'uf' + ]; + foreach ($cols as $col) { + $nueva_venta->{$col} = $venta->{$col}; + } + $nueva_venta->new(); + + $venta->estado = -1; + $tipo = model(TipoEstadoVenta::class)->where('descripcion', 'cedida')->findOne(); + $data = [ + 'venta' => $venta->id, + 'estado' => $tipo->id, + 'fecha' => $f->format('Y-m-d') + ]; + $estado = model(EstadoVenta::class)->create($data); + $estado->save(); + + $venta->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function entregar() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + return view('ventas.entregar', compact('venta')); + } + public static function consolidacion() + { + if (get('proyecto')) { + $id_proyecto = get('proyecto'); + $proyecto = model(Proyecto::class)->findOne($id_proyecto); + + $ventas = $proyecto->ventas(); + set_time_limit(count($ventas)); + + $f = Carbon::today(config('app.timezone')); + setlocale(LC_TIME, 'es'); + + return view('ventas.consolidacion.show', compact('ventas', 'f')); + } else { + $proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many(); + return view('ventas.consolidacion.proyectos', compact('proyectos')); + } + } + public static function devolucion() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + $uf = uf(Carbon::now(config('app.config')))->uf->value; + $valor = round($venta->saldo() * $uf); + + return view('ventas.devolucion', compact('venta', 'valor', 'uf')); + } + public static function devolver() + { + $id = get('venta'); + $venta = model(Venta::class)->findOne($id); + + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $uf = uf($f); + $valor = correctNumber(post('valor')); + + $data = [ + 'fecha' => $f->format('Y-m-d'), + 'valor' => $valor, + 'tipo' => 1, + 'uf' => $uf->uf->value, + 'identificador' => post('identificador'), + 'banco' => 0 + ]; + + $banco = model(Banco::class)->where('nombre', post('banco'))->findOne(); + if ($banco) { + $data['banco'] = $banco->id; + } + + $pago = model(Pago::class)->create($data); + $pago->newPagado(); + + $venta->devolucion = $pago->id; + $venta->save(); + header('Location: ' . url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $venta->id])); + } + public static function resciliaciones() + { + $resciliaciones = model(Venta::class)->where('estado', 0)->findMany(); + + return view('ventas.resciliaciones', compact('resciliaciones')); + } + public static function firmar() + { + $venta = \model(Venta::class)->findOne(get('venta')); + return view('ventas.firmar', compact('venta')); + } + public static function firmando() + { + $venta = \model(Venta::class)->findOne(get('venta')); + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $venta->firmar($f); + header('Location: ' . nUrl('ventas', 'show', ['venta' => $venta->id])); + + } + public static function archivar() + { + $venta = \model(Venta::class)->findOne(get('venta')); + return view('ventas.archivar', compact('venta')); + } + public static function archivando() + { + $venta = \model(Venta::class)->findOne(get('venta')); + $f = Carbon::createFromDate(post('year'), post('month'), post('day'), config('app.timezone')); + $venta->archivar($f); + header('Location: ' . nUrl('ventas', 'show', ['venta' => $venta->id])); + } +} +?> diff --git a/app/Definition/Controller.php b/app/Definition/Controller.php new file mode 100644 index 0000000..c0e3dae --- /dev/null +++ b/app/Definition/Controller.php @@ -0,0 +1,31 @@ +isPublic()) { + + return self::{$action}(); + } + } + if (self::$default == null and \method_exists(self::class, 'setDefault')) { + self::setDefault(); + } + if (self::$default == null) { + header('Location: .'); + return; + } + return self::$default; + } +} +?> \ No newline at end of file diff --git a/app/Definition/hasEstado.php b/app/Definition/hasEstado.php new file mode 100644 index 0000000..014fe8a --- /dev/null +++ b/app/Definition/hasEstado.php @@ -0,0 +1,38 @@ +getTable(); + $self = Stringy::create(get_class($this)); + $ns = $self->substr(0, $self->indexOfLast('\\')); + $self = $self->substr($self->indexOfLast('\\') + 1); + $column = $self->underscored(); + $class = $ns . '\\Estado' . $self; + if (substr($table, -1, 1) == 's') { + $column .= '_id'; + } + + return $this->has_many($class, $column)->findMany(); + } + public function estado() + { + $table = $this->getTable(); + $self = Stringy::create(get_class($this)); + $ns = $self->substr(0, $self->indexOfLast('\\')); + $self = $self->substr($self->indexOfLast('\\') + 1); + $column = $self->underscored(); + $class = $ns . '\\Estado' . $self; + if (substr($table, -1, 1) == 's') { + $column .= '_id'; + } + + $id = $this->has_many($class, $column)->max('id'); + return $this->has_many($class, $column)->findOne($id); + } +} +?> \ No newline at end of file diff --git a/app/Definition/hasRUT.php b/app/Definition/hasRUT.php new file mode 100644 index 0000000..8ba3d80 --- /dev/null +++ b/app/Definition/hasRUT.php @@ -0,0 +1,20 @@ +rut) . '-' . $this->dv; + } +} +?> \ No newline at end of file diff --git a/app/Exception/PropertyNotFound.php b/app/Exception/PropertyNotFound.php new file mode 100644 index 0000000..a35e537 --- /dev/null +++ b/app/Exception/PropertyNotFound.php @@ -0,0 +1,16 @@ +class = $class; + $this->property = $property; + $msg = "Property '" . $property . "' for class '" . $class . "' not found."; + parent::__construct($msg); + } +} \ No newline at end of file diff --git a/app/Helper/Color.php b/app/Helper/Color.php new file mode 100644 index 0000000..68c3199 --- /dev/null +++ b/app/Helper/Color.php @@ -0,0 +1,169 @@ +color = $args[0]; + break; + } + $this->color = $this->hex2dec($this->hex2array($args[0])); + break; + case 2: + if (is_array($args[0])) { + $this->color = $args[0]; + $this->color []= $args[1]; + break; + } + $color = $this->hex2array($args[0]); + $color []= $args[1]; + $this->color = $this->hex2dec($color); + break; + case 3: + case 4: + if (is_numeric($args[0])) { + $this->color = $args; + break; + } + $this->color = $this->hex2dec($args); + break; + } + } + protected function hex2dec(array $hex) + { + return array_map('hexdec', $hex); + } + protected function dec2hex(array $bin) + { + return array_map('dechex', $bin); + } + protected function hex2array(string $hex) + { + switch (strlen($hex)) { + case 3: + case 4: + case 6: + case 7: + return str_split($hex, 2); + default: + throw new OutOfBoundsException('The string ' . $hex . ' is not a correct color code.'); + } + } + protected function array2hex(array $arr) + { + return implode('', $arr); + } + + public function convertTo($type) + { + switch (strtolower($type)) { + case 'hex': + if (is_numeric($this->color[0])) { + $this->color = $this->dec2hex($this->color); + } + break; + case 'dec': + if (!is_numeric($this->color[0])) { + $this->color = $this->hex2dec($this->color); + } + break; + default: + throw new InvalidArgumentException($type . ' is not a valid argument.'); + } + } + public function add($base_color, $amount) + { + $changed = false; + if (!is_numeric($this->color)) { + $this->convertTo('dec'); + $changed = true; + } + switch (strtolower($base_color)) { + case 'r': + $base_color = 0; + break; + case 'g': + $base_color = 1; + break; + case 'b': + $base_color = 2; + break; + case 'a': + $base_color = 3; + break; + default: + throw new OutOfBoundsException("Base color '" . $base_color . "' does not exist."); + } + $this->color[$base_color] += $amount; + if ($changed) { + $this->convertTo('hex'); + } + } + public function print() + { + $this->convertTo('hex'); + return implode('', $this->color); + } + public function toRGB() + { + $changed = false; + $this->convertTo('dec'); + $str = 'rgb(' . implode(', ', array_map(function($a) { + return round($a, 2); + }, $this->color)) . ')'; + if ($changed) { + $this->convertTo('hex'); + } + return $str; + } + public function __toString() + { + return $this->print(); + } + public function toArray() + { + return $this->color; + } + public function toVector() + { + $changed = false; + $this->convertTo('dec'); + $arr = $this->toArray(); + if ($changed) { + $this->convertTo('hex'); + } + return $arr; + } + public function luminosity() + { + $changed = false; + $this->convertTo('dec'); + //sqrt( 0.299*R^2 + 0.587*G^2 + 0.114*B^2 ) + $str = sqrt(0.299 * pow($this->color[0], 2) + 0.587 * pow($this->color[1], 2) + 0.114 * pow($this->color[2], 2)) / 255 * 100; + if ($changed) { + $this->convertTo('hex'); + } + return $str; + } + public function isDark() + { + if ($this->luminosity() < 50) { + return true; + } + return false; + } + public function isBright() + { + if ($this->luminosity() > 75) { + return true; + } + return false; + } +} diff --git a/app/Helper/Line.php b/app/Helper/Line.php new file mode 100644 index 0000000..02cc0d9 --- /dev/null +++ b/app/Helper/Line.php @@ -0,0 +1,61 @@ +origin = $point_a; + $this->length = $this->distance($point_a, $point_b); + $this->direction = $this->gradient($point_a, $point_b); + } + public function origin() + { + return $this->origin; + } + public function length() + { + return $this->length; + } + public function direction() + { + return $this->direction; + } + /** + * Calculate the gradient to move from point a to point b + * @param array $point_a [Vector] + * @param array $point_b [Vector] + * @return array [Vector] + */ + public function gradient($point_a, $point_b) + { + $distance = $this->distance($point_a, $point_b); + return array_map(function($a, $b) use ($distance) { + return ($a - $b) / $distance; + }, $point_b, $point_a); + } + // sqrt((a0-b0)²+(a1-b1)²+(a2-b2)²) + public function distance($point_a, $point_b) + { + return sqrt(array_sum(array_map(function($a, $b) { + return pow($a - $b, 2); + }, $point_a, $point_b))); + } + /** + * Move from point in the direction of the gradient acording to step_size + * @param array $point [Vector] + * @param int $step_size [step size] + * @return array [Vector] + */ + public function move($point, $step_size) + { + $gradient = $this->direction; + return array_map(function($a, $b) use ($step_size) { + return $a + $b * $step_size; + }, $point, $gradient); + } +} diff --git a/app/Helper/functions.php b/app/Helper/functions.php new file mode 100644 index 0000000..abafe62 --- /dev/null +++ b/app/Helper/functions.php @@ -0,0 +1,140 @@ +copy()->endOfMonth()->addDays(9); + if ($date->greaterThanOrEqualTo($next_m_9)) { + return (object) ['total' => 0]; + } + $url = 'http://' . config('locations.money') . '/api/uf/value/' . $date->format('Y-m-d'); + $client = new \Goutte\Client(); + $client->setHeader('Accept', 'application/json'); + $client->request('GET', $url); + + $response = $client->getResponse(); + if (!$response) { + return (object) ['total' => 0]; + } + $status = $response->getStatusCode(); + if ($status >= 200 and $status < 300) { + $data = json_decode($response->getContent()); + return $data; + } + return (object) ['total' => 0]; +} +function format($tipo, $valor, $format = null, $print = false) { + if (strtolower($tipo) == 'localdate') { + $d = \Carbon\Carbon::parse($valor); + $d->locale('es_ES'); + if ($format == null) { + $format = 'DD [de] MMMM [de] YYYY'; + } + return $d->isoFormat($format); + } + if (method_exists('\App\Helper\Format', $tipo)) { + if ($print) { + return \App\Helper\Format::$tipo($valor, $print); + } else { + return \App\Helper\Format::$tipo($valor); + } + } else { + switch ($tipo) { + case 'localDate': + if (isset($format)) { + $intl = new IntlDateFormatter('es_ES', IntlDateFormatter::SHORT, IntlDateFormatter::SHORT, 'America/Santiago'); + $intl->setPattern($format); + return ucwords($intl->format($valor)); + } + case 'percent': + return \App\Helper\Format::number($valor, 2); + case 'rut': + return \App\Helper\Format::number($valor, 0); + } + } +} +function model(string $class_name) { + return \Model::factory($class_name); +} +function correctNumber($number) { + if (strpos($number, ',') !== false) { + return str_replace(',', '.', str_replace('.', '', $number)); + } elseif (substr_count($number, '.') > 1) { + return str_replace('.', '', $number); + } + return $number; +} +function parseRanges($range, $numeric = true, $negatives = true) { + $rns = preg_split('/[,;]+/', $range); + $data = []; + foreach ($rns as $p) { + if (!$negatives) { + if (strpos($p, '-') !== false) { + list($ini, $end) = explode('-', $p); + $data = array_merge($data, range($ini, $end)); + continue; + } + } + if ($numeric) { + $data []= (float) $p; + continue; + } + $data []= $p; + } + return $data; +} +function nUrl($p, $a = null, $data = null) { + $query = ['p' => $p]; + if ($a != null) { + $query['a'] = $a; + if ($data != null) { + $query = array_merge($query, $data); + } + } + return url('', $query); +} +function api($p, $a, $data = null) { + $url = baseUrl() . '/' . 'api'; + $url .= '?' . 'p=' . $p . '&a=' . $a . '&API_KEY=1'; + if ($data != null) { + $url .= '&' . implode('&', array_map(function($val, $k) { + return $k . '=' . $val; + }, $data)); + } + return $url; +} +function doLog($user, $action, $variables) { + App\Service\Register::log($user, $action, $variables); +} +?> diff --git a/app/Service/Auth.php b/app/Service/Auth.php new file mode 100644 index 0000000..7af1f48 --- /dev/null +++ b/app/Service/Auth.php @@ -0,0 +1,163 @@ +getCookie(); + } + protected function getCookie() + { + if (isset($_COOKIE['rememberMe'])) { + list($s, $t) = \explode(':', $_COOKIE['rememberMe']); + $this->selector = $s; + $this->token = $t; + } + } + protected function saveCookie() + { + $now = \Carbon\Carbon::now(config('app.timezone')); + $exp = $now->addHours(config('app.login_hours')); + \setcookie('rememberMe', $this->selector . ':' . $this->token, $exp->timestamp); + } + protected function clearCookie() + { + \setcookie('rememberMe', '', \Carbon\Carbon::now(config('app.timezone'))->timestamp); + } + protected function generateToken() + { + $this->selector = bin2hex(\random_bytes(12)); + $this->token = bin2hex(\random_bytes(20)); + } + public function login($username, $password) + { + $user = \Model::factory(\Incoviba\common\User::class)->where('name', $username)->where('enabled', 1)->findOne(); + if ($user !== false) { + if (\password_verify($password, $user->password) === false) { + $this->clearCookie(); + return false; + } + + $this->generateToken(); + $now = \Carbon\Carbon::now(config('app.timezone')); + $exp = $now->addHours(-config('app.login_hours')); + $auth = \Model::factory(\Incoviba\common\Auth::class)->where('user_id', $user->id)->whereGt('time', $exp->timestamp)->where('status', 1)->findOne(); + if ($auth !== false) { + $auth->time('now'); + $auth->selector = $this->selector; + $auth->token($this->token); + $auth->save(); + $this->saveCookie(); + return true; + } + + $auth = \Model::factory(\Incoviba\common\Auth::class)->create(); + $auth->user_id = $user->id; + $auth->time('now'); + $auth->selector = $this->selector; + $auth->token($this->token); + + try { + $auth->save(); + $this->saveCookie(); + return true; + } catch (\Exception $e) { + $this->clearCookie(); + return false; + } + } + return false; + } + public function isIn() + { + if ($this->selector == null) { + return false; + } + $auths = \Model::factory(\Incoviba\common\Auth::class)->where('selector', $this->selector)->findMany(); + if ($auths === false) { + $this->clearCookie(); + return false; + } + foreach ($auths as $auth) { + if (\password_verify($this->token, $auth->token)) { + return $auth->isIn(); + } + } + return false; + } + public function User() + { + if ($this->selector == null) { + return false; + } + $auths = \Model::factory(\Incoviba\common\Auth::class)->where('selector', $this->selector)->findMany(); + if ($auths === false) { + return false; + } + foreach ($auths as $auth) { + if (\password_verify($this->token, $auth->token)) { + return $auth->user(); + } + } + return false; + } + public function hasAccess() + { + if ($this->selector == null) { + return false; + } + $auths = \Model::factory(\Incoviba\common\Auth::class)->where('selector', $this->selector)->findMany(); + if ($auths === false) { + return false; + } + foreach ($auths as $auth) { + if (\password_verify($this->token, $auth->token)) { + return $auth->user()->hasAccess(); + } + } + return false; + } + public function checkAccess($controller, $action = null) + { + if ($this->selector == null) { + return false; + } + $auths = \Model::factory(\Incoviba\common\Auth::class)->where('selector', $this->selector)->findMany(); + if ($auths === false) { + return false; + } + foreach ($auths as $auth) { + if (\password_verify($this->token, $auth->token)) { + return $auth->user()->checkAccess($controller, $action); + } + } + return false; + } + public function logout() + { + $this->clearCookie(); + if ($this->selector == null) { + return true; + } + $auths = \Model::factory(\Incoviba\common\Auth::class)->where('selector', $this->selector)->findMany(); + if ($auths === false) { + return true; + } + foreach ($auths as $auth) { + if (\password_verify($this->token, $auth->token)) { + $auth->status = 0; + try { + $auth->save(); + return true; + } catch (\Exception $e) { + return false; + } + } + } + return true; + } +} diff --git a/app/Service/Borrador.php b/app/Service/Borrador.php new file mode 100644 index 0000000..4f4b3af --- /dev/null +++ b/app/Service/Borrador.php @@ -0,0 +1,118 @@ +cierre = $cierre; + $this->lineas = []; + } + protected function add(string $str, int $new_line = 0) + { + $this->lineas []= $str; + if ($new_line > 0) { + $this->newLine($new_line); + } + } + protected function newLine($n = 1) + { + for ($i = 0; $i < $n; $i ++) { + $this->lineas []= ''; + } + } + protected function load() + { + $this->word = IOFactory::load('borrador-' . $this->cierre->proyecto()->nombre . '.docx'); + } + protected function extract() + { + $this->load(); + $data = []; + foreach ($this->word->getSections() as $section) { + foreach ($section->getElements() as $element) { + $r = $this->elementGet($element); + $data []= $r; + } + } + if (count($data) > 0) { + $this->text = $data; + } + } + protected function elementGet($element) + { + if ($element instanceof TextBreak) { + return PHP_EOL; + } + if ($element instanceof TextRun) { + $data = []; + foreach ($element->getElements() as $e) { + $data []= $this->elementGet($e); + } + return implode('', $data); + } + if (!method_exists($element, 'getText')) { + d($element); + } + return $element->getText(); + } + protected function build() + { + if ($this->text == null) { + $this->extract(); + } + foreach ($this->text as $line) { + if ($line == PHP_EOL) { + $this->newLine(); + continue; + } + if (strpos($line, '[[') !== false) { + $replacer = new Replacer(); + $this->add($replacer->replace($line, $this->cierre)); + continue; + } + $this->add($line); + } + } + public function create() + { + $output = new PhpWord(); + + $output->getSettings()->setDecimalSymbol(','); + $output->getSettings()->setThemeFontLang(new Language(Language::ES_ES)); + + $section = $output->addSection(); + foreach ($this->lineas as $linea) { + if ($linea == '') { + $section->addTextBreak(); + continue; + } + $section->addText($linea); + } + + $output->getSettings()->setTrackRevisions(true); + + $writer = IOFactory::createWriter($output); + $filename = 'Borrador ' . $this->cierre->propietario()->nombreCompleto() . ' con ' . $this->cierre->proyecto()->inmobiliaria()->razon_social . '.docx'; + $writer->save($filename); + } + public function show() + { + $this->build(); + return implode(PHP_EOL, $this->lineas); + } +} +?> \ No newline at end of file diff --git a/app/Service/DBToModel.php b/app/Service/DBToModel.php new file mode 100644 index 0000000..158e85c --- /dev/null +++ b/app/Service/DBToModel.php @@ -0,0 +1,158 @@ +name = $name; + $this->db = \ORM::get_db($name); + } + + public function run() + { + $this->getTables(); + foreach ($this->tables as $table) { + if ($this->createClass($table)) { + echo 'ok
', PHP_EOL; + } + } + } + protected function getType($type) + { + if (strpos($type, '(') !== false) { + $type = substr($type, 0, strpos($type, '(')); + } + if (strpos($type, ' ') !== false) { + $type = substr($type, 0, strpos($type, ' ')); + } + switch ($type) { + case 'int': + case 'float': + case 'double': + case 'char': + return trim($type); + case 'date': + case 'datetime': + return trim(strtolower($type)); + case 'varchar': + case 'text': + case 'blob': + return 'string'; + case 'bigint': + case 'tinyint': + case 'enum': + return 'int'; + default: + d($type); + } + } + protected function getTables() + { + $q = "SHOW TABLES"; + $st = $this->db->query($q); + $results = $st->fetchAll(\PDO::FETCH_COLUMN); + $this->tables = []; + foreach ($results as $result) { + $this->tables []= $result; + } + } + protected function getColumns($table) + { + $q = "SHOW COLUMNS FROM `" . $table . "`"; + $st = $this->db->query($q); + $results = $st->fetchAll(\PDO::FETCH_OBJ); + return $results; + } + protected function phpDoc($columns) + { + $str = ['/**']; + $str []= ' *'; + foreach ($columns as $column) { + $str []= ' * @property ' . $this->getType($column->Type) . ' ' . $column->Field; + } + $str []= ' *'; + $str []= ' */'; + + return implode(PHP_EOL, $str); + } + protected function className($table) + { + $name = Stringy::create($table)->upperCamelize(); + return $name; + } + protected function createClass($table) + { + $class = '' . $this->className($table); + $columns = $this->getColumns($table); + $docs = $this->phpDoc($columns); + + $output = ['name}';"; + $output []= '}'; + $output []= '?>'; + + //d(implode(PHP_EOL, $output)); + + $filename = realpath(root() . '/src') . DIRECTORY_SEPARATOR . $class . '.php'; + return file_put_contents($filename, implode(PHP_EOL, $output)); + } + public function create($namespace, $table) + { + $class = '' . $this->className($table); + $columns = $this->getColumns($table); + $docs = $this->phpDoc($columns); + + $namespace = trim($namespace, '\\'); + + $output = ['name}';"; + $output []= '}'; + $output []= '?>'; + $output = implode(PHP_EOL, $output); + + $namespace = explode('\\', $namespace); + array_shift($namespace); + $namespace = implode('/', $namespace); + + $filename = realpath(root() . '/src/' . $namespace) . DIRECTORY_SEPARATOR . $class . '.php'; + + $result = [ + 'result' => false, + 'filename' => $filename, + 'output' => $output + ]; + if (!file_exists($filename)) { + $result['result'] = file_put_contents($filename, $output); + } else { + $result['result'] = true; + } + return json_encode($result); + } + public function list() + { + $this->getTables(); + $output = []; + foreach ($this->tables as $table) { + $output []= ['table' => $table, 'model' => '' . $this->className($table)]; + } + + return json_encode(['models' => $output]); + } +} +?> \ No newline at end of file diff --git a/app/Service/Factory.php b/app/Service/Factory.php new file mode 100644 index 0000000..ac7386a --- /dev/null +++ b/app/Service/Factory.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/app/Service/Informador.php b/app/Service/Informador.php new file mode 100644 index 0000000..c64db26 --- /dev/null +++ b/app/Service/Informador.php @@ -0,0 +1,463 @@ +title = $title; + } else { + $this->title = 'Informe'; + } + } + + public function addColumn(string $title, $col = '') + { + if ($col == '') { + if ($this->columns == null) { + $i = 0; + } else{ + $i = count($this->columns); + } + $col = $this->mapColumn($i); + } + + if (isset($this->columns[$col])) { + $columns = []; + foreach ($this->columns as $c => $data) { + if (ord($c) < ord($col)) { + $columns[$c] = $data; + } elseif (ord($c) == ord($col)) { + $columns[$col] = $title; + } else { + $columns[chr(ord($c) + 1)] = $data; + } + } + $this->columns = $columns; + } else { + $this->columns[$col] = $title; + } + } + public function mapColumn($n) + { + $letters = range('A', 'Z'); + $max = count($letters); + $r = $n / $max + 1; + $p = floor($r - 1) - 1; + $i = $n % $max; + if ($r >= 2) { + return $letters[$p] . $letters[$i]; + } + return $letters[$i]; + } + public function getColumn($col_title) + { + return array_search($col_title, $this->columns); + } + public function getColumnNumber($col) + { + $letters = range('A', 'Z'); + if (strlen($col) > 1) { + $ls = str_split($col); + $n = 0; + foreach ($ls as $i => $l) { + $n += array_search($l, $letters) + $i * count($letters) + 1; + } + return $n; + } + return array_search($col, $letters); + } + public function addColumns(array $columns) + { + foreach ($columns as $column) { + $this->addColumn($column); + } + } + public function addData(int $row, $data, $col = '') + { + if (!isset($this->data[$row])) { + $this->data[$row] = []; + } + if ($col == '') { + $i = count($this->data[$row]); + $col = $this->mapColumn($i); + } elseif (ctype_print($col)) { + $col = $this->getColumn($col); + } else { + $col = $this->mapColumn($col); + } + + if (isset($this->data[$row][$col])) { + $data_array = []; + foreach ($this->data[$row] as $c => $d) { + if (ord($c) < ord($col)) { + $data_array[$c] = $d; + } elseif (ord($c) == ord($col)) { + $data_array[$col] = $this->parseData($data); + } else { + $data_array[chr(ord($c) + 1)] = $d; + } + } + $this->data[$row] = $data_array; + } else { + $this->data[$row][$col] = $this->parseData($data); + } + } + protected function parseData($data) + { + if ($this->isDate($data)) { + // Date + return Date::PHPToExcel($data); + } + return $data; + } + protected function isDate($data) + { + try { + if (strpos($data, '-') === false) { + return false; + } + $fecha = explode('-', $data); + if (count($fecha) != 3) { + return false; + } + list($year, $month, $day) = $fecha; + if (strlen($year) == 4 and strlen($month) <= 2 and strlen($day) <= 2) { + return true; + } + if (ctype_digit($year) and ctype_digit($month) and ctype_digit($day)) { + $f = Carbon::parse($data, config('app.timezone')); + return true; + } + return false; + } catch(\Exception $e) { + return false; + } + return false; + } + public function addDataRow(int $row, array $data_array) + { + foreach ($data_array as $data) { + $this->addData($row, $data); + } + } + public function addDatas(array $data_matrix) + { + foreach ($data_matrix as $row => $data_array) { + $this->addDataRow($row, $data_array); + } + } + protected function findTitleColumn($title) + { + return array_search($title, $this->columns); + } + public function addFormat($format, $title = '') + { + $col = 'A'; + if ($title == '') { + $i = count($this->col_formats); + $col = $this->mapColumn($i); + } else { + $col = $this->findTitleColumn($title); + } + + if (isset($this->col_formats[$col])) { + $columns = []; + foreach ($this->col_formats as $c => $data) { + if (ord($c) < ord($col)) { + $columns[$c] = $data; + } elseif (ord($c) == ord($col)) { + $columns[$col] = $this->translateFormat($format); + } else { + $columns[chr(ord($c) + 1)] = $data; + } + } + $this->col_formats = $columns; + } else { + $this->col_formats[$col] = $this->translateFormat($format); + } + + uksort($this->col_formats, function($ak, $bk) { + return strcmp($ak, $bk); + }); + } + protected function translateFormat(array $format) + { + $translated = []; + foreach ($format as $category => $values) { + switch ($category) { + case 'numberFormat': + $data = $this->translateNumberFormat($values); + break; + case 'alignment': + $data = $this->translateAlignment($values); + break; + case 'font': + $data = $this->translateFont($values); + break; + case 'fill': + $data = $this->translateFill($values); + break; + case 'borders': + $data = $this->translateBorders($values); + break; + } + $translated[$category] = $data; + } + return $translated; + } + protected function translateNumberFormat(array $values) + { + $translated = []; + foreach ($values as $value) { + switch ($value) { + case 'short-date': + $translated['formatCode'] = 'dd-mm-yyyy'; + break; + case 'date': + $translated['formatCode'] = 'dd mmmm, yyyy'; + break; + case 'thousands': + $translated['formatCode'] = NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1; + break; + case 'pesos': + $translated['formatCode'] = '$ #.###'; + break; + default: + $translated['formatCode'] = $value; + } + } + return $translated; + } + protected function translateAlignment(array $values) + { + $translated = []; + foreach ($values as $type => $value) { + switch ($type) { + case 'horizontal': + switch ($value) { + case 'center': + $new = Alignment::HORIZONTAL_CENTER; + break; + } + break; + case 'vertical': + switch ($value) { + case 'middle': + case 'center': + $new = Alignment::VERTICAL_CENTER; + } + default: + $new = $value; + break; + } + $translated[$type] = $new; + } + return $translated; + } + protected function translateFont(array $values) + { + $translated = []; + foreach ($values as $type => $value) { + switch ($type) { + case 'color': + $new = $this->translateColor($value); + break; + default: + $new = $value; + break; + } + $translated[$type] = $new; + } + return $translated; + } + protected function translateFill(array $values) + { + $translated = []; + foreach ($values as $type => $value) { + switch ($type) { + case 'fillType': + switch ($value) { + case 'solid': + $new = Fill::FILL_SOLID; + break; + default: + $new = $value; + break; + } + break; + case 'color': + $new = $this->translateColor($value); + break; + default: + $new = $value; + break; + } + $translated[$type] = $new; + } + return $translated; + } + protected function translateBorders(array $values) + { + $translated = []; + foreach ($format as $category => $value) { + switch ($category) { + case 'allBorders': + case 'left': + case 'right': + case 'top': + case 'bottom': + case 'diagonal': + case 'vertical': + case 'horizontal': + $data = $this->translateBorder($value); + break; + default: + $data = $value; + } + $translated[$category] = $data; + } + return $translated; + } + protected function translateBorder(array $values) + { + $translated = []; + foreach ($values as $type => $value) { + switch ($type) { + case 'color': + $new = $this->translateColor($value); + break; + default: + $new = $value; + break; + } + $translated[$type] = $new; + } + return $translated; + } + protected function translateColor($color) + { + $color_definitions = [ + 'red' => 'ff0000', + 'light-red' => 'ffcccc', + 'dark-red' => 'a00000' + ]; + if (is_array($color)) { + $t = dechex(255 * $color['transparency'] / 100); + $c = $color_definitions[$color['color']]; + $hex = $t . $c; + return ['argb' => $hex]; + } + return ['rgb' => $color_definitions[$color]]; + } + public function addFormats(array $formats) + { + foreach ($formats as $title => $format) { + $this->addFormat($format, $title); + } + } + public function addTotal(string $col) + { + if (isset($this->columns[$col])) { + $sum = 0; + foreach ($this->data as $row => $data) { + $sum += $data[$col]; + } + $this->totals[$col] = $sum; + } + } + public function addAverage(string $col) + { + $this->addTotal($col); + $this->totals[$col] /= count($this->data); + } + + protected function fillData() + { + foreach ($this->data as $row => $data) { + $this->data[$row] = $this->fillAndSort($data); + } + if (count($this->totals) > 0) { + $this->totals = $this->fillAndSort($this->totals); + } + } + protected function fillAndSort(array $row) + { + foreach ($this->columns as $val) { + if (!isset($row[$val])) { + $row[$val] = ''; + } + } + function sortArrayByArray(Array $array, Array $orderArray) { + $ordered = array(); + foreach($orderArray as $key) { + if(array_key_exists($key, $array)) { + $ordered[$key] = $array[$key]; + unset($array[$key]); + } + } + return $ordered + $array; + } + $row = sortArrayByArray($row, $this->columns); + + return $row; + } + + public function informe() + { + $ea = new Spreadsheet(); + $ea->getProperties()->setCreator('Juan Pablo Vial B.'); + $ea->getProperties()->setTitle($this->title); + $ea->getProperties()->setCompany('Incoviba S.A.'); + + $ews = $ea->getActiveSheet(); + + $ews->fromArray(array($this->columns), '', 'A1'); + $ews->fromArray($this->data, '', 'A2'); + $end = 2; + if ($this->totals != null and count($this->totals) > 0) { + $ews->fromArray($this->totals, '', 'A' . count($data) + 2); + $end = 3; + } + + if ($this->col_formats != null and count($this->col_formats) > 0) { + foreach ($this->col_formats as $col => $format) { + $ews->getStyleByColumnAndRow($this->getColumnNumber($col), 2, $this->getColumnNumber($col), count($this->data) + $end)->applyFromArray($format); + } + } + + for ($col = 0; $col < count($this->columns); $col ++) { + $ews->getColumnDimensionByColumn($col)->setAutoSize(true); + } + + $ews->setAutoFilterByColumnAndRow(0, 1, count($this->columns) - 1, count($this->data)); + + $hoy = Carbon::now(config('app.timezone')); + $filename = str_replace('ñ', 'n', $this->title . ' - ' . $hoy->format('Y-m-d') . '.xlsx'); + + $writer = IOFactory::createWriter($ea, "Xlsx"); + + header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8"); + header('Content-Transfer-Encoding: binary'); + header('Content-Disposition: attachment; filename="' . $filename . '"'); + header('Cache-Control: max-age=0'); + + $writer->save('php://output'); + } +} +?> diff --git a/app/Service/Register.php b/app/Service/Register.php new file mode 100644 index 0000000..03f96e0 --- /dev/null +++ b/app/Service/Register.php @@ -0,0 +1,34 @@ + $user, + 'action' => $action, + 'time' => Carbon::now(config('app.timezone'))->toDateTimeString()//->format('Y-m-d HH:mm:ss') + ]; + $registry = model(RModel::class) + ->where('user', $user) + ->where('action', $action) + ->where('time', $data['time']) + ->findOne(); + if (!$registry) { + $registry = model(RModel::class)->create($data); + $registry->save(); + } + foreach ($variables as $data) { + $data['registry'] = $registry->id; + $log = (new Factory(RegistryData::class))->where($data)->find(); + if (!$log) { + $log = model(RegistryData::class)->create($data); + $log->save(); + } + } + } +} diff --git a/app/Service/Replacer.php b/app/Service/Replacer.php new file mode 100644 index 0000000..bf61513 --- /dev/null +++ b/app/Service/Replacer.php @@ -0,0 +1,127 @@ +parseLine($line); + + $output = $line; + foreach ($instructions as $instruction) { + $output = str_replace($instruction['original'], $this->buildLine($instruction['instruction'], $data), $output); + } + return $output; + } + protected function parseLine($line) + { + $ini_el = '[['; + $end_el = ']]'; + + $instructions = []; + $offset = 0; + while (strpos($line, $ini_el, $offset) !== false) { + $ini = strpos($line, $ini_el, $offset) + strlen($ini_el); + $end = strpos($line, $end_el, $offset); + $find = substr($line, $ini, $end - $ini); + $instructions []= ['original' => $ini_el . $find . $end_el, 'instruction' => $find]; + $offset = $end + 1; + } + return $instructions; + } + protected function buildLine($instructions, $data) + { + if (strpos($instructions, '|') !== false) { + $instructions = explode('|', $instructions); + } else { + $instructions = [$instructions]; + } + $output = ''; + foreach ($instructions as $instruction) { + $output = $this->buildReplace($instruction, $data, $output); + } + return $output; + } + protected function buildReplace($instruction, $data, $output = null) + { + if (strpos($instruction, '(') !== false) { + $ini = strpos($instruction, '(') + 1; + $end = strpos($instruction, ')'); + $mod = substr($instruction, $ini, $end - $ini); + $instruction = substr($instruction, 0, $ini - 1); + } + switch ($instruction) { + case 'UPPER': + return strtoupper($output); + case 'LOWER': + return strtolower($output); + case 'ISSET': + if ($output != '') { + return ', ' . $output; + } + return ''; + case 'UFS': + return format('ufs', $output); + case 'PESOS': + return format('pesos', $output); + } + + if (isset($mod)) { + $obj = $this->find($instruction . '(' . $mod .')', $data); + } else { + $obj = $this->find($instruction, $data); + } + if ($obj) { + return $obj; + } + if (is_object($output) and method_exists($output, $instruction)) { + if (isset($mod)) { + return $output->$instruction($mod); + } + return $output->$instruction(); + } + if (is_object($output) and isset($output->$instruction)) { + return $output->$instruction; + } + if ($instruction == 'strftime') { + setlocale(LC_TIME, 'es-CL', 'es'); + $f = Carbon::parse($output, config('app.timezone')); + $output = strftime($mod, $f->timestamp); + return $output; + } + + d($output, $instruction, function_exists($instruction), is_object($output), is_object($output) and isset($output->$instruction)); + } + protected function find($instruction, $data) + { + if (strpos($instruction, '(') !== false) { + $ini = strpos($instruction, '(') + 1; + $end = strpos($instruction, ')'); + $mod = substr($instruction, $ini, $end - $ini); + $instruction = substr($instruction, 0, $ini - 1); + } + if (method_exists($data, $instruction)) { + if (isset($mod)) { + return $data->$instruction($mod); + } + return $data->$instruction(); + } + if (isset($data->$instruction)) { + return $data->$instruction; + } + switch ($instruction) { + case 'Unidades': + $str = 'Departamento ' . $data->reserva()->unidad()->numeracion; + foreach ($data->reserva()->unidades() as $unidad) { + $str .= ', ' . ucwords($unidad->unidadProyecto()->tipo()->descripcion) . ' ' . $unidad->numeracion; + } + return $str; + case 'inmobiliaria': + return $data->proyecto()->inmobiliaria(); + } + return false; + } +} +?> \ No newline at end of file diff --git a/app/Service/Route.php b/app/Service/Route.php new file mode 100644 index 0000000..f910f87 --- /dev/null +++ b/app/Service/Route.php @@ -0,0 +1,131 @@ +add($t, $query, $callback); + } + } else { + switch (strtoupper($type)) { + case 'GET': + $this->get($query, $callback); + break; + case 'POST': + $this->post($query, $callback); + break; + } + } + } + public function get($query, $callback) + { + if ($this->exists('get', $query)) { + return; + } + $this->routes['get'][$query] = (object) ['query' => $query, 'callback' => $this->parseCallback($callback)]; + } + public function post($query, $callback) + { + if ($this->exists('post', $query)) { + return; + } + $this->routes['post'][$query] = (object) ['query' => $query, 'callback' => $this->parseCallback($callback)]; + } + protected function exists($type, $query) + { + return isset($this->routes['post'][$query]); + } + protected function parseCallback($callback) + { + if (is_callable($callback)) { + return $callback; + } + elseif (is_object($callback)) { + return [$callback, 'index']; + } + elseif (is_string($callback) and strpos($callback, '@') !== false) { + list($class, $method) = explode('@', $callback); + $class = '\\App\\Controller\\' . $class; + if (method_exists($class, $method)) { + return [$class, $method]; + } + } + elseif (is_string($callback)) { + $class = '\\App\\Controller\\' . $callback; + return [$class, 'index']; + } + } + public function route() + { + $url = $_SERVER['SCRIPT_NAME']; + $query = $_SERVER['QUERY_STRING']; + $method = $_SERVER['REQUEST_METHOD']; + $route = null; + switch (strtoupper($method)) { + case 'GET': + $route = $this->getGet($url, $query); + break; + case 'POST': + $route = $this->getPost($url, $query); + break; + } + if ($route) { + return $this->run($route->callback); + } + return false; + } + protected function getGet($url, $query) + { + if (isset($this->routes['get'][$url])) { + return $this->routes['get'][$url]; + } + $p = get('p'); + if ($p == null) { + $p = get('page'); + if ($p == null) { + $p = get('m'); + if ($p == null) { + $p = get('module'); + } + } + } + if (isset($this->routes['get'][$p])) { + return $this->routes['get'][$p]; + } + return false; + } + protected function getPost($url, $query) + { + if (isset($this->routes['post'][$url])) { + return $this->routes['post'][$url]; + } + $p = get('p'); + if ($p == null) { + $p = get('page'); + if ($p == null) { + $p = get('m'); + if ($p == null) { + $p = get('module'); + } + } + } + if (isset($this->routes['post'][$p])) { + return $this->routes['post'][$p]; + } + return false; + } + protected function run($callback) + { + return call_user_func($callback); + } +} +?> \ No newline at end of file