merge app api

This commit is contained in:
Schneider Roland
2023-01-19 17:43:10 +01:00
570 changed files with 81491 additions and 1263 deletions

View File

@@ -18,6 +18,12 @@ use yii\i18n\Formatter;
class DateUtil
{
public static function fromUnixTimeStamp($timestamp){
$dt = DateUtil::utcDate();
$dt->setTimestamp($timestamp);
return $dt;
}
/**
* Get UTC today @00:00:00 .
* Helper method to generate date for mysql
@@ -25,13 +31,49 @@ class DateUtil
* @return DateTime
* @throws Exception
*/
public static function todayStart( ){
$d2 = new DateTime();
public static function todayStart(){
$d2 = new DateTime();
return DateUtil::utcDate($d2);
}
/**
* @param $date \DateTime optional. The date to set as utc date. If not set, new DateTime() will be used
* @return DateTime the datetime object with time reset and utc timezone
*/
public static function utcDate($date = null){
$d2 = isset($date ) ? $date : new DateTime();
$d2 = DateUtil::withTimeZoneUTC($d2);
return DateUtil::resetTime($d2);
}
/**
* @param $date \DateTime optional. If not set,defaults to : new DateTime() .
* @return DateTime
*/
public static function utcDateTime($date = null){
$d2 = isset($date ) ? $date : new DateTime();
return DateUtil::withTimeZoneUTC($d2);
}
/**
* @param $date \DateTime
* @return DateTime
*/
public static function withTimeZoneUTC( $date = null){
$d2 = isset($date ) ? $date : new DateTime();
$d2->setTimezone( new DateTimeZone('UTC') );
$d2->setTime(0, 0);
return $d2;
}
/**
* @param $dateTime \DateTime
* @return \DateTime
*/
public static function resetTime($dateTime){
$dateTime->setTime(0, 0);
return $dateTime;
}
/**
* Get UTC t @00:00:00 .
* Helper method to generate date for mysql
@@ -39,16 +81,12 @@ class DateUtil
* @return DateTime
* @throws Exception
*/
public static function tomorrowStart( ){
$d2 = new DateTime();
public static function tomorrowStart( $date = null){
$d2 = isset($date) ? $date : new DateTime();
$d2->add(new DateInterval('P1D'));
$d2->setTimezone( new DateTimeZone('UTC') );
$d2->setTime(0, 0);
return $d2;
return DateUtil::utcDate($d2);
}
public static function addMonth($timestamp, $monthCount = 1)
{
@@ -99,7 +137,7 @@ class DateUtil
* @return string
* @throws InvalidConfigException
*/
public static function formatUtc($dateTimeObject)
public static function formatDateTimeUtc($dateTimeObject)
{
$formatter = new Formatter;
$formatter->datetimeFormat = 'php:Y-m-d H:i:s';
@@ -127,6 +165,10 @@ class DateUtil
return $date;
}
public static function parseDateTime($dateTimeString){
return DateTime::createFromFormat('Y-m-d H:i:s', $dateTimeString, new DateTimeZone( 'UTC'));
}
/**
* @param integer $weekDay Numeric representation of the day of the week. @See https://www.php.net/manual/en/function.date.php
* @return string

View File

@@ -4,7 +4,7 @@ namespace common\components;
use common\models\Transfer;
use yii\base\Object;
use yii\base\BaseObject;
use common\models\MessageDetstaLab;
use common\models\MessageDetstaTetel;
use common\models\MessageDetsta;
@@ -12,13 +12,13 @@ use common\models\MessageDetstaFej;
use common\models\TicketInstallmentRequest;
/**
* Detstat üzenet mentése adatbázisba
*
*
* @property common\models\Ugiro $koteg
* @property common\models\giro\GiroDETSTA $giroDETSTA
*/
class DetStaDBSave extends Object
class DetStaDBSave extends BaseObject
{
/**
* giro köteg
* */
@@ -35,21 +35,21 @@ class DetStaDBSave extends Object
public $messageFej;
/**messagedetsta lab*/
public $messageLab;
public $path;
/**messagedetsta tetelek*/
public $messageTetelek = [];
public function run(){
$this->saveMessageDetsta();
$this->saveMessageDetstaFej( );
$this->saveMessageDetstaLab();
$this->saveMessageDetstaTetelek();
}
/**
*
* */
@@ -60,17 +60,17 @@ class DetStaDBSave extends Object
if ( isset( $this->koteg ) ){
$this->message->id_ugiro = $this->koteg->id_ugiro;
}
if ( !$this->message->save() ){
\Yii::error("Nem sikerült menteni a detsta üzenet fájlt");
throw new \Exception("Nem sikerült menteni a detsta üzenet fájtl");
}
\Yii::info("detsta üzenet mentve");
}
protected function readDate($date){
$date = trim($date);
if ( empty($date))
@@ -81,7 +81,7 @@ class DetStaDBSave extends Object
}
return $dtime->format('Y-m-d');
}
/**
*
* */
@@ -89,9 +89,9 @@ class DetStaDBSave extends Object
$this->messageFej = new MessageDetstaFej();
$fej = $this->giroDETSTA->fej;
/** @var common\components\giro\GiroDETSTAFej $fej */
$dtime = \DateTime::createFromFormat("yyyyMMdd","");
$this->messageFej->id_message = $this->message->id_message;
$this->messageFej->record_tipus = $fej->recordTipus;
$this->messageFej->uzenet_tipus = $fej->uzenetTipus;
@@ -108,7 +108,7 @@ class DetStaDBSave extends Object
}
\Yii::info("detsta fej üzenet mentve");
}
protected function saveMessageDetstaLab( ){
$this->messageLab = new MessageDetstaLab();
$lab = $this->giroDETSTA->lab;
@@ -120,25 +120,25 @@ class DetStaDBSave extends Object
$this->messageLab->visszautasitott_tetelek_osszerteke = $lab->visszautasitottTetelekSzama;
$this->messageLab->megnemvalaszolt_tetelek_szama = $lab->megNemValaszoltTetelekSzama;
$this->messageLab->megnemvalaszolt_tetelek_osszerteke = $lab->megNemValaszoltTetelekOsszerteke;
if ( !$this->messageLab->save(false)){
\Yii::error("Nem sikerült menteni a detsta üzenet lab fájlt");
throw new \Exception("Nem sikerült menteni a detsta üzenet lab fájlt");
}
\Yii::info("detsta lab üzenet mentve");
}
protected function saveMessageDetstaTetelek( ){
$tetelek = $this->giroDETSTA->tetelek;
foreach ($tetelek as $tetel){
$this->saveMessageDetstaTetel($tetel);
}
}
protected function saveMessageDetstaTetel($tetel ){
$mt = new MessageDetstaTetel();
$mt->id_message = $this->message->id_message;
$mt->record_tipus = $tetel->recordTipus ;
$mt->tetel_sorszam= $tetel->tetelSorszam ;
$mt->osszeg= $tetel->osszeg ;
@@ -149,22 +149,22 @@ class DetStaDBSave extends Object
$mt->valasz_hivatkozasi_kod= $tetel->valaszHivatkozasiKod ;
$mt->eredeti_hivatkozasi_kod= $tetel->eredetiHivatkozasiKod ;
$mt->ugyfel_azonosito= $tetel->ugyfelAzonosito ;
$request = $this->readRequest($mt->tetel_sorszam);
if ( isset($request) ){
$mt->id_ticket_installment_request = $request->id_ticket_installment_request;
}
if ( !$mt->save(false)){
\Yii::error("Nem sikerült menteni a detsta üzenet tetelt");
throw new \Exception("Nem sikerült menteni a detsta üzenet tetelt");
}
\Yii::info("detsta tetel üzenet mentve");
$this->messageTetelek[] = $mt;
}
protected function readRequest($tetel_sorszam){
$query = TicketInstallmentRequest::find();
$query->innerJoin("ugiro_request_assignment","ugiro_request_assignment.id_request = ticket_installment_request.id_ticket_installment_request");
@@ -173,6 +173,6 @@ class DetStaDBSave extends Object
$query->andWhere(['ticket_installment_request.number' => $tetel_sorszam]);
return $query->one();
}
}
}

View File

@@ -2,7 +2,7 @@
namespace common\components;
use yii\base\Object;
use yii\base\BaseObject;
use common\models\Ugiro;
use common\components\giro\GiroDETSTA;
@@ -14,7 +14,7 @@ use common\components\giro\GiroDETSTA;
* @property \common\models\UGiro $koteg
*
* */
class DetStatProcessor extends Object{
class DetStatProcessor extends BaseObject{
/**aktuális koteg, config paraméterként kapju*/
@@ -154,4 +154,4 @@ class DetStatProcessor extends Object{
}
}
}

View File

@@ -3,7 +3,7 @@
namespace common\components;
use common\models\Transfer;
use yii\base\Object;
use yii\base\BaseObject;
use common\models\TicketInstallmentRequest;
use common\components\giro\GiroDETSTATetel;
use common\models\Account;
@@ -19,7 +19,7 @@ use common\models\Contract;
*
*
*/
class DetStatTetelProcessor extends Object {
class DetStatTetelProcessor extends BaseObject {
/**
* A válasz tétel . Ha nincs megadva, automatikus visszautasítjuk a megbízást
* */
@@ -320,4 +320,4 @@ class DetStatTetelProcessor extends Object {
public function hasError() {
return false;
}
}
}

View File

@@ -4,7 +4,7 @@ namespace common\components;
use common\models\Card;
class FreeUniqueCardNumberGenerator extends \yii\base\Object {
class FreeUniqueCardNumberGenerator extends \yii\base\BaseObject {
public $count;
public $keyset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
public $length = 6;
@@ -37,4 +37,4 @@ class FreeUniqueCardNumberGenerator extends \yii\base\Object {
protected function checkCacheUnique($number) {
return array_search ( $number, $this->cache ) === false;
}
}
}

View File

@@ -147,6 +147,7 @@ class GD
public function save($file, $quality = 90)
{
try{
switch($this->_mime) {
case 'image/jpeg':
return imagejpeg($this->_image, $file, $quality);
@@ -159,6 +160,9 @@ class GD
return imagegif($this->_image, $file);
break;
}
}catch (\Exception $e){
\Yii::error("Failed to save image image:", $e->getMessage());
}
return false;
}
}

View File

@@ -538,4 +538,9 @@ class Helper {
return $result;
}
public static function isRestAllowVerifyOnly() {
return \Yii::$app->params ['rest_allow_verify_only'] == true;
}
}

View File

@@ -1,4 +1,5 @@
<?php
namespace common\components;
use Yii;
@@ -9,14 +10,15 @@ use common\components\GD;
class Image
{
/**
* @param UploadedFile $fileInstance
* @param string $dir relative dir from upload dir
* @param unknown $resizeWidth
* @param unknown $resizeHeight
* @param bool $resizeCrop
* @throws HttpException*/
/**
* @param UploadedFile $fileInstance
* @param string $dir relative dir from upload dir
* @param unknown $resizeWidth
* @param unknown $resizeHeight
* @param bool $resizeCrop
* @throws HttpException
*/
public static function upload(UploadedFile $fileInstance, $dir = '', $resizeWidth = null, $resizeHeight = null, $resizeCrop = false)
{
$fileName = Upload::getUploadPath($dir) . DIRECTORY_SEPARATOR . Upload::getFileName($fileInstance);
@@ -25,29 +27,29 @@ class Image
? self::copyResizedImage($fileInstance->tempName, $fileName, $resizeWidth, $resizeHeight, $resizeCrop)
: $fileInstance->saveAs($fileName);
if(!$uploaded){
throw new HttpException(500, 'Cannot upload file "'.$fileName.'". Please check write permissions.');
if (!$uploaded) {
throw new HttpException(500, 'Cannot upload file "' . $fileName . '". Please check write permissions.');
}
return Upload::getLink($fileName);
}
public static function saveBinary($binary_data, $dir = '')
{
$fileName = Upload::getUploadPath($dir) . DIRECTORY_SEPARATOR . Upload::genFileName("jpg");
$uploaded = file_put_contents( $fileName, $binary_data );
$uploaded = file_put_contents($fileName, $binary_data);
if(!$uploaded){
throw new HttpException(500, 'Cannot upload file "'.$fileName.'". Please check write permissions.');
if (!$uploaded) {
throw new HttpException(500, 'Cannot upload file "' . $fileName . '". Please check write permissions.');
}
return Upload::getLink($fileName);
}
/**
*
*
* @param unknown $filename
* @param unknown $width
* @param unknown $height
@@ -56,16 +58,14 @@ class Image
*/
static function thumb($filename, $width = null, $height = null, $crop = true)
{
if($filename && file_exists(($filename = Yii::getAlias('@frontend/web') . $filename)))
{
if ($filename && file_exists(($filename = Yii::getAlias('@frontend/web') . $filename))) {
$info = pathinfo($filename);
$thumbName = $info['filename'] . '-' . md5( filemtime($filename) . (int)$width . (int)$height . (int)$crop ) . '.' . $info['extension'];
$thumbName = $info['filename'] . '-' . md5(filemtime($filename) . (int)$width . (int)$height . (int)$crop) . '.' . $info['extension'];
$thumbFile = Yii::getAlias('@frontend/web') . DIRECTORY_SEPARATOR . Upload::$UPLOADS_DIR . DIRECTORY_SEPARATOR . 'thumbs' . DIRECTORY_SEPARATOR . $thumbName;
$thumbWebFile = '/' . Upload::$UPLOADS_DIR . '/thumbs/' . $thumbName;
if(file_exists($thumbFile)){
if (file_exists($thumbFile)) {
return $thumbWebFile;
}
elseif(FileHelper::createDirectory(dirname($thumbFile), 0777) && self::copyResizedImage($filename, $thumbFile, $width, $height, $crop)){
} elseif (FileHelper::createDirectory(dirname($thumbFile), 0777) && self::copyResizedImage($filename, $thumbFile, $width, $height, $crop)) {
return $thumbWebFile;
}
}
@@ -74,39 +74,38 @@ class Image
static function copyResizedImage($inputFile, $outputFile, $width, $height = null, $crop = true)
{
if (extension_loaded('gd'))
{
$image = new GD($inputFile);
if (extension_loaded('gd')) {
try {
$image = new GD($inputFile);
if($height) {
if($width && $crop){
$image->cropThumbnail($width, $height);
if ($height) {
if ($width && $crop) {
$image->cropThumbnail($width, $height);
} else {
$image->resize($width, $height);
}
} else {
$image->resize($width, $height);
$image->resize($width);
}
} else {
$image->resize($width);
return $image->save($outputFile);
} catch (\Exception $e) {
\Yii::error("Failed to create thumbnail: ". $e->getMessage());
}
return $image->save($outputFile);
}
elseif(extension_loaded('imagick'))
{
} elseif (extension_loaded('imagick')) {
$image = new \Imagick($inputFile);
if($height && !$crop) {
if ($height && !$crop) {
$image->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1, true);
}
else{
} else {
$image->resizeImage($width, null, \Imagick::FILTER_LANCZOS, 1);
}
if($height && $crop){
if ($height && $crop) {
$image->cropThumbnailImage($width, $height);
}
return $image->writeImage($outputFile);
}
else {
} else {
throw new HttpException(500, 'Please install GD or Imagick extension');
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace common\components;
use Mpdf\Mpdf;
use yii\base\BaseObject;
class MpdfUtil extends BaseObject
{
// mpdf version 6 constructor
//function mPDF($mode='',$format='A4',$default_font_size=0,$default_font='',$mgl=15,$mgr=15,$mgt=16,$mgb=16,$mgh=9,$mgf=9, $orientation='P') {
public static function createMpdfWith6XConstructor($mode = '', $format = 'A4', $default_font_size = 0, $default_font = '', $mgl = 15, $mgr = 15, $mgt = 16, $mgb = 16, $mgh = 9, $mgf = 9, $orientation = 'P')
{
return self::createMpdf([
'mode' => $mode,
'format' => $format,
'default_font_size' => $default_font_size,
'default_font' => $default_font,
'margin_left' => $mgl,
'margin_right' => $mgr,
'margin_top' => $mgt,
'margin_bottom' => $mgb,
'margin_header' => $mgh,
'margin_footer' => $mgf,
'orientation' => $orientation
]);
}
public static function createMpdf($options = [])
{
$mpdf = new Mpdf(
array_merge([
'mode' => 'utf-8',
'format' => 'A4'
], $options)
);
return $mpdf;
}
}

View File

@@ -2,7 +2,7 @@
namespace common\components;
use yii\base\Object;
use yii\base\BaseObject;
use yii\db\Query;
use common\models\Product;
use yii\data\ActiveDataProvider;
@@ -14,7 +14,7 @@ use common\models\Transfer;
* @property common\models\Account $account a kassza
* @property common\models\Product[] $products a termékek
* */
class ProductInventory extends Object{
class ProductInventory extends BaseObject{
@@ -110,4 +110,4 @@ class ProductInventory extends Object{
}
?>
?>

View File

@@ -0,0 +1,72 @@
<?php
namespace common\components;
class StopWatch
{
public $start;
public $splits = [];
public $stop;
// public function _(){
// $this->start();
// }
public function __construct()
{
$this->start();
}
public function start()
{
$this->start = $this->time();
}
public function split()
{
$this->splits[] = $this->time();
return $this->getSplit();
}
public function stop()
{
$this->stop = $this->time();
}
function time()
{
return time();
}
function diff($start, $end)
{
if (!isset($start) || !isset($end)) {
return -1;
}
return $end - $start;
}
function getSplit()
{
$lastSplit = null;
if (isset($this->stop)) {
$lastSplit = $this->stop;
} else {
$count = count($this->splits);
if ($count > 0) {
$lastSplit = $this->splits[$count - 1];
}
}
return $this->diff($this->start, $lastSplit);
}
function getTotal(){
return $this->diff($this->start, $this->stop);
}
}

File diff suppressed because one or more lines are too long

View File

@@ -11,7 +11,7 @@ use common\models\Ticket;
class TransferPayout extends \yii\base\Object{
class TransferPayout extends \yii\base\BaseObject{
/**Current user*/
public $idUser = null;
@@ -136,4 +136,4 @@ class TransferPayout extends \yii\base\Object{
}
}
}

View File

@@ -2,34 +2,35 @@
namespace common\components\accountstate;
use yii\base\Object;
use common\models\User;
use common\models\Account;
use common\models\AccountState;
use common\components\DailyListing;
use common\components\MpdfUtil;
use yii\base\BaseObject;
/**
* @property common\models\AccountState $model
* */
class AccountStateMail extends Object {
class AccountStateMail extends BaseObject {
public $controller;
public $model;
public $user;
public $account;
public $message;
public $details;
public function init(){
$this->user = User::findOne($this->model->id_user);
$this->account = Account::findOne($this->model->id_account);
$this->details = null;
if ($this->model ->isTypeClose ()) {
$prev;
if ($this->model->type == AccountState::TYPE_CLOSE) {
if (isset ( $this->model->prev_state )) {
@@ -41,28 +42,28 @@ class AccountStateMail extends Object {
}
$this->details = new DailyListing();
$this->details->loadAccountState ( $this->model );
$this->details->readModeAccountState();
// $this->details->readTotalEasy ();
// $this->details->readTotalDetailed ();
// $this->details->readTotalMedium ();
}
}
public function sednMail(){
$subject = $this->model->isTypeOpen() ? "Kassza nyitás " : "Kassza zárás";
$subject .= " - " . $this->user->username ." - ". $this->account->name;
$this->message = \Yii::$app->mailer->compose('account_state', [
'model' => $this->model,
'details' => $this->details
]);
$this->attachPdf();
try{
$this->message->setFrom(\Yii::$app->params['infoEmail'])
->setTo( \Yii::$app->params['notify_mail'] )
@@ -71,21 +72,21 @@ class AccountStateMail extends Object {
}catch (\Exception $e){
\Yii::error("Nem sikerült elküldeni a kassza müvelet emailt");
}
}
protected function attachPdf(){
$mpdf=new \mPDF('utf-8', 'A4-L');
$mpdf= MpdfUtil::createMpdfWith6XConstructor('utf-8', 'A4-L');
$mpdf->useSubstitutions=false;
$mpdf->simpleTables = true;
$mpdf->SetHeader( \Yii::$app->params[ "company_name" ] . " - Létrehozva: " .$user->username . ", ".\Yii::$app->formatter->asDatetime(time()) );
$mpdf->setFooter('{PAGENO} / {nb}');
$stylesheet = file_get_contents( \Yii::getAlias('@vendor'.'/bower/bootstrap/dist/css/bootstrap.css')); // external css
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($this->controller->renderPartial("@common/views/account-state/account_state_pdf", [
'model' => $this->model,
'details' => $this->details
@@ -94,11 +95,11 @@ class AccountStateMail extends Object {
$dt= "_letrehozva_".date("Ymd_His"). "_" . $this->user->username;
$fn= $type .$dt.".pdf";
$content = $mpdf->Output($fn, 'S');
$this->message->attachContent($content, ['fileName' => $fn, 'contentType' => 'application/pdf']);
}
}
}

View File

@@ -5,3 +5,4 @@ Yii::setAlias('backend', dirname(dirname(__DIR__)) . '/backend');
Yii::setAlias('console', dirname(dirname(__DIR__)) . '/console');
Yii::setAlias('rest', dirname(dirname(__DIR__)) . '/rest');
Yii::setAlias('customerapi', dirname(dirname(__DIR__)) . '/customerapi');
Yii::setAlias('mobileapi', dirname(dirname(__DIR__)) . '/mobileapi');

View File

@@ -0,0 +1,582 @@
<?php
namespace common\manager;
use common\components\DateUtil;
use common\components\Helper;
use common\components\StopWatch;
use common\models\Card;
use common\models\CardKeyAssignment;
use common\models\DoorLog;
use common\models\DoorLogForTest;
use common\models\Key;
use common\models\Log;
use common\models\Ticket;
use common\models\VirtualKey;
use frontend\models\KeyToggleForm;
use yii\base\BaseObject;
use yii\base\InvalidConfigException;
use yii\db\Exception;
use yii\web\BadRequestHttpException;
use yii\web\ServerErrorHttpException;
/**
* Created by IntelliJ IDEA.
* User: rocho
* Date: 2018.12.17.
* Time: 6:12
*/
class DoorManager extends BaseObject
{
/**
* @param $identifier 00000000: nyomogombos nyitás
* @param $device string B(gomb)|Q(qrcode)|C(nfc),E(emergency)
* @param $direction string IN|OUT
* @param $verifyOnly boolean true: akkor csak lekerdezés, false: megtörtént a mozgás (ilyenkor vonunk le egy alkalmat)
* @param $createdAt number unix timestamp , override createdAt for doorLogs
* @param $date number unix timestamp, override date for validation check 'now'
* @return void
* @throws BadRequestHttpException
* @throws ServerErrorHttpException
* @throws \yii\base\InvalidConfigException
* @throws \yii\db\Exception
*/
public function move($identifier, $device, $direction, $verifyOnly, $createdAt = null, $date = null)
{
$requestId = uniqid("",false);
$stopWatch = new StopWatch();
// for testing purposes
if ( Helper::isRestAllowVerifyOnly() === false ){
\Yii::info("$requestId: verifyonly not allowed");
$verifyOnly = false;
}
\Yii::info("$requestId: move with next parameers:" . ";identifier" . $identifier . ";device" . $device . ";direction" . $direction . ";verifyOnly" . $verifyOnly . ";createdAt" . print_r($createdAt,true) . ";date" . print_r($date,true));
\Yii::info("$requestId: move get request: " . print_r($_GET, true));
\Yii::info("$requestId: move post request: " . print_r($_GET, true));
if (isset($createdAt)) {
$createdAt = DateUtil::parseDateTime($createdAt);
} else {
$createdAt = DateUtil::utcDateTime();
}
if (isset($date)) {
$date = DateUtil::parseDateTime($date);
} else {
$date = DateUtil::utcDate();
}
if ($device === 'E') {
$this->moveEmergency($requestId,$identifier, $device, $direction, $verifyOnly, $createdAt, $date);
return;
}
$cardNumber = $identifier;
$virtualKey = null;
switch ($direction) {
case 'IN':
$direction = DoorLog::$DIRECTION_IN;
break;
case 'OUT':
$direction = DoorLog::$DIRECTION_OUT;
break;
default:
throw new BadRequestHttpException("$requestId: Direction not supported: " . $direction);
}
// if device is qr code
if ($device == 'Q') {
// allow only virtual key
$virtualKey = VirtualKey::findOne(['number' => $identifier]);
if (!isset($virtualKey)) {
throw new BadRequestHttpException("$requestId: Virtual key not found: " . $identifier);
}
$card = Card::findOne($virtualKey->id_card);
if ($card != null) {
$card = Card::readCard($card->number);
}
if ($card == null) {
throw new BadRequestHttpException("$requestId: Card not found by virtual key: " . $identifier . '/' . $virtualKey->id_card);
}
$cardNumber = $card->number;
\Yii::info("$requestId: virtual key and card loaded in sec " . $stopWatch->split());
} else {
// load by rfid or card number
$card = Card::readCard(Helper::fixAsciiChars($identifier));
\Yii::info("$requestId: Card loaded in sec " . $stopWatch->split());
if (!isset($card)) {
throw new BadRequestHttpException("$requestId: Card not found with number: " . $identifier);
}
\Yii::info("$requestId: card loaded in sec " . $stopWatch->split());
$virtualKey = VirtualKey::findOne(['id_card' => $card->id_card]);
\Yii::info("$requestId: virtual key for card loaded in sec " . $stopWatch->split());
}
\Yii::info("$requestId: Card number " . $card->number);
if ($card->type == Card::TYPE_EMPLOYEE) {
$this->moveEmployee($identifier, $device, $direction, $verifyOnly, $createdAt, $date, $card, $cardNumber, $virtualKey);
return;
}
$this->moveCustomer($requestId, $identifier, $device, $direction, $verifyOnly, $createdAt, $date, $card, $cardNumber, $virtualKey);
}
function moveEmergency($requestId,$identifier, $device, $direction, $verifyOnly, $createdAt, $date)
{
\Yii::info("$requestId: emergency move");
try {
$createdAtStr = DateUtil::formatDateTimeUtc($createdAt);
\Yii::$app->db->beginTransaction();
$doorLog = new DoorLog();
$doorLog->version = 2;
$doorLog->direction = DoorLog::$DIRECTION_ALL_EMERGENCY;
$doorLog->source_app = $device;
$doorLog->created_at = $createdAtStr;
$doorLog->save(false);
Log::log(
[
'type' => Log::$TYPE_INFO,
'message' => 'Ajtó nyitás: vészhelyzet',
'id_door_log' => $doorLog->id_door_log
]
);
\Yii::$app->db->transaction->commit();
} catch (\Exception $e) {
\Yii::$app->db->transaction->rollBack();
throw $e;
}
}
function moveEmployee($identifier, $device, $direction, $verifyOnly, $createdAt, $date, $card, $cardNumber, $virtualKey)
{
/**
* if the card type is employee, neither customer nor ticket is needed.
* Free to enter/leave
*/
\Yii::info("employee move");
try {
$createdAtStr = DateUtil::formatDateTimeUtc($createdAt);
\Yii::$app->db->beginTransaction();
$doorLog = new DoorLog();
$doorLog->version = 2;
$doorLog->direction = $direction;
$doorLog->source_app = $device;
$doorLog->created_at = $createdAtStr;
$doorLog->id_card = $card->id_card;
$doorLog->card_flag = $card->flag;
if (!$verifyOnly) {
$doorLog->save(false);
Log::log(
[
'type' => Log::$TYPE_INFO,
'message' => 'Ajtó nyitás: munkatárs',
'id_door_log' => $doorLog->id_door_log
]
);
}
\Yii::$app->db->transaction->commit();
} catch (\Exception $e) {
\Yii::$app->db->transaction->rollBack();
throw $e;
}
}
/**
* @param $requestId
* @param $identifier string virtual key id, card rfid or card number
* @param $device string device
* @param $direction number direction
* @param $verifyOnly boolean only check or real move
* @param $createdAt
* @param $date
* @param $card
* @param $cardNumber
* @param $virtualKey
* @return void
* @throws BadRequestHttpException
* @throws ServerErrorHttpException
* @throws InvalidConfigException
* @throws Exception
*/
function moveCustomer($requestId, $identifier, $device, $direction, $verifyOnly, $createdAt, $date, $card, $cardNumber, $virtualKey)
{
\Yii::info("$requestId: move customer");
$stopWatch = new StopWatch();
try {
$createdAtStr = DateUtil::formatDateTimeUtc($createdAt);
\Yii::info("$requestId: crated at str: ". $createdAtStr);
\Yii::$app->db->beginTransaction();
$doorLog = new DoorLog();
$doorLog->version = 2;
$doorLog->direction = $direction;
$doorLog->source_app = $device;
$doorLog->created_at = $createdAtStr;
$doorLog->id_card = $card->id_card;
$doorLog->card_flag = $card->flag;
$activeTickets = Ticket::readActive($card, clone $date);
\Yii::info("$requestId: active ticket count:" . count($activeTickets));
/** @var Ticket $ticket */
$ticket = null;
if (isset($activeTickets) && count($activeTickets) > 0) {
$ticket = $activeTickets[0];
}
if (!isset($ticket)) {
throw new BadRequestHttpException("$requestId: No active ticket found for:" . $card->number);
}
\Yii::info("$requestId: ticket {$ticket->id_ticket} loaded in sec " . $stopWatch->split());
$doorLog->id_ticket_current = $ticket->id_ticket;
// customer is also required
$customer = $card->customer;
if (!isset($customer)) {
throw new BadRequestHttpException("$requestId: Customer not found for:" . $card->number);
}
$doorLog->id_customer = $customer->id_customer;
\Yii::info("$requestId: customer {$customer->id_customer} loaded in sec " . $stopWatch->split());
if (!$verifyOnly) {
// save the door log
$doorLog->save(false);
}
\Yii::info("$requestId: door log {$doorLog->id_door_log} saved in sec " . $stopWatch->split());
// if direction is in
if ($direction == DoorLog::$DIRECTION_IN) {
if ($card->isFlagDoor()) {
throw new BadRequestHttpException("$requestId: Card already 'IN': " . $card->id_card);
}
if ($card->isFlagKey()) {
throw new BadRequestHttpException("$requestId: Key required: " . $card->id_card);
}
if ($card->isFlagStatus()) {
throw new BadRequestHttpException("$requestId: Card has no active status: " . $card->id_card);
}
if (isset($virtualKey)) {
if (isset($virtualKey->direction_in_at)) {
throw new BadRequestHttpException("$requestId: Virtual key - already moved in: " . $identifier . '/' . $virtualKey->id_card);
}
$virtualKey->direction_in_at = Helper::getDateTimeString();
\Yii::info("$requestId: Setting virtual key direction_in_at");
if (!$verifyOnly) {
\Yii::info("$requestId: Updating virtual key");
$virtualKey->save(false);
}
}
// detect if need to increase usage count for ticket
if (!$verifyOnly) {
// if not verifyonly, check, if ticket usage count must be increased
$countDoorLogsForTicketSince = $this->getCountDoorLogsForTicketSince($ticket->id_ticket, DateUtil::utcDate(clone $date));
\Yii::info("$requestId: getCountDoorLogsForTicketSince: " . $countDoorLogsForTicketSince);
if (!isset($countDoorLogsForTicketSince)) {
$countDoorLogsForTicketSince = 0;
}
\Yii::info("$requestId: count of door logs '{$countDoorLogsForTicketSince}' loaded in sec " . $stopWatch->split());
// if the current event is the first door log today
if ($countDoorLogsForTicketSince == 1) {
// increase the ticket usage count with 1
$usageCount = $ticket->usage_count;
$ticket->usage_count += 1;
$ticket->save(false);
\Yii::info("$requestId: First ticket usage today, increasing usage count for card: " . $card->id_card);
Log::log(
[
'type' => Log::$TYPE_TICKET_USAGE_FIRST,
'message' => 'Bérlet használat(előtte: ' . $usageCount . ' -> utána: ' . $ticket->usage_count,
'id_ticket' => $ticket->id_ticket,
'id_door_log' => $doorLog->id_door_log
]
);
\Yii::info("$requestId: Ticket usage count increased after first doorlog of day in sec " . $stopWatch->split());
} else {
\Yii::info("$requestId: more then one door log today for card: " . $card->id_card);
// we have already a door log for today, other than this
// Now we split the day into 3hour intervalls, starting with the createdAt value of the first event.
// If the actual event happens in an interval, in which still now doorlog event happend, we increase
// the usage count with 1
// 3 óránként 1-et levonunk
$startOfDay = DateUtil::utcDate(clone $date);
$startOfTomorrow = DateUtil::tomorrowStart(clone $date);
$allDoorLogToday = DoorLog::find()
->andWhere(['>=', 'door_log.created_at', DateUtil::formatDateUtc($startOfDay)])
->andWhere(['<', 'door_log.created_at', DateUtil::formatDateUtc($startOfTomorrow)])
->andWhere(['id_ticket_current' => $ticket->id_ticket])
->andWhere(['in', 'direction', [DoorLog::$DIRECTION_IN_WITHOUT_MOVE, DoorLog::$DIRECTION_IN]])
->orderBy(['door_log.created_at' => SORT_ASC])
->all();
\Yii::info("$requestId: All door logs for today loaded in sec " . $stopWatch->split());
\Yii::info("$requestId: allDoorLogToday", print_r($allDoorLogToday, true));
if (isset($allDoorLogToday) && count($allDoorLogToday) > 0) {
$firstInToday = $allDoorLogToday[0];
}
if (isset($firstInToday)) {
\Yii::info("$requestId: first in today for card: " . $card->id_card . " was at " . $firstInToday->created_at);
$firstEntryDateTimeToday = DateUtil::parseDateTime($firstInToday->created_at);
$interval = \DateInterval::createFromDateString('3 hours');
$daterange = new \DatePeriod($firstEntryDateTimeToday, $interval, $startOfTomorrow);
$intervals = [];
$intervalStart = null;
foreach ($daterange as $intervalEnd) {
if (isset($intervalStart)) {
$intervals[] = $this->createTicketUsageInterval($intervalStart, $intervalEnd, $allDoorLogToday, $doorLog);
}
$intervalStart = clone $intervalEnd;
}
if ($intervalStart < $startOfTomorrow) {
$intervals[] = $this->createTicketUsageInterval($intervalStart, $startOfTomorrow, $allDoorLogToday, $doorLog);
}
$activeInterval = $this->getActiveInterval($intervals, $createdAt);
if (!isset($activeInterval)) {
throw new ServerErrorHttpException("$requestId: Active Interval not found");
}
$logCountInActiveInterval = count($activeInterval['logs']);
if ($logCountInActiveInterval == 1) {
$ticket->usage_count = $ticket->usage_count + 1;
$ticket->save(false);
\Yii::info("$requestId: Ticket usage count increased after first IN after first door_log in interval in sec " . $stopWatch->split());
}
}
}
}
}
if ($direction == DoorLog::$DIRECTION_OUT || $direction == DoorLog::$DIRECTION_OUT_WITHOUT_MOVE) {
if ($card->isFlagOutKey()) {
throw new BadRequestHttpException("$requestId: Can't exit with card has a key assigned");
}
if ($card->isFlagStatus()) {
throw new BadRequestHttpException("$requestId: Can't exit with card has inactive status");
}
$keyAssigned = CardKeyAssignment::findOne(['id_card' => $card->id_card]);
if (isset($keyAssigned)) {
throw new BadRequestHttpException("$requestId: Can't exit with card has a key assigned");
}
if (isset($virtualKey)) {
if (!isset($virtualKey->direction_in_at)) {
throw new BadRequestHttpException("$requestId: Virtual key: move out without move in");
}
if (isset($virtualKey->direction_out_at)) {
throw new BadRequestHttpException("$requestId: Virtual key: already move out");
}
$virtualKey->direction_out_at = Helper::getDateTimeString();
if (!$verifyOnly) {
$virtualKey->save(false);
}
}
$ticket->count_move_out = $ticket->usage_count;
if (!$verifyOnly) {
$ticket->save(false);
}
\Yii::info("$requestId: direction_out: ticket count_move_out set after direction_out in sec " . $stopWatch->split());
}
if (!$verifyOnly) {
Card::updateCardFlagTicket($ticket->id_ticket);
\Yii::info("$requestId: updateCardFlagTicket: card flag updated in sec " . $stopWatch->split());
// reload card after flag is set
$card = Card::readCard($cardNumber);
if ($direction == DoorLog::$DIRECTION_OUT_WITHOUT_MOVE || $direction == DoorLog::$DIRECTION_OUT) {
$card->flag_out = Helper::setBit($card->flag_out, Card::$FLAG_DOOR, true);
$card->flag = Helper::setBit($card->flag, Card::$FLAG_DOOR, false);
$card->save(false);
\Yii::info("$requestId: direction_out: Door flag updated in sec " . $stopWatch->split());
} else if ($direction == DoorLog::$DIRECTION_IN || $direction == DoorLog::$DIRECTION_IN_WITHOUT_MOVE) {
$card->flag_out = Helper::setBit($card->flag_out, Card::$FLAG_DOOR, false);
$card->flag = Helper::setBit($card->flag, Card::$FLAG_DOOR, true);
$card->save(false);
\Yii::info("$requestId: direction_in: Card flag updated in sec " . $stopWatch->split());
}
}
$stopWatch->stop();
\Yii::info("$requestId: finished in sec " . $stopWatch->getTotal());
\Yii::$app->db->transaction->commit();
\Yii::info("$requestId: Commited");
} catch (\Exception $e) {
\Yii::$app->db->transaction->rollBack();
\Yii::info("$requestId: rollbacked");
throw $e;
}
}
function getActiveInterval($intervals, $date)
{
foreach ($intervals as $interval) {
$start = $interval['start'];
$end = $interval['end'];
if ($start <= $date && $date < $end) {
return $interval;
}
}
return null;
}
function createTicketUsageInterval($start, $end, $allLogs, $actualDoorLog)
{
$result = ['start' => $start, 'end' => $end, 'logs' => []];
foreach ($allLogs as $log) {
$createdAt = DateUtil::parseDateTime($log->created_at);
if ($createdAt >= $start && $createdAt < $end) {
$result['logs'][] = $log;
}
}
return $result;
}
function getCountDoorLogsForTicketSince($idTicket, $since)
{
\Yii::info("getting door log count for today");
return DoorLog::find()
->innerJoinWith('card')
->andWhere(['card.id_ticket_current' => $idTicket])
->andWhere(['in', 'door_log.direction', [DoorLog::$DIRECTION_IN, DoorLog::$DIRECTION_IN_WITHOUT_MOVE]])
->andWhere(['>=', 'door_log.created_at', DateUtil::formatDateUtc($since)])
->count();
}
public function readActive($cardNumber)
{
$card = Card::readCard($cardNumber);
return Ticket::readActive($card);
}
public function resetLogs($cardNumber)
{
$card = Card::readCard($cardNumber);
$card->flag = 0;
$card->flag_out = 0;
$card->save(false);
Card::updateCardFlagTicket($card->id_card);
DoorLog::deleteAll(
['id_card' => $card->id_card]
);
// todo: revoke all assigned key
$this->revokeKey($cardNumber, "f100");
}
public function getLogs($cardNumber)
{
return DoorLog::findAll(
['id_card' => $cardNumber]
);
}
public function getInfo($cardNumber)
{
$card = Card::readCard($cardNumber);
return [
'card' => $card,
'customer' => $card->customer,
'tickets' => Ticket::readActive($card),
'doorLogs' => DoorLog::findAll(
['id_card' => $card->id_card]
),
'lastDoorLog' => DoorLog::find()->orderBy(['id_door_log' => SORT_DESC])->limit(1)->one(),
'doorLogCount' => DoorLog::find()->count()
];
}
public function createLog()
{
\Yii::info("Post create log:" . \Yii::$app->request->method);
if (\Yii::$app->request->isPost) {
$log = new DoorLogForTest();
if ($log->load(\Yii::$app->request->post(), "")) {
if ($log->validate()) {
\Yii::info("Door log saving:" . $log->created_at);
$log->save(false);
return $log;
} else {
throw new BadRequestHttpException(print_r($log->getErrors(), true));
}
} else {
\Yii::info("validated" . print_r($log->errors, true));
throw new BadRequestHttpException();
}
}
throw new BadRequestHttpException('Not a Post');
}
function checkoutKey($cardNumber, $keyNumber)
{
$model = new KeyToggleForm();
$model->card = Card::readCard($cardNumber);
$model->customer = $model->card->customer;
$model->keyCard = $model->card;
$model->keyModel = $model->readKey($keyNumber);
$model->assign();
}
function revokeKey($cardNumber, $keyNumber)
{
$model = new KeyToggleForm();
$model->card = Card::readCard($cardNumber);
$model->customer = $model->card->customer;
$model->keyCard = $model->card;
$model->keyModel = $model->readKey($keyNumber);
$model->revoke();
}
}

View File

@@ -0,0 +1,122 @@
<?php
namespace common\manager;
use common\models\Card;
use common\models\CardEventRegistrationForm;
use common\models\Customer;
use common\models\Event;
use common\models\EventRegistration;
use common\models\MobileDevice;
use common\models\Ticket;
use customerapi\models\available\EventInterval;
use customerapi\models\registrations\EventRegistrationAvailable;
use customerapi\models\details\EventRegistrationView;
use Exception;
use Yii;
use yii\base\BaseObject;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
/**
* Created by IntelliJ IDEA.
* User: rocho
* Date: 2018.12.17.
* Time: 6:12
*/
class MobileDeviceManager extends BaseObject
{
public function login($cardNumber, $deviceIdentifier)
{
$card = Card::find()->andWhere(
['number' => $cardNumber]
)->one();
if ( $card == null ){
throw new NotFoundHttpException();
}
$device = MobileDevice::find()
->andWhere(
[
'id_card' => $card->id_card,
'device_identifier' => $deviceIdentifier
]
)->one();
if ( $device === null ){
throw new NotFoundHttpException();
}
// if (
// in_array($device->status, [MobileDevice::STATUS_ACTIVE, MobileDevice::STATUS_INACTIVE], true) === false ){
// throw new NotFoundHttpException();
// }
return $device;
}
public function create($cardNumber, $deviceIdentifier, $deviceName)
{
$card = Card::find()->andWhere(
['number' => $cardNumber]
)->one();
if ( $card == null ){
throw new NotFoundHttpException();
}
// do not allow registering cards without customer
$customer = Customer::find()->andWhere(['id_customer_card' => $card->id_card])->one();
if ( $customer == null ){
throw new NotFoundHttpException();
}
$device = MobileDevice::find()
->andWhere(
[
'id_card' => $card->id_card,
'device_identifier' => $deviceIdentifier
]
)->one();
if ( $device ){
throw new BadRequestHttpException("Device already exists, can't create");
}
$device = new MobileDevice();
$device->device_identifier = $deviceIdentifier;
$device->id_card = $card->id_card;
$device->status = MobileDevice::STATUS_INACTIVE;
$device->device_name = $deviceName;
$device->save(false);
return $device;
}
/**
* @param $cardNumber
* @param $deviceIdentifier
* @return array|MobileDevice|ActiveRecord
* @throws BadRequestHttpException
* @throws NotFoundHttpException
*/
public function loginOrCreate($cardNumber, $deviceIdentifier, $deviceName)
{
try {
return $this->login($cardNumber, $deviceIdentifier);
} catch (\Exception $e) {
return $this->create($cardNumber, $deviceIdentifier, $deviceName);
}
}
}

View File

@@ -34,6 +34,7 @@ class Card extends \common\models\BaseFitnessActiveRecord
const TYPE_BARCODE = 30;
const TYPE_OLD = 40;
const TYPE_EMPLOYEE = 50;
const TYPE_REVIEW = 60;
public static $FLAG_TICKET = 0; //has valid ticket
@@ -164,6 +165,7 @@ class Card extends \common\models\BaseFitnessActiveRecord
self::TYPE_BARCODE => Yii::t('common/card', 'BARCODE'),
self::TYPE_OLD => Yii::t('common/card', 'OLD'),
self::TYPE_EMPLOYEE => Yii::t('common/card', 'Munkatárs'),
self::TYPE_REVIEW => Yii::t('common/card', 'Review'),
];
}

View File

@@ -12,6 +12,7 @@ use yii\behaviors\TimestampBehavior;
* @property integer $id_card
* @property integer $id_key
* @property integer $id_user
* @property string $virtual_key
* @property string $created_at
* @property string $updated_at
*/

View File

@@ -6,6 +6,7 @@ use Yii;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\base\NotSupportedException;
use yii\filters\RateLimitInterface;
use yii\web\IdentityInterface;
/**
@@ -42,7 +43,7 @@ use yii\web\IdentityInterface;
* @property string password_hash
* @property string auth_key
*/
class Customer extends BaseFitnessActiveRecord implements IdentityInterface
class Customer extends BaseFitnessActiveRecord implements IdentityInterface, RateLimitInterface
{
const STATUS_DELETED = 0;
@@ -339,4 +340,23 @@ class Customer extends BaseFitnessActiveRecord implements IdentityInterface
}
}
public function getRateLimit($request, $action)
{
return [1000,3600];
// TODO: Implement getRateLimit() method.
}
public function loadAllowance($request, $action)
{
// TODO: Implement loadAllowance() method.
return [1000,3600];
}
public function saveAllowance($request, $action, $allowance, $timestamp)
{
// TODO: Implement saveAllowance() method.
return [1000,3600];
}
}

View File

@@ -22,12 +22,29 @@ use yii\helpers\ArrayHelper;
* @property integer id_ticket_current
* @property integer card_flag
* @property integer flag_out
* @property integer version
*/
class DoorLog extends \yii\db\ActiveRecord
{
public static $SOURCE_APP_FORGO_VILLA = "forgo_villa";
public static $SOURCE_APP_FITNESS_ADMIN = "fitness_admin";
public static $SOURCE_APP_FORGO_VILLA = "forgo_villa";
public static $SOURCE_APP_FITNESS_ADMIN = "fitness_admin";
public static $DIRECTION_OUT_MANUAL_READ_KEY_ASSIGNED = -2; // "Kézi olvasás/Kulcs ki",
public static $DIRECTION_IN_MANUAL_READ_KEY_UNASSIGNED = -1; // "Kézi olvasás/Kulcs vissza",
public static $DIRECTION_ALL_MANUAL_READ = 0; // "Kézi olvasás",
public static $DIRECTION_OUT_WITHOUT_MOVE = 1; // "KI olvastatás mozgás nélkül",
public static $DIRECTION_IN_WITHOUT_MOVE = 3; // "BE olvastatás mozgás nélkül",
public static $DIRECTION_OUT = 5; // "KI mozgás",
public static $DIRECTION_IN = 7; // "BE mozgás",
public static $DIRECTION_OUT_ERROR_KEY_ASSIGNED = 9; // "KI olvastatás, van érvényes öltöző kulcs (nem enged)",
public static $DIRECTION_IN_ERROR_KEY_MISSING = 11; // "BE olvastatás, nincs érvényes öltöző kulcs (nem enged)",
public static $DIRECTION_OUT_NO_TICKET = 17; // "Bérlet érvényességi időn kívüli KI olvastatás (nem enged)",
public static $DIRECTION_IN_NO_TICKET = 19; // "Bérlet érvényességi időn kívüli BE olvastatás (nem enged)",
public static $DIRECTION_ALL_EMERGENCY = 128; // "Vésznyitás",
public static $DIRECTION_ALL_CARD_BLOCKED = 256; // "Kártya tiltva -> információ mező",
/**
* @inheritdoc
*/
@@ -35,16 +52,21 @@ class DoorLog extends \yii\db\ActiveRecord
{
return 'door_log';
}
public function behaviors()
{
return ArrayHelper::merge( [
[
'class' => TimestampBehavior::className(),
'value' => function(){ return date('Y-m-d H:i:s' ); },
'updatedAtAttribute' => false,
]
], parent::behaviors());
return ArrayHelper::merge([
[
'class' => TimestampBehavior::className(),
'value' => function ($event) {
if ( isset($event->sender->created_at) ){
return $event->sender->created_at;
}
return date('Y-m-d H:i:s');
},
'updatedAtAttribute' => false,
]
], parent::behaviors());
}
/**
@@ -75,133 +97,147 @@ class DoorLog extends \yii\db\ActiveRecord
'source_app' => Yii::t('common/door_log', 'Eszköz'),
];
}
public function getCustomer(){
return $this->hasOne( Customer::className(), ["id_customer" =>"id_customer" ] );
}
public function getCustomerName(){
$result = "";
if (isset($this->customer)){
$result = $this->customer->name;
}
return $result;
}
public function getCard(){
return $this->hasOne( Card::className(), ["id_card" =>"id_card" ] );
}
public function getCardNumber(){
$result = "";
if (isset($this->card)){
$result = $this->card->number;
}
return $result;
}
public function getKey(){
return $this->hasOne( Key::className(), ["id_key" =>"id_key" ] );
}
public function getKeyNumber(){
$result = "";
if (isset($this->key)){
$result = $this->key->number;
}
return $result;
}
public function getDirectionName(){
$result = "";
if ( $this->source_app == 'forgo_villa'){
if (isset($this->direction)){
$result = Helper::getArrayValue(self::getDirectionTypes() , $this->direction, "-");
}
}else{
$result = "Kézi olvasás";
}
return $result;
}
public static function getSourceAppName($source_app){
$result = "";
switch ($source_app){
case self::$SOURCE_APP_FITNESS_ADMIN :
$result = "Recepciós alkalmazás";
break;
case self::$SOURCE_APP_FORGO_VILLA:
$result = "Forgó villa";
break;
}
return $result;
}
public static function getDirectionTypes( ){
return [
-2 => "Kézi olvasás/Kulcs ki",
-1 => "Kézi olvasás/Kulcs vissza",
0 => "Kézi olvasás",
1 => "KI olvastatás mozgás nélkül",
3 => "BE olvastatás mozgás nélkül",
5 => "KI mozgás",
7 => "BE mozgás",
9 => "KI olvastatás, van érvényes öltöző kulcs (nem enged)",
11 => "BE olvastatás, nincs érvényes öltöző kulcs (nem enged)",
17 => "Bérlet érvényességi időn kívüli KI olvastatás (nem enged)",
19 => "Bérlet érvényességi időn kívüli BE olvastatás (nem enged)",
128 => "Vésznyitás",
256 => "Kártya tiltva -> információ mező",
];
}
public static function getCardFlagTexts( ){
return [
0 => "Kártya érvényes bérlettel",
1 => "Nincs érvényes bérlet",
2 => "Kártya inaktív/Érvényes bérlet",
3 => "Kártya inaktív/Nincs érvényes bérlet"
];
}
public function getCustomer()
{
return $this->hasOne(Customer::className(), ["id_customer" => "id_customer"]);
}
public static function mkDoorLog($direction,$card,$customer = null,$key = null){
public function getCustomerName()
{
$result = "";
if (isset($this->customer)) {
$result = $this->customer->name;
}
return $result;
}
if ( !Helper::isKeyToggleDoorLogEnabled() ){
return;
public function getCard()
{
return $this->hasOne(Card::className(), ["id_card" => "id_card"]);
}
public function getCardNumber()
{
$result = "";
if (isset($this->card)) {
$result = $this->card->number;
}
return $result;
}
public function getKey()
{
return $this->hasOne(Key::className(), ["id_key" => "id_key"]);
}
public function getKeyNumber()
{
$result = "";
if (isset($this->key)) {
$result = $this->key->number;
}
return $result;
}
public function getDirectionName()
{
$result = "";
if ($this->source_app == 'forgo_villa') {
if (isset($this->direction)) {
$result = Helper::getArrayValue(self::getDirectionTypes(), $this->direction, "-");
}
} else {
$result = "Kézi olvasás";
}
return $result;
}
public static function getSourceAppName($source_app)
{
$result = "";
switch ($source_app) {
case self::$SOURCE_APP_FITNESS_ADMIN :
$result = "Recepciós alkalmazás";
break;
case self::$SOURCE_APP_FORGO_VILLA:
$result = "Forgó villa";
break;
}
return $result;
}
public static function getDirectionTypes()
{
return [
-2 => "Kézi olvasás/Kulcs ki",
-1 => "Kézi olvasás/Kulcs vissza",
0 => "Kézi olvasás",
1 => "KI olvastatás mozgás nélkül",
3 => "BE olvastatás mozgás nélkül",
5 => "KI mozgás",
7 => "BE mozgás",
9 => "KI olvastatás, van érvényes öltöző kulcs (nem enged)",
11 => "BE olvastatás, nincs érvényes öltöző kulcs (nem enged)",
17 => "Bérlet érvényességi időn kívüli KI olvastatás (nem enged)",
19 => "Bérlet érvényességi időn kívüli BE olvastatás (nem enged)",
128 => "Vésznyitás",
256 => "Kártya tiltva -> információ mező",
];
}
public static function getCardFlagTexts()
{
return [
0 => "Kártya érvényes bérlettel",
1 => "Nincs érvényes bérlet",
2 => "Kártya inaktív/Érvényes bérlet",
3 => "Kártya inaktív/Nincs érvényes bérlet"
];
}
public static function mkDoorLog($direction, $card, $customer = null, $key = null)
{
if (!Helper::isKeyToggleDoorLogEnabled()) {
return;
}
$dlog = new DoorLog();
$dlog->id_card = $card->id_card;
$dlog = new DoorLog();
$dlog->id_card = $card->id_card;
if ( isset($customer)){
$dlog->id_customer = $customer->id_customer;
}
if (isset($customer)) {
$dlog->id_customer = $customer->id_customer;
}
if ( isset($key)){
$dlog->id_key = $key->id_key;
}
$dlog->direction = $direction;
$dlog->type = $card->type;
$dlog->source_app = DoorLog::$SOURCE_APP_FITNESS_ADMIN;
if (isset($key)) {
$dlog->id_key = $key->id_key;
}
$dlog->direction = $direction;
$dlog->type = $card->type;
$dlog->source_app = DoorLog::$SOURCE_APP_FITNESS_ADMIN;
$dlog->id_account = Account::readDefault();
$dlog->id_account = Account::readDefault();
if ( $dlog->direction == 0){
$dlog->card_flag = $card->validity;
}else{
$dlog->card_flag = -1;
}
if ($dlog->direction == 0) {
$dlog->card_flag = $card->validity;
} else {
$dlog->card_flag = -1;
}
$dlog->created_at = date('Y-m-d H:i:s');
$dlog->save(false);
}
$dlog->created_at = date('Y-m-d H:i:s');
$dlog->save(false);
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace common\models;
use Yii;
use common\components\Helper;
use yii\behaviors\TimestampBehavior;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "door_log".
*
* @property integer $id_door_log
* @property integer $id_card
* @property integer $id_customer
* @property integer $id_key
* @property integer $direction
* @property integer $type
* @property integer $id_account
* @property string $created_at
* @property string $source_app
* @property integer id_ticket_current
* @property integer card_flag
* @property integer flag_out
*/
class DoorLogForTest extends DoorLog
{
public function behaviors()
{
return [];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[
['id_card', 'id_customer', 'id_key', 'direction', 'type', 'id_ticket_current'], 'integer'
],
[['created_at'], 'string'],
[['created_at'], 'required'],
];
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace common\models;
class HuBankAccountValidator
{
public function validate($bankAccount){
if ( !isset($bankAccount)){
// \Yii::error("HuBankAccountValidator: bank account is null");
return false;
}
$stripedBankAccount = preg_replace('/\s+/', '', $bankAccount);
if ( !(strlen($stripedBankAccount) == 24 || strlen($stripedBankAccount) == 16)){
// \Yii::error("HuBankAccountValidator: bank account length is invalid");
return false;
}
$arrayOfNumbers = str_split($stripedBankAccount);
$multipliers = [9,7,3,1];
$groups = [0,0,0];
for ( $i = 0; $i < count($arrayOfNumbers); $i++ ) {
$number = $arrayOfNumbers[$i];
$multiplier = $multipliers[$i % 4];
$total = $multiplier * $number;
$groups[intval($i / 8)] += $total ;
}
$sumOfGroups = 0;
foreach ($groups as $group){
$sumOfGroups += $group;
}
$mod = $sumOfGroups % 10;
if ( $mod > 0 ){
// \Yii::error("HuBankAccountValidator: bank account groups are invalid: " . $groups[0] .",". $groups[1] . "," . $groups[2],true);
return false;
}
return true;
}
}

View File

@@ -33,67 +33,71 @@ use yii\helpers\Console;
*/
class Log extends BaseFitnessActiveRecord
{
public static $TYPE_INFO = 10;
public static $TYPE_ERR = 20;
public static $TYPE_TICKET_USAGE_FIRST = 30;
public static $TYPE_TICKET_USAGE_MULTIPLE = 40;
public static $TYPE_LOGIN = 50;
public static $TYPE_DEFAULT_ACCOUNT= 60;
public static $TYPE_CREATE_CUSTOMER= 70;
public static $TYPE_PROCUREMENT_UPDATE = 80;
public static $TYPE_TICKET_COUNT_MOVE_OUT = 90;
public static $TYPE_WASTE = 100;
public static $TYPE_NEWSLETTER_SUBSCRIBE = 110;
public static $TYPE_NEWSLETTER_UNSUBSCRIBE = 120;
public static $TYPE_NEWSLETTER_SENT = 130;
public static $TYPE_TICKET_EXPIRE_SENT = 140;
public static $TYPE_NEWSLETTER_SEND_START = 150;
public static $TYPE_NEWSLETTER_SEND_END = 160;
public static $TYPE_KEY_ASSIGN = 170;
public static $TYPE_KEY_UNASSIGN = 180;
public static $TYPE_TOWEL_IN = 190;
public static $TYPE_TOWEL_OUT = 200;
public static $TYPE_CRUD = 210;
public static $TYPE_TICKET_UPDATED_BY_ADMIN = 220;
public static $TYPE_INFO = 10;
public static $TYPE_ERR = 20;
public static $TYPE_TICKET_USAGE_FIRST = 30;
public static $TYPE_TICKET_USAGE_MULTIPLE = 40;
public static $TYPE_LOGIN = 50;
public static $TYPE_DEFAULT_ACCOUNT = 60;
public static $TYPE_CREATE_CUSTOMER = 70;
public static $TYPE_PROCUREMENT_UPDATE = 80;
public static $TYPE_TICKET_COUNT_MOVE_OUT = 90;
public static $TYPE_WASTE = 100;
public static $TYPE_NEWSLETTER_SUBSCRIBE = 110;
public static $TYPE_NEWSLETTER_UNSUBSCRIBE = 120;
public static $TYPE_NEWSLETTER_SENT = 130;
public static $TYPE_TICKET_EXPIRE_SENT = 140;
public static $TYPE_NEWSLETTER_SEND_START = 150;
public static $TYPE_NEWSLETTER_SEND_END = 160;
public static $TYPE_KEY_ASSIGN = 170;
public static $TYPE_KEY_UNASSIGN = 180;
public static $TYPE_TOWEL_IN = 190;
public static $TYPE_TOWEL_OUT = 200;
public static $TYPE_CRUD = 210;
public static $TYPE_TICKET_UPDATED_BY_ADMIN = 220;
public static $TYPE_MOBILE_DEVICE_STATUS = 230;
public static function getTypes(){
return [
Log::$TYPE_INFO => "Info",
Log::$TYPE_ERR => "Hiba",
Log::$TYPE_TICKET_USAGE_FIRST => "Bérlet használat",
Log::$TYPE_TICKET_USAGE_MULTIPLE => "Többszöri bérlet használat",
Log::$TYPE_LOGIN => "Bejelentkezés",
Log::$TYPE_DEFAULT_ACCOUNT=> "Alapértelmezett kassza",
Log::$TYPE_CREATE_CUSTOMER=> "Új vendég",
Log::$TYPE_PROCUREMENT_UPDATE => "Beszerzés módosítás",
Log::$TYPE_TICKET_COUNT_MOVE_OUT => "Ki mozgás",
Log::$TYPE_WASTE => "Selejt",
Log::$TYPE_NEWSLETTER_SUBSCRIBE => "Feliratkozás hirlevélre",
Log::$TYPE_NEWSLETTER_UNSUBSCRIBE => "Leiratkozás hírlevélről",
Log::$TYPE_NEWSLETTER_SENT => "Hirlevél elküldve",
Log::$TYPE_TICKET_EXPIRE_SENT => "Bérlet lejáart figyelmeztetés elküldve",
Log::$TYPE_NEWSLETTER_SEND_START => "Hirlevél küldés start",
Log::$TYPE_NEWSLETTER_SEND_END => "Hirlevél küldés vége",
Log::$TYPE_KEY_ASSIGN => "Kulcs kiadás",
Log::$TYPE_KEY_UNASSIGN => "Kulcs visszaadás",
Log::$TYPE_TOWEL_IN => "Törölköző ki",
Log::$TYPE_TOWEL_OUT => "Törölköző vissza",
Log::$TYPE_CRUD => "CRUD",
Log::$TYPE_TICKET_UPDATED_BY_ADMIN => "Bérlet módosítás"
public static function getTypes()
{
return [
Log::$TYPE_INFO => "Info",
Log::$TYPE_ERR => "Hiba",
Log::$TYPE_TICKET_USAGE_FIRST => "Bérlet használat",
Log::$TYPE_TICKET_USAGE_MULTIPLE => "Többszöri bérlet használat",
Log::$TYPE_LOGIN => "Bejelentkezés",
Log::$TYPE_DEFAULT_ACCOUNT => "Alapértelmezett kassza",
Log::$TYPE_CREATE_CUSTOMER => "Új vendég",
Log::$TYPE_PROCUREMENT_UPDATE => "Beszerzés módosítás",
Log::$TYPE_TICKET_COUNT_MOVE_OUT => "Ki mozgás",
Log::$TYPE_WASTE => "Selejt",
Log::$TYPE_NEWSLETTER_SUBSCRIBE => "Feliratkozás hirlevélre",
Log::$TYPE_NEWSLETTER_UNSUBSCRIBE => "Leiratkozás hírlevélről",
Log::$TYPE_NEWSLETTER_SENT => "Hirlevél elküldve",
Log::$TYPE_TICKET_EXPIRE_SENT => "rlet lejáart figyelmeztetés elküldve",
Log::$TYPE_NEWSLETTER_SEND_START => "Hirlevél küldés start",
Log::$TYPE_NEWSLETTER_SEND_END => "Hirlevél küldés vége",
Log::$TYPE_KEY_ASSIGN => "Kulcs kiadás",
Log::$TYPE_KEY_UNASSIGN => "Kulcs visszaadás",
Log::$TYPE_TOWEL_IN => "Törölköző ki",
Log::$TYPE_TOWEL_OUT => "Törölköző vissza",
Log::$TYPE_CRUD => "CRUD",
Log::$TYPE_TICKET_UPDATED_BY_ADMIN => "Bérlet módosítás",
Log::$TYPE_MOBILE_DEVICE_STATUS => "Mobil eszköz státusz"
];
}
public function getTypeName(){
$types = Log::getTypes();
return Helper::getArrayValue($types,$this->type,null);
}
/**
public function getTypeName()
{
$types = Log::getTypes();
return Helper::getArrayValue($types, $this->type, null);
}
/**
* @inheritdoc
*/
public static function tableName()
@@ -134,79 +138,89 @@ class Log extends BaseFitnessActiveRecord
'id_door_log' => Yii::t('common/log', 'Kapu log'),
'created_at' => Yii::t('common/log', 'Dátum idő'),
'updated_at' => Yii::t('common/log', 'Módosítás'),
'start' => 'Időszak kezdete',
'end' => 'Időszak vége'
'start' => 'Időszak kezdete',
'end' => 'Időszak vége'
];
}
public static function info($message ){
self::log(['type' =>self::$TYPE_INFO, 'message' => $message]);
public static function info($message)
{
self::log(['type' => self::$TYPE_INFO, 'message' => $message]);
}
/**
* example
* Log::log([
'type' =>Log::$TYPE_LOGIN,
'message' => $message
]);
* 'type' =>Log::$TYPE_LOGIN,
* 'message' => $message
* ]);
* @param array $config
*/
public static function log( $config ){
$model = new Log($config);
$model->app = \Yii::$app->name;
$model->url = Url::canonical();
$model->id_user = \Yii::$app->user->id;
$model->save(false);
public static function log($config)
{
$model = new Log($config);
$model->app = \Yii::$app->name;
$model->url = Url::canonical();
$model->id_user = \Yii::$app->user->id;
$model->save(false);
}
/**
* create a log from the console app
* */
public static function logC( $config ){
$model = new Log($config);
$model->app = "Fitness rendszer";
$model->url = "console";
$model->id_user = 1;
$model->save(false);
public static function logC($config)
{
$model = new Log($config);
$model->app = "Fitness rendszer";
$model->url = "console";
$model->id_user = 1;
$model->save(false);
}
public function getUser(){
return $this->hasOne( User::className(), ["id" =>"id_user" ] );
public function getUser()
{
return $this->hasOne(User::className(), ["id" => "id_user"]);
}
public function getTicket(){
return $this->hasOne( Ticket::className(), ["id_ticket" =>"id_ticket" ] );
public function getTicket()
{
return $this->hasOne(Ticket::className(), ["id_ticket" => "id_ticket"]);
}
public function getCustomer(){
return $this->hasOne( Customer::className(), ["id_customer" =>"id_customer" ] );
public function getCustomer()
{
return $this->hasOne(Customer::className(), ["id_customer" => "id_customer"]);
}
public function getMoneyMovement(){
return $this->hasOne( MoneyMovement::className(), ["id_money_movement" =>"id_money_movement" ] );
public function getMoneyMovement()
{
return $this->hasOne(MoneyMovement::className(), ["id_money_movement" => "id_money_movement"]);
}
public function getUserName(){
public function getUserName()
{
$user = $this->user;
if ( isset($user)){
if (isset($user)) {
return $user->username;
}
return null;
}
public function getCustomerName(){
public function getCustomerName()
{
$customer = $this->customer;
if ( isset($customer)){
if (isset($customer)) {
return $customer->name;
}
return null;
}
public function getTicketName(){
public function getTicketName()
{
$ticket = $this->ticket;
if ( isset($ticket)){
if (isset($ticket)) {
return $ticket->ticketTypeName;
}
return null;

View File

@@ -0,0 +1,134 @@
<?php
namespace common\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\helpers\ArrayHelper;
use yii\web\IdentityInterface;
/**
* This is the model class for table "mobile_device".
*
* @property integer $id
* @property integer $id_card
* @property string $status
* @property string $device_identifier
* @property string $device_name
* @property string $activated_at
* @property string $created_at
* @property string $updated_at
*/
class MobileDevice extends \yii\db\ActiveRecord implements IdentityInterface
{
const STATUS_ACTIVE = 'active';
const STATUS_INACTIVE = 'inactive';
const STATUS_DELETED_MANUAL = 'deleted_manual';
const STATUS_DELETED_SYSTEM = 'deleted_system';
/**
* @inheritdoc
*/
public static function tableName()
{
return 'mobile_device';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
// [['id_card'], 'integer'],
// [['activated_at', 'created_at', 'updated_at'], 'safe'],
// [['created_at', 'updated_at'], 'required'],
// [['status'], 'string', 'max' => 20],
// [['device_identifier'], 'string', 'max' => 255]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('common/mobiledevice', 'ID'),
'id_card' => Yii::t('common/mobiledevice', 'Id Card'),
'status' => Yii::t('common/mobiledevice', 'Status'),
'device_identifier' => Yii::t('common/mobiledevice', 'Device Identifier'),
'device_name' => Yii::t('common/mobiledevice', 'Device Name'),
'activated_at' => Yii::t('common/mobiledevice', 'Activated At'),
'created_at' => Yii::t('common/mobiledevice', 'Created At'),
'updated_at' => Yii::t('common/mobiledevice', 'Updated At'),
];
}
public function behaviors()
{
return ArrayHelper::merge( [
[
'class' => TimestampBehavior::className(),
'value' => function(){ return date('Y-m-d H:i:s' ); }
]
],
parent::behaviors());
}
public static function toStatusHumanReadable($status){
$result = "";
switch ($status){
case self::STATUS_ACTIVE:
$result ='Aktív';
break;
case self::STATUS_DELETED_MANUAL:
$result ='Törölve (m)';
break;
case self::STATUS_DELETED_SYSTEM:
$result ='Törölve (r)';
break;
case self::STATUS_INACTIVE:
$result ='Inaktív';
break;
}
return $result;
}
public static function findIdentity($id)
{
self::findOne(['id' => $id]);
}
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
public function getId()
{
return $this->id;
}
public function getAuthKey()
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
public function validateAuthKey($authKey)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
public function getCard()
{
return $this->hasOne(Card::class, [
'id_card' => 'id_card'
]);
}
}

View File

@@ -7,7 +7,7 @@ use yii\helpers\ArrayHelper;
use yii\behaviors\TimestampBehavior;
use common\components\AccountAwareBehavior;
use common\components\UserAwareBehavior;
use yii\base\Object;
use yii\base\BaseObject;
use common\models\Transfer;
/**

View File

@@ -6,7 +6,7 @@ use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Transfer;
use yii\base\Object;
use yii\base\BaseObject;
use yii\db\Query;
use yii\db\Expression;
use common\models\Account;

View File

@@ -6,7 +6,7 @@ use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Transfer;
use yii\base\Object;
use yii\base\BaseObject;
use yii\db\Query;
use yii\db\Expression;
use common\models\Account;

View File

@@ -0,0 +1,71 @@
<?php
namespace common\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "virtual_key".
*
* @property integer $id
* @property integer $id_card
* @property integer $id_key
* @property integer $number
* @property string $direction_in_at
* @property string $direction_out_at
* @property string $created_at
* @property string $updated_at
*/
class VirtualKey extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'virtual_key';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id_card', 'id_key'], 'integer'],
[[ 'created_at', 'updated_at'], 'required'],
[[ 'direction_in_at', 'created_at', 'updated_at'], 'safe']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('common/virtualkey', 'ID'),
'id_card' => Yii::t('common/virtualkey', 'Id Card'),
'id_key' => Yii::t('common/virtualkey', 'Id Key'),
'direction_in_at' => Yii::t('common/virtualkey', 'Direction In At'),
'direction_out_at' => Yii::t('common/virtualkey', 'Direction Out At'),
'created_at' => Yii::t('common/virtualkey', 'Created At'),
'updated_at' => Yii::t('common/virtualkey', 'Updated At'),
];
}
public function behaviors()
{
return ArrayHelper::merge([
[
'class' => TimestampBehavior::className(),
'value' => function () {
return date('Y-m-d H:i:s');
}
]
],
parent::behaviors());
}
}