Browse Source

Implementando vlucas/Valitron como biblioteca de validacao na requisicao listarBilhetes, montando query de consulta de bilhetes.

1.9
Claudio Zimmermann Junior 3 months ago committed by Gitea
parent
commit
55d5e28143
  1. 0
      app/Repositories/Audita.php
  2. 0
      app/Repositories/AuditaFull.php
  3. 48
      app/Repositories/Bilhetes.php
  4. 0
      app/Repositories/Meet.php
  5. 0
      app/Repositories/MeetPeople.php
  6. 0
      app/Repositories/Organizacao.php
  7. 0
      app/Repositories/OrganizacaoUsuario.php
  8. 0
      app/Repositories/Parametro.php
  9. 0
      app/Repositories/Queue.php
  10. 0
      app/Repositories/Token.php
  11. 0
      app/Repositories/Usuario.php
  12. 38
      app/controllers/CallController.php
  13. 2
      app/core/Connection.php
  14. 115
      app/core/Repository.php
  15. 10
      app/models/Bilhetes.php
  16. 17
      app/traits/Validate.php
  17. 3
      composer.json
  18. 61
      composer.lock

0
app/models/Audita.php → app/Repositories/Audita.php

0
app/models/AuditaFull.php → app/Repositories/AuditaFull.php

48
app/Repositories/Bilhetes.php

@ -0,0 +1,48 @@
<?php
namespace app\Repositories;
use app\core\Repository;
class Bilhetes extends Repository
{
protected static string $table = 'pbx_bilhetes';
public static function getBilhetes(array $data): array
{
$query = "SELECT
a.id_bilhetes AS id, a.calldate AS data_hora,
a.src AS origem, a.dst AS destino, a.billsec AS tempo_conversacao,
a.duration AS tempo_atendimento, a.accountcode AS id_transfer,
a.uniqueid AS uniqueid, a.userfield AS nome_audio,
a.data_bilhete AS data, a.fora_horario AS fora_horario,
a.org_id
FROM pbx_bilhetes a
WHERE a.lastapp <> 'Transferred Call' ";
foreach ($data as $k => $v) {
if (!$v) {
continue;
}
if (in_array($k, ['src', 'dst', 'entry'])) {
$query .= " AND $k LIKE '%:$k%'";
continue;
}
if ($k === 'i_date') {
$query .= " AND data_bilhete >= :$k";
continue;
}
if ($k === 'f_date') {
$query .= " AND data_bilhete <= :$k";
continue;
}
$query .= " AND $k = :$k";
}
$query .= " ORDER BY data_bilhete";
return self::query($query, $data);
}
}

0
app/models/Meet.php → app/Repositories/Meet.php

0
app/models/MeetPeople.php → app/Repositories/MeetPeople.php

0
app/models/Organizacao.php → app/Repositories/Organizacao.php

0
app/models/OrganizacaoUsuario.php → app/Repositories/OrganizacaoUsuario.php

0
app/models/Parametro.php → app/Repositories/Parametro.php

0
app/models/Queue.php → app/Repositories/Queue.php

0
app/models/Token.php → app/Repositories/Token.php

0
app/models/Usuario.php → app/Repositories/Usuario.php

38
app/controllers/CallController.php

@ -2,16 +2,17 @@
namespace app\controllers; namespace app\controllers;
use app\models\Bilhetes;
use app\traits\Validate;
use Slim\Routing\RouteCollectorProxy; use Slim\Routing\RouteCollectorProxy;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
use Valitron\Validator;
use Exception; use Exception;
use app\Repositories\Bilhetes;
use app\traits\Validate;
class CallController class CallController
{ {
use Validate;
static function route() static function route()
{ {
return function (RouteCollectorProxy $group) { return function (RouteCollectorProxy $group) {
@ -23,10 +24,26 @@ class CallController
function listarBilhetes(Request $request, Response $response, array $args) function listarBilhetes(Request $request, Response $response, array $args)
{ {
try { try {
$validator = new Validator();
$validator->mapFieldsRules([
'id' => ['integer', ['min', 1]],
'uniqueid' => ['string'],
'src' => ['string'],
'dst' => ['string'],
'i_date' => ['date'],
'f_date' => ['date'],
'entry' => ['string']
]);
$body = json_decode($request->getBody()->getContents(), true); $body = json_decode($request->getBody()->getContents(), true);
$dados = $this->validateData($request, true); $validator = $validator->withData($body);
if (!$validator->validate()) {
$response->getBody()
->write(json_encode($validator->errors()));
return $response->withStatus(422);
}
$result = Bilhetes::getBilhetes($body);
$query = "SELECT /*$query = "SELECT
a.id_bilhetes AS id, a.calldate AS data_hora, a.id_bilhetes AS id, a.calldate AS data_hora,
a.src AS origem, a.dst AS destino, a.billsec AS tempo_conversacao, a.src AS origem, a.dst AS destino, a.billsec AS tempo_conversacao,
a.duration AS tempo_atendimento, a.accountcode AS id_transfer, a.duration AS tempo_atendimento, a.accountcode AS id_transfer,
@ -36,21 +53,22 @@ class CallController
FROM pbx_bilhetes a FROM pbx_bilhetes a
WHERE a.lastapp <> 'Transferred Call' "; WHERE a.lastapp <> 'Transferred Call' ";
$dados['org_id'] = $body['org_id'];
foreach ($dados as $k => $v) { foreach ($body as $k => $v) {
if ($v) { if ($v) {
$query .= " AND $k = :$k"; $query .= " AND $k = :$k";
} }
} }
$data = Bilhetes::query($query, $dados); $result = Bilhetes::query($query, $data); */
if (!$data) { if (!$result) {
$response->getBody()->write(json_encode(['status' => false, 'data' => ['message' => 'Nenhum resultado encontrado!']])); $response->getBody()->write(json_encode(['status' => false, 'data' => ['message' => 'Nenhum resultado encontrado!']]));
} else { } else {
$response->getBody()->write(json_encode(['status' => true, 'data' => $data])); $response->getBody()->write(json_encode(['status' => true, 'data' => $result]));
} }
} catch (Exception $e) { } catch (Exception $e) {
$response->getBody()->write(json_encode(['status' => false, 'data' => ["message" => "Nao foi possivel realizar a consulta! " . $e->getMessage()]])); $response->getBody()->write(json_encode(['status' => false, 'data' => ["message" => "Nao foi possivel realizar a consulta! " . $e->getMessage()]]));
return $response->withStatus(500);
} }
return $response; return $response;
} }

2
app/core/Connection.php

@ -7,7 +7,7 @@ use PDO;
class Connection class Connection
{ {
private static PDO $instance; private static PDO $instance;
public static function getInstance() public static function getInstance(): PDO|NULL
{ {
$cd = []; $cd = [];
if (empty(self::$instance)) { if (empty(self::$instance)) {

115
app/core/Repository.php

@ -200,119 +200,4 @@ abstract class Repository
} }
return 0; return 0;
} }
// function create(array $params)
// {
// $dados = [];
// try {
// $table = $this->table;
// $query = "INSERT INTO $table (";
// foreach ($params as $key => $value) {
// $dados[$key] = $value;
// if (array_key_last($params) == $key) {
// $query .= " $key )";
// } else {
// $query .= " $key, ";
// }
// }
// $query .= " VALUES( ";
// foreach ($params as $key => $value) {
// if (array_key_last($params) == $key) {
// $query .= " :$key );";
// } else {
// $query .= " :$key, ";
// }
// }
// return $this->db->create($query, $dados);
// } catch (Exception $e) {
// }
// }
// function list(array $params = [])
// {
// try {
// $table = $this->table;
// $query = "SELECT * FROM $table";
// $data = $this->db->read($query, $params);
// if (!$data) {
// return [];
// }
// return $data->fetchAll();
// } catch (Exception $e) {
// }
// }
// function update(array $params, $where)
// {
// try {
// $dados = array_filter($params);
// $table = $this->table;
// $query = "UPDATE $table SET ";
// foreach ($dados as $key => $value) {
// if (array_key_last($dados) == $key) {
// $query .= " $key = :$key";
// } else {
// $query .= " $key = :$key, ";
// }
// }
// $query .= " WHERE 1 = 1 ";
// if (empty($where)) {
// throw new Exception("Parâmetro (where) é obrigatório! [Table: $table] where: ['column' => 'value']");
// }
// foreach ($where as $column => $value) {
// $query .= "AND $column = :$column";
// $dados[$column] = $value;
// }
// return $this->db->update($query, $dados);
// } catch (Exception $e) {
// }
// }
// function delete(array $where): int
// {
// try {
// $table = $this->table;
// $dados = [];
// $query = "DELETE FROM $table WHERE 1 = 1";
// if (empty($where)) {
// throw new Exception("Parâmetro (where) é obrigatório! [Table: $table] where: ['column' => 'value']");
// }
// foreach ($where as $column => $value) {
// $query .= "AND $column = :$column";
// $dados[$column] = $value;
// }
// return $this->db->delete($query, $dados);
// } catch (Exception $e) {
// }
// return 0;
// }
// function get(array $params = null, $limit = 100)
// {
// try {
// $table = $this->table;
// $dados = [];
// $query = "SELECT * FROM $table WHERE 1=1 ";
// if (empty($params)) {
// $query .= " ORDER BY 1 LIMIT $limit";
// } else {
// foreach ($params as $column => $value) {
// $query .= "AND $column = :$column";
// $dados[$column] = $value;
// }
// }
// $data = $this->db->read($query, $dados);
// if (!$data) {
// return [];
// }
// return $data->fetch();
// } catch (Exception $e) {
// }
// }
} }

10
app/models/Bilhetes.php

@ -1,10 +0,0 @@
<?php
namespace app\models;
use app\core\Repository;
class Bilhetes extends Repository
{
protected static $table = 'pbx_bilhetes';
}

17
app/traits/Validate.php

@ -9,18 +9,19 @@ use Exception;
trait Validate trait Validate
{ {
public function validateData(Request $request, $data = false) public function validateData(array $body, array $filters = [], bool $date = false): array
{ {
$body = json_decode($request->getBody()->getContents(), true);
$parametro = Parametro::find(['org_id' => $body['org_id']], ['prm_max_dias_relatorio']); $parametro = Parametro::find(['org_id' => $body['org_id']], ['prm_max_dias_relatorio']);
$datas = []; $dates = [];
if (empty($filters)) {
$filters = [ $filters = [
'id', 'uniqueid', 'origem', 'destino', 'id', 'uniqueid', 'origem', 'destino',
'fila', 'org_id', 'data_inicial', 'fila', 'org_id', 'data_inicial',
'data_final', 'agente', 'apelido', 'data_final', 'agente', 'apelido',
'nome', 'ramal', 'evento' 'nome', 'ramal', 'evento'
]; ];
}
foreach ($body as $k => $v) { foreach ($body as $k => $v) {
if (!in_array($k, $filters)) { if (!in_array($k, $filters)) {
@ -28,9 +29,9 @@ trait Validate
} }
} }
if ($data) { if ($date) {
$datas['data_inicial'] = $body['data_inicial'] ?? date('Y-m-d H:i:s'); $dates['data_inicial'] = $body['data_inicial'] ?? date('Y-m-d H:i:s');
$datas['data_final'] = $body['data_final'] ?? date('Y-m-d H:i:s'); $dates['data_final'] = $body['data_final'] ?? date('Y-m-d H:i:s');
if (($body['data_inicial'] && $body['data_final']) && strtotime($body['data_inicial']) > strtotime($body['data_final'])) { if (($body['data_inicial'] && $body['data_final']) && strtotime($body['data_inicial']) > strtotime($body['data_final'])) {
throw new Exception('A [data_inicial] nao pode ser maior que [data_final]!'); throw new Exception('A [data_inicial] nao pode ser maior que [data_final]!');
@ -41,11 +42,11 @@ trait Validate
} }
if ($parametro->prm_max_dias_relatorio) { if ($parametro->prm_max_dias_relatorio) {
if (strtotime($datas['data_inicial']) > strtotime($body['data_inicial'] . "+" . $parametro->prm_max_dias_relatorio . "days")) { if (strtotime($dates['data_inicial']) > strtotime($body['data_inicial'] . "+" . $parametro->prm_max_dias_relatorio . "days")) {
throw new Exception("O periodo nao pode ultrapassar " . $parametro->prm_max_dias_relatorio . " dias!"); throw new Exception("O periodo nao pode ultrapassar " . $parametro->prm_max_dias_relatorio . " dias!");
} }
} }
} }
return $datas; return $dates;
} }
} }

3
composer.json

@ -14,7 +14,8 @@
"slim/slim": "4.*", "slim/slim": "4.*",
"slim/psr7": "^1.6", "slim/psr7": "^1.6",
"tuupola/cors-middleware": "^1.3", "tuupola/cors-middleware": "^1.3",
"firebase/php-jwt": "^6.3" "firebase/php-jwt": "^6.3",
"vlucas/valitron": "^1.4"
}, },
"config": { "config": {
"optimize-autoloader": false, "optimize-autoloader": false,

61
composer.lock generated

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "fdbb6dffe913987160bb9dd2cbde94e0", "content-hash": "1dd4e4d801720ff263feb9d481a91eee",
"packages": [ "packages": [
{ {
"name": "fig/http-message-util", "name": "fig/http-message-util",
@ -1081,6 +1081,65 @@
} }
], ],
"time": "2021-09-14T12:46:25+00:00" "time": "2021-09-14T12:46:25+00:00"
},
{
"name": "vlucas/valitron",
"version": "v1.4.11",
"source": {
"type": "git",
"url": "https://github.com/vlucas/valitron.git",
"reference": "fadce39f5f235755bb9794b2573af2d5bfcba85f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/vlucas/valitron/zipball/fadce39f5f235755bb9794b2573af2d5bfcba85f",
"reference": "fadce39f5f235755bb9794b2573af2d5bfcba85f",
"shasum": ""
},
"require": {
"php": ">=5.3.2"
},
"require-dev": {
"phpunit/phpunit": ">=4.8.35"
},
"suggest": {
"ext-mbstring": "It can support the multiple bytes string length."
},
"type": "library",
"autoload": {
"psr-4": {
"Valitron\\": "src/Valitron"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Vance Lucas",
"email": "vance@vancelucas.com",
"homepage": "https://www.vancelucas.com"
}
],
"description": "Simple, elegant, stand-alone validation library with NO dependencies",
"homepage": "https://github.com/vlucas/valitron",
"keywords": [
"valid",
"validation",
"validator"
],
"support": {
"issues": "https://github.com/vlucas/valitron/issues",
"source": "https://github.com/vlucas/valitron/tree/v1.4.11"
},
"funding": [
{
"url": "https://tidelift.com/funding/github/packagist/vlucas/valitron",
"type": "tidelift"
}
],
"time": "2022-10-14T11:54:24+00:00"
} }
], ],
"packages-dev": [], "packages-dev": [],

Loading…
Cancel
Save