This commit is contained in:
2020-12-01 17:23:13 -03:00
parent 09e8c226bb
commit 9852a8cbdc
274 changed files with 24706 additions and 0 deletions

163
app/Service/Auth.php Normal file
View File

@ -0,0 +1,163 @@
<?php
namespace App\Service;
class Auth
{
protected $selector;
protected $token;
public function __construct()
{
$this->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;
}
}

118
app/Service/Borrador.php Normal file
View File

@ -0,0 +1,118 @@
<?php
namespace App\Service;
use Incoviba\nuevo\Venta\Cierre;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Element\TextBreak;
use PhpOffice\PhpWord\Element\Text;
use PhpOffice\PhpWord\Element\TextRun;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Style\Language;
class Borrador
{
protected $cierre;
protected $lineas;
protected $word;
protected $text;
public function __construct(Cierre $cierre)
{
$this->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);
}
}
?>

158
app/Service/DBToModel.php Normal file
View File

@ -0,0 +1,158 @@
<?php
namespace App\Service;
use Stringy\Stringy;
class DBToModel
{
protected $name;
protected $db;
protected $tables;
public function __construct($name = 'mysql')
{
$this->name = $name;
$this->db = \ORM::get_db($name);
}
public function run()
{
$this->getTables();
foreach ($this->tables as $table) {
if ($this->createClass($table)) {
echo 'ok<br />', 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 = ['<?php'];
$output []= '';
$output []= $docs;
$output []= 'class ' . $class . ' extends \\Model';
$output []= '{';
$output []= "\tpublic static \$_connection_name = '{$this->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 = ['<?php'];
$output []= 'namespace ' . $namespace . ';';
$output []= '';
$output []= $docs;
$output []= 'class ' . $class . ' extends \\Model';
$output []= '{';
$output []= "\tpublic static \$_connection_name = '{$this->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]);
}
}
?>

204
app/Service/Factory.php Normal file
View File

@ -0,0 +1,204 @@
<?php
namespace App\Service;
use Stringy\Stringy;
class Factory
{
protected $class;
protected $is_aggregator;
public function __construct($class)
{
$this->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() . '';
}
}

463
app/Service/Informador.php Normal file
View File

@ -0,0 +1,463 @@
<?php
namespace App\Service;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use Carbon\Carbon;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
class Informador
{
protected $title;
protected $columns;
protected $data;
protected $col_formats;
protected $totals;
public function __construct($title = '')
{
if ($title != '') {
$this->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');
}
}
?>

34
app/Service/Register.php Normal file
View File

@ -0,0 +1,34 @@
<?php
namespace App\Service;
use Carbon\Carbon;
use Incoviba\common\Registry as RModel;
class Register
{
public static function log($user, $action, $variables)
{
$data = [
'user' => $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();
}
}
}
}

127
app/Service/Replacer.php Normal file
View File

@ -0,0 +1,127 @@
<?php
namespace App\Service;
use Carbon\Carbon;
class Replacer
{
public function replace($line, $data)
{
$instructions = $this->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;
}
}
?>

131
app/Service/Route.php Normal file
View File

@ -0,0 +1,131 @@
<?php
namespace App\Service;
class Route
{
protected $routes;
public function __construct()
{
}
public function add($type, $query, $callback)
{
if (is_array($type)) {
foreach ($type as $t) {
$this->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);
}
}
?>