Commit 95947cf1 authored by Karamel's avatar Karamel
Browse files

Superugly fiscal data access.

parent 2feb51b7
......@@ -12,22 +12,19 @@ $loginMiddleware = function($request, $response, $next) {
// Check for logged user
$userId = null;
/* if ($ptApp->isDebugMode()) {
$user = 0; // Disabled login
} else {*/
$token = Login::getToken();
if ($token != null) {
$userId = Login::getLoggedUserId($token, $ptApp->getJwtSecret(), $ptApp->getJwtTimeout());
if ($userId !== null) {
$user = $ptApp->getIdentModule()->getUser($userId);
$ptApp->login($user);
}
$token = Login::getToken();
if ($token != null) {
$userId = Login::getLoggedUserId($token, $ptApp->getJwtSecret(), $ptApp->getJwtTimeout());
if ($userId !== null) {
$user = $ptApp->getIdentModule()->getUser($userId);
$ptApp->login($user);
}
//}
}
$isLogin = 'api/login' == substr($request->getUri()->getPath(), 0, 9);
$mustLogin = ('fiscal/' !== substr($request->getUri()->getPath(), 0, 7)
&& 'api/login' !== substr($request->getUri()->getPath(), 0, 9));
if ($userId === null && !$isLogin) {
if ($userId === null && $mustLogin) {
// Reject the call because not authenticated.
$response = $response->withStatus(403, 'Not logged');
} else {
......
......@@ -42,7 +42,6 @@ $app = new \Slim\App([
]
]);
$app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware($app));
// Add login middleware
......@@ -75,6 +74,7 @@ include('../routes/tax.php');
include('../routes/ticket.php');
include('../routes/user.php');
include('../routes/version.php');
include('../routes/fiscal.php');
// Run
$app->run();
<?php
use Dflydev\FigCookies\FigResponseCookies;
use Dflydev\FigCookies\SetCookie;
use \Pasteque\Server\System\Login;
use \Pasteque\Server\System\API\APICaller;
use \Pasteque\Server\System\API\APIResult;
function fiscalLogin($app, $ptApp, $request, $response) {
$data = $request->getParsedBody();
if (!empty($data['user']) && !empty($data['password'])) {
$apiResult = APICaller::run($ptApp, 'login', 'login',
['login' => $data['user'], 'password' => $data['password']]);
if ($apiResult->getStatus() == APIResult::STATUS_CALL_OK) {
// Set the cookie
$newToken = $apiResult->getContent();
if ($newToken != null) {
$response = $response->withHeader(Login::TOKEN_HEADER, $newToken);
$cookie = SetCookie::create(Login::TOKEN_HEADER)
->withValue($newToken)
->withMaxAge($ptApp->getJwtTimeout())
->withPath($request->getUri()->getPath())
->withDomain($request->getUri()->getHost());
$response = FigResponseCookies::set($response, $cookie);
$user = $ptApp->getIdentModule()->getUser($data['user']);
$ptApp->login($user);
}
}
}
return $response;
}
function fiscalTpl($response, $template, $data = []) {
$body = $response->getBody();
$body->write(file_get_contents(__DIR__ . '/../templates/header.html'));
require_once(__DIR__ . '/../templates/' . $template);
$content = render($data);
$body->write($content);
$body->write(file_get_contents(__DIR__ . '/../templates/footer.html'));
}
$app->any('/fiscal/z/{sequence}', function ($request, $response, $args) {
$ptApp = $this->get('settings')['ptApp'];
$response = fiscalLogin($this, $ptApp, $request, $response);
if ($ptApp->getCurrentUser() == null) {
fiscalTpl($response, 'login.php');
return $response;
} else {
fiscalTpl($response, 'z.html');
return $response;
}
});
/** Z ticket listing */
$app->any('/fiscal/sequence/{sequence}/z/', function ($request, $response, $args) {
$ptApp = $this->get('settings')['ptApp'];
$response = fiscalLogin($this, $ptApp, $request, $response);
if ($ptApp->getCurrentUser() == null) {
fiscalTpl($response, 'login.php');
return $response;
} else {
// Get pagination input
$queryParams = $request->getQueryParams();
$page = (!empty($queryParams['page'])) ? $queryParams['page'] : 0;
$sequence = $args['sequence'];
$count = 10;
// Get total count of Z tickets (for pagination)
$apiCount = APICaller::run($ptApp, 'fiscal', 'countZ',
['sequence' => $sequence]);
$pageCount = 0;
if ($apiCount->getStatus() != APIResult::STATUS_CALL_OK) {
fiscalTpl($response, 'apierror.php', $apiCount);
return $response;
} else {
$zCount = $apiCount->getContent();
$pageCount = intval($apiCount->getContent() / $count);
if ($zCount % $count > 0) { $pageCount++; }
}
// Get Z tickets
$apiResult = APICaller::run($ptApp, 'fiscal', 'listZ',
['sequence' => $sequence, 'count' => $count, 'page' => $page]);
if ($apiResult->getStatus() == APIResult::STATUS_CALL_OK) {
// Convert tickets to structs and check signature
$data = $apiResult->getContent();
$structs = [];
if ($page == 0 && count($data) > 0) {
$struct = $data[0]->toStruct();
$struct['signature'] = $data[0]->checkSignature(null) ? 'ok' : 'NOK';
$structs[] = $struct;
}
for ($i = 1; $i < count($data); $i++) {
$struct = $data[$i]->toStruct();
$struct['signature'] = $data[$i]->checkSignature($data[$i - 1]) ? 'ok' : 'NOK';
$structs[] = $struct;
}
// Render
fiscalTpl($response, 'listz.php', ['sequence' => $sequence,
'page' => $page, 'pageCount' => $pageCount,
'z' => $structs]);
} else {
fiscalTpl($response, 'apierror.php', $apiResult);
}
return $response;
}
});
/** Tickets listing */
$app->any('/fiscal/sequence/{sequence}/tickets/', function ($request, $response, $args) {
$ptApp = $this->get('settings')['ptApp'];
$response = fiscalLogin($this, $ptApp, $request, $response);
if ($ptApp->getCurrentUser() == null) {
fiscalTpl($response, 'login.php');
return $response;
} else {
// Get pagination input
$queryParams = $request->getQueryParams();
$page = (!empty($queryParams['page'])) ? $queryParams['page'] : 0;
$sequence = $args['sequence'];
$count = 10;
// Get total count of tickets (for pagination)
$apiCount = APICaller::run($ptApp, 'fiscal', 'countTickets',
['sequence' => $sequence]);
$pageCount = 0;
if ($apiCount->getStatus() != APIResult::STATUS_CALL_OK) {
fiscalTpl($response, 'apierror.php', $apiCount);
return $response;
} else {
$zCount = $apiCount->getContent();
$pageCount = intval($apiCount->getContent() / $count);
if ($zCount % $count > 0) { $pageCount++; }
}
// Get tickets
$apiResult = APICaller::run($ptApp, 'fiscal', 'listTickets',
['sequence' => $sequence, 'count' => $count, 'page' => $page]);
if ($apiResult->getStatus() == APIResult::STATUS_CALL_OK) {
// Convert tickets to structs and check signature
$data = $apiResult->getContent();
$structs = [];
if ($page == 0 && count($data) > 0) {
$struct = $data[0]->toStruct();
$struct['signature'] = $data[0]->checkSignature(null) ? 'ok' : 'NOK';
$structs[] = $struct;
}
for ($i = 1; $i < count($data); $i++) {
$struct = $data[$i]->toStruct();
$struct['signature'] = $data[$i]->checkSignature($data[$i - 1]) ? 'ok' : 'NOK';
$structs[] = $struct;
}
// Render
fiscalTpl($response, 'listtkts.php', ['sequence' => $sequence,
'page' => $page, 'pageCount' => $pageCount,
'tickets' => $structs]);
} else {
fiscalTpl($response, 'apierror.php', $apiResult);
}
return $response;
}
});
/** Fiscal home page */
$app->any('/fiscal/', function ($request, $response, $args) {
$ptApp = $this->get('settings')['ptApp'];
$response = fiscalLogin($this, $ptApp, $request, $response);
if ($ptApp->getCurrentUser() == null) {
fiscalTpl($response, 'login.php');
return $response;
} else {
$apiResult = APICaller::run($ptApp, 'fiscal', 'getSequences');
if ($apiResult->getStatus() == APIResult::STATUS_CALL_OK) {
$data = $apiResult->getContent();
fiscalTpl($response, 'menu.php', $data);
} else {
fiscalTpl($response, 'apierror.php', $apiResult);
}
return $response;
}
});
<?php
function render($data) {
$ret = '<h2>Error</h2>';
$ret .= '<p>Status: ' . htmlspecialchars($data->getStatus()) . '</p>';
$ret .= '<pre>' . htmlspecialchars($data->getContent()) . '</pre>';
return $ret;
}
</body>
</html>
\ No newline at end of file
<html>
<head>
<title>Pastèque</title>
<meta charset="utf-8"/>
</head>
<body>
<?php
use \Pasteque\Server\System\DateUtils;
function renderTicket($tkt) {
$data = json_decode($tkt['content']);
$output = ($tkt['content']);
if ($data !== null) {
$output = json_encode($data, \JSON_PRETTY_PRINT);
}
$ret = '<div>';
$ret .= '<h3>Numéro : ' . $tkt['number'] . '</h3>';
$ret .= '<p>Signature : ' . $tkt['signature'] . '</p>' ;
$ret .= '<pre>' . htmlspecialchars($output) . '</pre>';
$ret .= '</div>';
return $ret;
}
function renderPagination($data) {
$ret = '<p>Page</p>';
$ret .= '<p>';
for ($i = 0; $i < $data['pageCount']; $i++) {
if ($data['page'] == $i) {
$ret .= $i . ' ';
} else {
$ret .= '<a href=".?page=' . htmlspecialchars($i) . '">' . htmlspecialchars($i) . '</a> ';
}
}
$ret .= '</p>';
return $ret;
}
function render($data) {
$ret = '<h2>Liste des tickets</h2>';
$ret .= renderPagination($data);
foreach ($data['tickets'] as $tkt) {
$ret .= renderTicket($tkt);
}
$ret .= renderPagination($data);
return $ret;
}
<?php
use \Pasteque\Server\System\DateUtils;
function renderZ($z) {
$data = json_decode($z['content']);
$output = ($z['content']);
if ($data !== null) {
$output = json_encode($data, \JSON_PRETTY_PRINT);
}
$ret = '<div>';
$ret .= '<h3>Numéro : ' . $z['number'] . '</h3>';
$ret .= '<p>Signature : ' . $z['signature'] . '</p>' ;
$ret .= '<pre>' . htmlspecialchars($output) . '</pre>';
$ret .= '</div>';
return $ret;
}
function renderPagination($data) {
$ret .= '<p>Page</p>';
$ret .= '<p>';
for ($i = 0; $i < $data['pageCount']; $i++) {
if ($data['page'] == $i) {
$ret .= $i . ' ';
} else {
$ret .= '<a href=".?page=' . htmlspecialchars($i) . '">' . htmlspecialchars($i) . '</a> ';
}
}
$ret .= '</p>';
return $ret;
}
function render($data) {
$ret = '<h2>Liste des tickets Z</h2>';
$ret .= renderPagination($data);
foreach ($data['z'] as $z) {
$ret .= renderZ($z);
}
$ret .= renderPagination($data);
return $ret;
}
<?php
function render($data) {
return <<<HTML
<div id="content" class="container-fluid">
<div id="login" style="margin: auto; width: 30ex; padding-top: 8%;">
<h1>Pastèque<br />Login</h1>
<form name="loginform" id="loginform" action="." method="post" style="background-color: #fff; box-shadow: 0 1px 3px #777; padding: 1ex;">
<p>
<label for="user_login">Identifiant<br />
<input type="text" name="user" id="user_login" class="input" value="" size="20" /></label>
</p>
<p>
<label for="user_pass">Mot de passe<br />
<input type="password" name="password" id="user_pass" class="input" value="" size="20" /></label>
</p>
<p class="submit">
<input type="submit" name="submit" id="submit" class="button" value="Se connecter" />
</p>
</form>
</div>
</div>
HTML;
}
<?php
function render($data) {
$ret = '<h1>Consultation des données fiscale</h1>';
$ret .= '<h2>Lister tous les tickets par caisse</h2>';
$ret .= '<ul>';
foreach ($data as $sequence) {
$ret .= '<li>' . htmlspecialchars($sequence) . ' : <a href="./sequence/' . htmlspecialchars($sequence) . '/z/" target="_blank">Tickets Z</a> <a href="./sequence/' . htmlspecialchars($sequence) . '/tickets/" target="_blank">Tickets</a></li>';
}
$ret .= '</ul>';
return $ret;
}
<?php
// Pastèque API
//
// Copyright (C)
// 2012 Scil (http://scil.coop)
// 2017 Karamel, Association Pastèque (karamel@creativekara.fr, https://pasteque.org)
//
// This file is part of Pastèque.
//
// Pastèque is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Pastèque is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Pastèque. If not, see <http://www.gnu.org/licenses/>.
namespace Pasteque\Server\API;
use \Pasteque\Server\Model\FiscalTicket;
class FiscalAPI implements API
{
const MODEL_NAME = 'Pasteque\Server\Model\FiscalTicket';
public function __construct($dao) {
$this->dao = $dao;
}
public static function fromApp($app) {
return new static($app->getDao());
}
public function getSequences() {
$em = $this->dao->getEntityManager();
$q = $em->createQuery('select distinct(s.sequence) '
. 'from \Pasteque\Server\Model\FiscalTicket s ');
$sequences = $q->getResult();
$result = [];
foreach ($sequences as $seq) {
$result[] = $seq[1];
}
return $result;
}
/** Count the number of z tickets, including EOS. */
public function countZ($sequence) {
$em = $this->dao->getEntityManager();
$q = $em->createQuery('select count(s.sequence) '
. 'from \Pasteque\Server\Model\FiscalTicket s '
. 'where s.type = :type') ;
$q->setParameters(['type' => FiscalTicket::TYPE_ZTICKET]);
$sequences = $q->getResult();
$result = [];
if (count($sequences) > 0) {
return $sequences[0][1];
} else {
return 0;
}
}
/** Count the number of tickets, including EOS. */
public function countTickets($sequence) {
$em = $this->dao->getEntityManager();
$q = $em->createQuery('select count(s.sequence) '
. 'from \Pasteque\Server\Model\FiscalTicket s '
. 'where s.type = :type');
$q->setParameters(['type' => FiscalTicket::TYPE_TICKET]);
$sequences = $q->getResult();
$result = [];
if (count($sequences) > 0) {
return $sequences[0][1];
} else {
return 0;
}
}
/** List Z tickets from a $sequence. If $page > 0 it will also fetch
* the previous Z to be able to check the signature. */
public function listZ($sequence, $count, $page) {
$em = $this->dao->getEntityManager();
// order by date asc then number desc because EOS has the same date
$q = $em->createQuery('select s '
. 'from \Pasteque\Server\Model\FiscalTicket s '
. 'where s.sequence = :seq and s.type = :type '
. 'order by s.date asc, s.number desc');
$q->setParameters([':seq' => $sequence,
'type' => FiscalTicket::TYPE_ZTICKET]);
$offset = 0;
$includePrevious = false;
if ($page > 0) {
$offset = $count * $page - 1;
$includePrevious = true;
}
$q->setMaxResults(($includePrevious) ? $count + 1 : $count);
$q->setFirstResult($offset);
$z = $q->getResult();
$result = [];
foreach ($z as $res) {
$result[] = $res;
}
return $result;
}
/** List tickets from a $sequence. If $page > 0 it will also fetch
* the previous ticket to be able to check the signature. */
public function listTickets($sequence, $count, $page) {
$em = $this->dao->getEntityManager();
// order by date asc then number desc because EOS has the same date
$q = $em->createQuery('select s '
. 'from \Pasteque\Server\Model\FiscalTicket s '
. 'where s.sequence = :seq and s.type = :type '
. 'order by s.date asc, s.number desc');
$q->setParameters([':seq' => $sequence,
'type' => FiscalTicket::TYPE_TICKET]);
$offset = 0;
$includePrevious = false;
if ($page > 0) {
$offset = $count * $page - 1;
$includePrevious = true;
}
$q->setMaxResults(($includePrevious) ? $count + 1 : $count);
$q->setFirstResult($offset);
$z = $q->getResult();
$result = [];
foreach ($z as $res) {
$result[] = $res;
}
return $result;
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment